Beispiel #1
0
 public HttpPipelineTransport CreateTransport(HttpPipelineTransport currentTransport)
 {
     return(Mode switch
     {
         RecordedTestMode.Live => currentTransport,
         RecordedTestMode.Record => new RecordTransport(_session, currentTransport, entry => _disableRecording.Value, Random),
         RecordedTestMode.Playback => new PlaybackTransport(_session, _matcher, _sanitizer, Random,
                                                            entry => _disableRecording.Value == EntryRecordModel.RecordWithoutRequestBody),
         _ => throw new ArgumentOutOfRangeException(nameof(Mode), Mode, null),
     });
Beispiel #2
0
        public ResourcesManagementClient GetResourceManagementClient(HttpPipelineTransport transport)
        {
            ResourcesManagementClientOptions options = new ResourcesManagementClientOptions();

            options.Transport = transport;

            return(CreateClient <ResourcesManagementClient>(
                       TestEnvironment.SubscriptionId,
                       new TestCredential(), options));
        }
Beispiel #3
0
        private TextAnalyticsClient CreateTestClient(HttpPipelineTransport transport)
        {
            var options = new TextAnalyticsClientOptions(TextAnalyticsClientOptions.ServiceVersion.V3_2_Preview_2)
            {
                Transport = transport
            };

            var client = new TextAnalyticsClient(new Uri(s_endpoint), new AzureKeyCredential(s_apiKey), options);

            return(client);
        }
        private TextAnalyticsClient CreateTestClient(HttpPipelineTransport transport)
        {
            var options = new TextAnalyticsClientOptions
            {
                Transport = transport
            };

            var client = InstrumentClient(new TextAnalyticsClient(new Uri(s_endpoint), new AzureKeyCredential(s_apiKey), options));

            return(client);
        }
Beispiel #5
0
        private TextAnalyticsClient CreateTestClient(HttpPipelineTransport transport)
        {
            var options = new TextAnalyticsClientOptions
            {
                Transport = transport
            };

            var client = InstrumentClient(new TextAnalyticsClient(new Uri(s_endpoint), s_subscriptionKey, options));

            return(client);
        }
        private ConfigurationClient CreateTestService(HttpPipelineTransport transport)
        {
            var options = new ConfigurationClientOptions
            {
                Transport = transport
            };

            var client = InstrumentClient(new ConfigurationClient(s_connectionString, options));

            return(client);
        }
        protected static async Task <Response> SendGetRequest(HttpPipelineTransport transport, HttpPipelinePolicy policy, ResponseClassifier responseClassifier = null)
        {
            Assert.IsInstanceOf <HttpPipelineSynchronousPolicy>(policy, "Use SyncAsyncPolicyTestBase base type for non-sync policies");

            using (Request request = transport.CreateRequest())
            {
                request.Method = RequestMethod.Get;
                request.Uri.Reset(new Uri("http://example.com"));
                var pipeline = new HttpPipeline(transport, new[] { policy }, responseClassifier);
                return(await pipeline.SendRequestAsync(request, CancellationToken.None));
            }
        }
Beispiel #8
0
        protected async Task <Response> SendGetRequest(HttpPipelineTransport transport, HttpPipelinePolicy policy, ResponseClassifier responseClassifier = null)
        {
            await Task.Yield();

            using (Request request = transport.CreateRequest())
            {
                request.Method         = HttpPipelineMethod.Get;
                request.UriBuilder.Uri = new Uri("http://example.com");
                var pipeline = new HttpPipeline(transport, new [] { policy }, responseClassifier);
                return(await SendRequestAsync(pipeline, request, CancellationToken.None));
            }
        }
        private CertificateClient CreateClient(HttpPipelineTransport transport)
        {
            CertificateClientOptions options = new CertificateClientOptions
            {
                Transport = transport,
            };

            return(InstrumentClient(
                       new CertificateClient(
                           new Uri(VaultUri),
                           new MockCredential(),
                           options
                           )));
        }
Beispiel #10
0
        protected async Task <Response> ExecuteRequest(Request request, HttpPipelineTransport transport)
        {
            var message = new HttpMessage(request, new ResponseClassifier());

            if (_isAsync)
            {
                await transport.ProcessAsync(message);
            }
            else
            {
                transport.Process(message);
            }
            return(message.Response);
        }
Beispiel #11
0
        public HttpPipeline(HttpPipelineTransport transport, HttpPipelinePolicy[] policies = null, IServiceProvider services = null)
        {
            _transport = transport ?? throw new ArgumentNullException(nameof(transport));

            policies = policies ?? Array.Empty <HttpPipelinePolicy>();

            var all = new HttpPipelinePolicy[policies.Length + 1];

            all[policies.Length] = new HttpPipelineTransportPolicy(_transport);
            policies.CopyTo(all, 0);

            _pipeline = all;
            _services = services ?? HttpClientOptions.EmptyServiceProvider.Singleton;
        }
        public void CreateReturnsStaticInstanceWhenNoOptionsArePassed([Values(true, false)] bool noOptionsSpecified)
        {
            var options = new HttpPipelineTransportOptions();
            var target  = noOptionsSpecified ? HttpPipelineTransport.Create() : HttpPipelineTransport.Create(options);
            var target2 = noOptionsSpecified ? HttpPipelineTransport.Create() : HttpPipelineTransport.Create(options);

#if NETFRAMEWORK
            var sharedInstance = HttpWebRequestTransport.Shared;
#else
            var sharedInstance = HttpClientTransport.Shared;
#endif

            Assert.AreEqual(noOptionsSpecified, target == sharedInstance);
            Assert.AreEqual(noOptionsSpecified, target == target2);
        }
Beispiel #13
0
        protected async Task <Response> ExecuteRequest(Request request, HttpPipelineTransport transport, CancellationToken cancellationToken = default)
        {
            var message = new HttpMessage(request, ResponseClassifier.Shared);

            message.CancellationToken = cancellationToken;
            if (_isAsync)
            {
                await transport.ProcessAsync(message);
            }
            else
            {
                transport.Process(message);
            }
            return(message.Response);
        }
Beispiel #14
0
        public HttpPipelineTransport CreateTransport(HttpPipelineTransport currentTransport)
        {
            switch (Mode)
            {
            case RecordedTestMode.Live:
                return(currentTransport);

            case RecordedTestMode.Record:
                return(new RecordTransport(_session, currentTransport, entry => !_disableRecording.Value, Random));

            case RecordedTestMode.Playback:
                return(new PlaybackTransport(_session, _matcher, Random));

            default:
                throw new ArgumentOutOfRangeException(nameof(Mode), Mode, null);
            }
        }
Beispiel #15
0
        public HttpPipeline(HttpPipelineTransport transport, HttpPipelinePolicy[] policies = null, IServiceProvider services = null)
        {
            if (transport == null)
            {
                throw new ArgumentNullException(nameof(transport));
            }
            if (policies == null)
            {
                policies = Array.Empty <HttpPipelinePolicy>();
            }

            var all = new HttpPipelinePolicy[policies.Length + 1];

            all[policies.Length] = transport;
            policies.CopyTo(all, 0);
            _pipeline = all;
            _services = services != null ? services: HttpPipelineOptions.EmptyServiceProvider.Singleton;
        }
Beispiel #16
0
        public void SetTransportOptions([Values(true, false)] bool isCustomTransportSet)
        {
            using var testListener = new TestEventListener();
            testListener.EnableEvents(AzureCoreEventSource.Singleton, EventLevel.Verbose);

            var transport = new MockTransport(new MockResponse(503), new MockResponse(200));
            var options   = new TestOptions();

            if (isCustomTransportSet)
            {
                options.Transport = transport;
            }

            List <EventWrittenEventArgs> events = new();

            using var listener = new AzureEventSourceListener(
                      (args, s) =>
            {
                events.Add(args);
            },
                      EventLevel.Verbose);

            var pipeline = HttpPipelineBuilder.Build(
                options,
                Array.Empty <HttpPipelinePolicy>(),
                Array.Empty <HttpPipelinePolicy>(),
                new HttpPipelineTransportOptions(),
                ResponseClassifier.Shared);

            HttpPipelineTransport transportField = pipeline.GetType().GetField("_transport", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField).GetValue(pipeline) as HttpPipelineTransport;

            if (isCustomTransportSet)
            {
                Assert.That(transportField, Is.TypeOf <MockTransport>());
                events.Any(
                    e => e.EventId == 23 &&
                    e.EventName == "PipelineTransportOptionsNotApplied" &&
                    e.GetProperty <string>("optionsType") == options.GetType().FullName);
            }
            else
            {
                Assert.That(transportField, Is.Not.TypeOf <MockTransport>());
            }
        }
        public PerfTest(TOptions options)
        {
            Options       = options;
            ParallelIndex = Interlocked.Increment(ref _globalParallelIndex) - 1;

            if (Options.Insecure)
            {
                var transport = (new PerfClientOptions()).Transport;

                // Disable SSL validation
                if (transport is HttpClientTransport)
                {
                    _insecureTransport = new HttpClientTransport(new HttpClient(new HttpClientHandler()
                    {
                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                    }));
                }
                else
                {
                    // Assume _transport is HttpWebRequestTransport (currently internal class)
                    ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, errors) => true;

                    _insecureTransport = transport;
                }
            }

            if (Options.TestProxies != null && Options.TestProxies.Any())
            {
                if (Options.Insecure)
                {
                    _recordPlaybackHttpClient = new HttpClient(new HttpClientHandler()
                    {
                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                    });
                }
                else
                {
                    _recordPlaybackHttpClient = new HttpClient();
                }

                _testProxy       = Options.TestProxies.ElementAt(ParallelIndex % Options.TestProxies.Count());
                _testProxyPolicy = new TestProxyPolicy(_testProxy);
            }
        }
