<commit_before>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;

namespace System.Net.Http.Functional.Tests
{
    using Configuration = System.Net.Test.Common.Configuration;

    // Note:  Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
    // to separately Dispose (or have a 'using' statement) for the handler.
    [ActiveIssue(29802, TargetFrameworkMonikers.Uap)]
    public abstract class PostScenarioTest : HttpClientTestBase
    {
        private const string ExpectedContent = "Test contest";
        private const string UserName = "user1";
        private const string Password = "<PASSWORD>";
        private static readonly Uri BasicAuthServerUri =
            Configuration.Http.BasicAuthUriForCreds(false, UserName, Password);
        private static readonly Uri SecureBasicAuthServerUri =
            Configuration.Http.BasicAuthUriForCreds(true, UserName, Password);

        private readonly ITestOutputHelper _output;

        public static readonly object[][] EchoServers = Configuration.Http.EchoServers;

        public static readonly object[][] BasicAuthEchoServers =
            new object[][]
                {
                    new object[] { BasicAuthServerUri },
                    new object[] { SecureBasicAuthServerUri }
                };

        public PostScenarioTest(ITestOutputHelper output)
        {
            _output = output;
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostNoContentUsingContentLengthSemantics_Success(Uri serverUri)
        {
            await PostHelper(serverUri, string.Empty, null,
                useContentLengthUpload: true, useChunkedEncodingUpload: false);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostEmptyContentUsingContentLengthSemantics_Success(Uri serverUri)
        {
            await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
                useContentLengthUpload: true, useChunkedEncodingUpload: false);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostEmptyContentUsingChunkedEncoding_Success(Uri serverUri)
        {
            await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
                useContentLengthUpload: false, useChunkedEncodingUpload: true);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostEmptyContentUsingConflictingSemantics_Success(Uri serverUri)
        {
            await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
                useContentLengthUpload: true, useChunkedEncodingUpload: true);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostUsingContentLengthSemantics_Success(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
                useContentLengthUpload: true, useChunkedEncodingUpload: false);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostUsingChunkedEncoding_Success(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
                useContentLengthUpload: false, useChunkedEncodingUpload: true);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostSyncBlockingContentUsingChunkedEncoding_Success(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new SyncBlockingContent(ExpectedContent),
                useContentLengthUpload: false, useChunkedEncodingUpload: true);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostRepeatedFlushContentUsingChunkedEncoding_Success(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new RepeatedFlushContent(ExpectedContent),
                useContentLengthUpload: false, useChunkedEncodingUpload: true);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostUsingUsingConflictingSemantics_UsesChunkedSemantics(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
                useContentLengthUpload: true, useChunkedEncodingUpload: true);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx behaves differently and will buffer content and use 'Content-Length' semantics")]
        public async Task PostUsingNoSpecifiedSemantics_UsesChunkedSemantics(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
                useContentLengthUpload: false, useChunkedEncodingUpload: false);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory]
        [InlineData(5 * 1024)]
        [InlineData(63 * 1024)]
        public async Task PostLongerContentLengths_UsesChunkedSemantics(int contentLength)
        {
            var rand = new Random(42);
            var sb = new StringBuilder(contentLength);
            for (int i = 0; i < contentLength; i++)
            {
                sb.Append((char)(rand.Next(0, 26) + 'a'));
            }
            string content = sb.ToString();

            await PostHelper(Configuration.Http.RemoteEchoServer, content, new StringContent(content),
                useContentLengthUpload: true, useChunkedEncodingUpload: false);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(BasicAuthEchoServers))]
        public async Task PostRewindableContentUsingAuth_NoPreAuthenticate_Success(Uri serverUri)
        {
            HttpContent content = CustomContent.Create(ExpectedContent, true);
            var credential = new NetworkCredential(UserName, Password);
            await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, false);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(BasicAuthEchoServers))]
        public async Task PostNonRewindableContentUsingAuth_NoPreAuthenticate_ThrowsHttpRequestException(Uri serverUri)
        {
            HttpContent content = CustomContent.Create(ExpectedContent, false);
            var credential = new NetworkCredential(UserName, Password);
            await Assert.ThrowsAsync<HttpRequestException>(() => 
                PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: false));
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(BasicAuthEchoServers))]
        public async Task PostNonRewindableContentUsingAuth_PreAuthenticate_Success(Uri serverUri)
        {
            if (IsWinHttpHandler)
            {
                // Issue #9228
                return;
            }

            HttpContent content = CustomContent.Create(ExpectedContent, false);
            var credential = new NetworkCredential(UserName, Password);
            await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: true);
        }

        [OuterLoop] // TODO: Issue #11345
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostAsync_EmptyContent_ContentTypeHeaderNotSent(Uri serverUri)
        {
            using (HttpClient client = CreateHttpClient())
            using (HttpResponseMessage response = await client.PostAsync(serverUri, null))
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                bool sentContentType = TestHelper.JsonMessageContainsKey(responseContent, "Content-Type");

                Assert.False(sentContentType);<commit_msg>Add HttpClient test for sending rewindable content stream (#29971)<commit_after>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.IO;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;

namespace System.Net.Http.Functional.Tests
{
    using Configuration = System.Net.Test.Common.Configuration;

    // Note:  Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
    // to separately Dispose (or have a 'using' statement) for the handler.
    [ActiveIssue(29802, TargetFrameworkMonikers.Uap)]
    public abstract class PostScenarioTest : HttpClientTestBase
    {
        private const string ExpectedContent = "Test contest";
        private const string UserName = "user1";
        private const string Password = "<PASSWORD>";
        private static readonly Uri BasicAuthServerUri =
            Configuration.Http.BasicAuthUriForCreds(false, UserName, Password);
        private static readonly Uri SecureBasicAuthServerUri =
            Configuration.Http.BasicAuthUriForCreds(true, UserName, Password);

        private readonly ITestOutputHelper _output;

        public static readonly object[][] EchoServers = Configuration.Http.EchoServers;

        public static readonly object[][] BasicAuthEchoServers =
            new object[][]
                {
                    new object[] { BasicAuthServerUri },
                    new object[] { SecureBasicAuthServerUri }
                };

        public PostScenarioTest(ITestOutputHelper output)
        {
            _output = output;
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostRewindableStreamContentMultipleTimes_StreamContentFullySent(Uri serverUri)
        {
            const string requestBody = "ABC";

            using (var client = new HttpClient())
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(requestBody)))
            {
                var content = new StreamContent(ms);

                for (int i = 1; i <= 3; i++)
                {
                    HttpResponseMessage response = await client.PutAsync(serverUri, content);
                    Assert.Equal(requestBody.Length, ms.Position); // Stream left at end after send.

                    string responseBody = await response.Content.ReadAsStringAsync();
                    _output.WriteLine(responseBody);
                    Assert.True(TestHelper.JsonMessageContainsKeyValue(responseBody, "BodyContent", requestBody));
                }
            }
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostNoContentUsingContentLengthSemantics_Success(Uri serverUri)
        {
            await PostHelper(serverUri, string.Empty, null,
                useContentLengthUpload: true, useChunkedEncodingUpload: false);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostEmptyContentUsingContentLengthSemantics_Success(Uri serverUri)
        {
            await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
                useContentLengthUpload: true, useChunkedEncodingUpload: false);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostEmptyContentUsingChunkedEncoding_Success(Uri serverUri)
        {
            await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
                useContentLengthUpload: false, useChunkedEncodingUpload: true);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostEmptyContentUsingConflictingSemantics_Success(Uri serverUri)
        {
            await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
                useContentLengthUpload: true, useChunkedEncodingUpload: true);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostUsingContentLengthSemantics_Success(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
                useContentLengthUpload: true, useChunkedEncodingUpload: false);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostUsingChunkedEncoding_Success(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
                useContentLengthUpload: false, useChunkedEncodingUpload: true);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostSyncBlockingContentUsingChunkedEncoding_Success(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new SyncBlockingContent(ExpectedContent),
                useContentLengthUpload: false, useChunkedEncodingUpload: true);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostRepeatedFlushContentUsingChunkedEncoding_Success(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new RepeatedFlushContent(ExpectedContent),
                useContentLengthUpload: false, useChunkedEncodingUpload: true);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostUsingUsingConflictingSemantics_UsesChunkedSemantics(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
                useContentLengthUpload: true, useChunkedEncodingUpload: true);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx behaves differently and will buffer content and use 'Content-Length' semantics")]
        public async Task PostUsingNoSpecifiedSemantics_UsesChunkedSemantics(Uri serverUri)
        {
            await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
                useContentLengthUpload: false, useChunkedEncodingUpload: false);
        }

        [OuterLoop("Uses external servers")]
        [Theory]
        [InlineData(5 * 1024)]
        [InlineData(63 * 1024)]
        public async Task PostLongerContentLengths_UsesChunkedSemantics(int contentLength)
        {
            var rand = new Random(42);
            var sb = new StringBuilder(contentLength);
            for (int i = 0; i < contentLength; i++)
            {
                sb.Append((char)(rand.Next(0, 26) + 'a'));
            }
            string content = sb.ToString();

            await PostHelper(Configuration.Http.RemoteEchoServer, content, new StringContent(content),
                useContentLengthUpload: true, useChunkedEncodingUpload: false);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(BasicAuthEchoServers))]
        public async Task PostRewindableContentUsingAuth_NoPreAuthenticate_Success(Uri serverUri)
        {
            HttpContent content = CustomContent.Create(ExpectedContent, true);
            var credential = new NetworkCredential(UserName, Password);
            await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, false);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(BasicAuthEchoServers))]
        public async Task PostNonRewindableContentUsingAuth_NoPreAuthenticate_ThrowsHttpRequestException(Uri serverUri)
        {
            HttpContent content = CustomContent.Create(ExpectedContent, false);
            var credential = new NetworkCredential(UserName, Password);
            await Assert.ThrowsAsync<HttpRequestException>(() => 
                PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: false));
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(BasicAuthEchoServers))]
        public async Task PostNonRewindableContentUsingAuth_PreAuthenticate_Success(Uri serverUri)
        {
            if (IsWinHttpHandler)
            {
                // Issue #9228
                return;
            }

            HttpContent content = CustomContent.Create(ExpectedContent, false);
            var credential = new NetworkCredential(UserName, Password);
            await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: true);
        }

        [OuterLoop("Uses external servers")]
        [Theory, MemberData(nameof(EchoServers))]
        public async Task PostAsync_EmptyContent_ContentTypeHeaderNotSent(Uri serverUri)
        {
            using (HttpClient client = CreateHttpClient())
            using (HttpResponseMessage response = await client.PostAsync(serverUri, null))
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                bool sentContentType = TestHelper.JsonMessageContainsKey(responseContent, "Content-Type");

                Assert.False(sentContentType);
{'fraction_non_alphanumeric': 0.07810860078440038, 'fraction_numerical': 0.007567806440921394, 'mean_word_length': 2.7803299227396114, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4228833', 'n_tokens_mistral': 4726, 'n_tokens_neox': 4506, 'n_words': 1072}