예제 #1
0
        public void Resulting_HttpContent_Has_Json_Media_Type()
        {
            var serializer = new JsonHttpContentSerializer();
            var content    = serializer.Serialize(new object(), null);

            content.Headers.ContentType.MediaType.Should().Be(MediaType.ApplicationJson);
        }
예제 #2
0
        public void Uses_Specified_Encoding_In_Charset(string encodingStr, string expectedCharset)
        {
            var encoding   = Encoding.GetEncoding(encodingStr);
            var serializer = new JsonHttpContentSerializer();
            var content    = serializer.Serialize(new object(), encoding);

            content.Headers.ContentType.CharSet.Should().Be(expectedCharset);
        }
예제 #3
0
        public async Task Throws_HttpContentSerializationException_For_Invalid_Json(string json)
        {
            var content    = new StringContent(json);
            var serializer = new JsonHttpContentSerializer();

            Func <Task> testCode = async() => await serializer.DeserializeAsync(content, typeof(MockDto));

            await testCode.Should().ThrowAsync <HttpContentSerializationException>();
        }
예제 #4
0
        public async Task Serializes_Object(MockDto dto)
        {
            var serializer = new JsonHttpContentSerializer();
            var serialized = serializer.Serialize(dto, encoding: null);
            var str        = await serialized.ReadAsStringAsync();

            var expected = JsonConvert.SerializeObject(dto);

            str.Should().Be(expected);
        }
예제 #5
0
        public async Task Deserializes_Object(string json)
        {
            var content      = new StringContent(json);
            var serializer   = new JsonHttpContentSerializer();
            var deserialized = await serializer.DeserializeAsync(content, typeof(MockDto));

            var expected = JsonConvert.DeserializeObject <MockDto>(json);

            deserialized.Should().BeEquivalentTo(expected);
        }
예제 #6
0
    public async Task <int> RunAsync(IReadOnlyList <string> args)
    {
        const string defaultUrl = "http://localhost:4117/";

        var argsReader = new ArgsReader(args);

        if (argsReader.ReadFlag("?|h|help"))
        {
            throw new ArgsReaderException("");
        }

        var serializerName           = argsReader.ReadOption("serializer")?.ToLowerInvariant();
        ServiceSerializer serializer = serializerName switch
        {
            null or "systemtextjson" => SystemTextJsonServiceSerializer.Instance,
            "newtonsoftjson" or "obsoletejson" => NewtonsoftJsonServiceSerializer.Instance,
                          _ => throw new ArgsReaderException("Unsupported serializer."),
        };
        var contentSerializer = HttpContentSerializer.Create(serializer);

#pragma warning disable CS0618 // Type or member is obsolete
        if (serializerName is "obsoletejson")
        {
            contentSerializer = new JsonHttpContentSerializer(new JsonHttpContentSerializerSettings {
                ForceAsyncIO = true
            });
        }
#pragma warning restore CS0618 // Type or member is obsolete

        var jsonSerializer = serializer as JsonServiceSerializer ?? NewtonsoftJsonServiceSerializer.Instance;
        var tests          = ConformanceTestsInfo.FromJson(m_testsJson, jsonSerializer).Tests !;

        var command = argsReader.ReadArgument();

        if (command == "host")
        {
            var url = argsReader.ReadOption("url") ?? defaultUrl;
            argsReader.VerifyComplete();

            var service = new ConformanceApiService(
                new ConformanceApiServiceSettings
            {
                Tests          = tests,
                JsonSerializer = jsonSerializer,
            });

            await new WebHostBuilder()
            .UseKestrel(options => options.AllowSynchronousIO = serializerName is "newtonsoftjson")
            .UseUrls(url)
            .Configure(app => app.Run(httpContext => HostAsync(httpContext, service, contentSerializer)))
            .Build()
            .RunAsync();

            return(0);
        }

        if (command == "test")
        {
            var baseUri   = new Uri(argsReader.ReadOption("url") ?? defaultUrl);
            var testNames = argsReader.ReadArguments();
            argsReader.VerifyComplete();

            var api = new HttpClientConformanceApi(
                new HttpClientServiceSettings
            {
                BaseUri           = baseUri,
                ContentSerializer = contentSerializer,
            });

            var tester = new ConformanceApiTester(
                new ConformanceApiTesterSettings
            {
                Tests      = tests,
                Api        = api,
                HttpClient = new HttpClient {
                    BaseAddress = baseUri
                },
                JsonSerializer = jsonSerializer,
            });

            var results = new List <ConformanceTestResult>();

            if (testNames.Count == 0)
            {
                results.AddRange((await tester.RunAllTestsAsync()).Results);
            }
            else
            {
                foreach (var testName in testNames)
                {
                    var testInfo = tests.SingleOrDefault(x => x.Test == testName);
                    if (testInfo == null)
                    {
                        Console.WriteLine($"Test not found: {testName}");
                        return(-1);
                    }

                    results.Add(await tester.RunTestAsync(testInfo));
                }
            }

            var failureCount = 0;
            foreach (var result in results.Where(x => x.Status == ConformanceTestStatus.Fail))
            {
                Console.WriteLine($"{result.TestName} fail: {result.Message}");
                failureCount++;
            }

            Console.WriteLine($"{results.Count} tests: {results.Count - failureCount} passed, {failureCount} failed.");

            return(failureCount == 0 ? 0 : 1);
        }

        if (command == "fsd")
        {
            var outputPath   = argsReader.ReadOption("output");
            var shouldVerify = argsReader.ReadFlag("verify");
            argsReader.VerifyComplete();

            return(WriteText(path: outputPath, contents: m_fsdText, shouldVerify: shouldVerify));
        }

        if (command == "json")
        {
            var outputPath   = argsReader.ReadOption("output");
            var shouldVerify = argsReader.ReadFlag("verify");
            argsReader.VerifyComplete();

            return(WriteText(path: outputPath, contents: m_testsJson, shouldVerify: shouldVerify));
        }

        if (command != null)
        {
            throw new ArgsReaderException($"Invalid command: {command}");
        }

        throw new ArgsReaderException("Missing command.");
    }