Beispiel #18
0
        private static async Task SendRequest(HttpPipelineTransport transport)
        {
            Console.WriteLine("Request");

            var serviceClient = new BlobServiceClient(_connectionString, new BlobClientOptions()
            {
                Transport = transport,
            });
            var containerClient = serviceClient.GetBlobContainerClient(_containerName);
            var blobClient      = containerClient.GetBlobClient(_blobName);

            var stream   = new MemoryStream();
            var response = await blobClient.DownloadToAsync(stream);

            Console.WriteLine("Headers:");
            Console.WriteLine($"  Date: {response.Headers.Date.Value.LocalDateTime}");
            Console.WriteLine($"Content: {Encoding.UTF8.GetString(stream.ToArray())}");
            Console.WriteLine();
        }
Beispiel #19
0
        private CertificateClient CreateClient(HttpPipelineTransport transport)
        {
            CertificateClientOptions options = new CertificateClientOptions
            {
                Retry =
                {
                    Delay = TimeSpan.FromMilliseconds(10),
                    Mode  = RetryMode.Fixed,
                },
                Transport = transport,
            };

            return(InstrumentClient(
                       new CertificateClient(
                           new Uri(VaultUri),
                           new MockCredential(),
                           options
                           )));
        }
        public HttpPipelineTransport CreateTransport(HttpPipelineTransport currentTransport)
        {
            var transport = Mode switch
            {
                RecordedTestMode.Live => currentTransport,
                RecordedTestMode.Record => new RecordTransport(_session, currentTransport, entry => _disableRecording.Value, Random),
                RecordedTestMode.Playback => new PlaybackTransport(_session, _matcher, _sanitizer, Random, entry => _disableRecording.Value == EntryRecordModel.RecordWithoutRequestBody),
                RecordedTestMode.RemotePlayback => new RemoteRecordTransport(currentTransport, _sessionFile, playback: true),
                RecordedTestMode.RemoteRecord => new RemoteRecordTransport(currentTransport, _sessionFile, playback: false),
                _ => throw new ArgumentOutOfRangeException(nameof(Mode), Mode, null),
            };

            if (transport is RemoteRecordTransport remote)
            {
                _disposeAction += remote.Stop;
            }

            return(transport);
        }
Beispiel #21
0
        public PerfTest(TOptions options)
        {
            Options = options;

            if (Options.Insecure)
            {
                var transport = (new PerfClientOptions()).Transport;

                // Disable SSL validation
                if (transport is HttpClientTransport)
                {
                    _insecureTransport = new HttpClientTransport(new HttpClient(new HttpClientHandler()
                    {
                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                    }));
                }
                else
                {
                    // Assume _transport is HttpWebRequestTransport (currently internal class)
                    ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, errors) => true;

                    _insecureTransport = transport;
                }
            }

            if (Options.TestProxy != null)
            {
                if (Options.Insecure)
                {
                    _recordPlaybackHttpClient = new HttpClient(new HttpClientHandler()
                    {
                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                    });
                }
                else
                {
                    _recordPlaybackHttpClient = new HttpClient();
                }

                _testProxyPolicy = new TestProxyPolicy(Options.TestProxy);
            }
        }
Beispiel #22
0
 public ProxyTransport(TestProxy proxy, HttpPipelineTransport transport, TestRecording recording, Func <EntryRecordModel> filter)
 {
     if (transport is HttpClientTransport)
     {
         var handler = new HttpClientHandler
         {
             ServerCertificateCustomValidationCallback = (_, certificate, _, _) => certificate.Issuer == TestProxy.DevCertIssuer
         };
         _innerTransport = new HttpClientTransport(handler);
     }
     // HttpWebRequestTransport
     else
     {
         _isWebRequestTransport = true;
         _innerTransport        = transport;
     }
     _recording = recording;
     _proxy     = proxy;
     _filter    = filter;
 }
Beispiel #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SmsClientOptions"/>.
        /// </summary>
        public SmsClientOptions(ServiceVersion version = LatestVersion, RetryOptions retryOptions = default, HttpPipelineTransport transport = default)
        {
            ApiVersion = version switch
            {
                ServiceVersion.V1 => "2020-07-20-preview1",
                _ => throw new ArgumentOutOfRangeException(nameof(version)),
            };

            if (transport != default)
            {
                Transport = transport;
            }

            if (retryOptions != null)
            {
                Retry.Mode       = retryOptions.Mode;
                Retry.MaxRetries = retryOptions.MaxRetries;
                Retry.Delay      = retryOptions.Delay;
                Retry.MaxDelay   = retryOptions.MaxDelay;
            }
        }
Beispiel #24
0
 internal ClientOptions(ClientOptions?clientOptions, DiagnosticsOptions?diagnostics)
 {
     if (clientOptions != null)
     {
         Retry       = new RetryOptions(clientOptions.Retry);
         Diagnostics = diagnostics ?? new DiagnosticsOptions(clientOptions.Diagnostics);
         _transport  = clientOptions.Transport;
         if (clientOptions.Policies != null)
         {
             Policies = new(clientOptions.Policies);
         }
     }
     else
     {
         // Implementation Note: this code must use the copy constructors on DiagnosticsOptions and RetryOptions specifying
         // null as the argument rather than calling their default constructors. Calling their default constructors would result
         // in a stack overflow as this constructor is called from a static initializer.
         _transport  = GetDefaultTransport();
         Diagnostics = new DiagnosticsOptions(null);
         Retry       = new RetryOptions(null);
     }
 }
Beispiel #25
0
        internal ClientOptions(ClientOptions?clientOptions)
        {
            if (clientOptions != null)
            {
                Retry = new RetryOptions(clientOptions.Retry);

                Diagnostics = new DiagnosticsOptions(clientOptions.Diagnostics);

                _transport = clientOptions.Transport;
                if (clientOptions.Policies != null)
                {
                    Policies = new(clientOptions.Policies);
                }
            }
            else
            {
                // Intentionally leaving this null. The only consumer of this branch is
                // DefaultAzureCredential that would re-assign the value
                _transport  = null !;
                Diagnostics = new DiagnosticsOptions();
                Retry       = new RetryOptions();
            }
        }
 public HttpPipelineTransportPolicy(HttpPipelineTransport httpPipelineTransport)
 {
     _httpPipelineTransport = httpPipelineTransport;
 }
Beispiel #27
0
 public DefaultClientOptions() : base(null)
 {
     Transport = HttpPipelineTransport.Create();
     Diagnostics.IsTelemetryEnabled          = !EnvironmentVariableToBool(Environment.GetEnvironmentVariable("AZURE_TELEMETRY_DISABLED")) ?? true;
     Diagnostics.IsDistributedTracingEnabled = !EnvironmentVariableToBool(Environment.GetEnvironmentVariable("AZURE_TRACING_DISABLED")) ?? true;
 }
Beispiel #28
0
 public RecordTransport(RecordSession session, HttpPipelineTransport innerTransport, Random random)
 {
     _innerTransport = innerTransport;
     _random         = random;
     _session        = session;
 }
 public HttpPipelineTransportPolicy(HttpPipelineTransport transport)
 {
     _transport = transport;
 }
Beispiel #30
0
 public FaultInjectionTransport(HttpPipelineTransport transport, Uri uri)
 {
     _transport = transport;
     _uri       = uri;
 }