// Copyright © 2020 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Collections.Generic; using System.Threading.Tasks; using Moq; using Xunit; using Xunit.Abstractions; namespace CefSharp.Test.Framework { //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle [Collection(CefSharpFixtureCollection.Key)] public class RequestContextExtensionTests { private const string ProxyPreferenceKey = "proxy"; private readonly ITestOutputHelper output; private delegate void SetPreferenceDelegate(string name, object value, out string errorMessage); public RequestContextExtensionTests(ITestOutputHelper output) { this.output = output; } [Theory] [InlineData("http", "localhost", 8080, "http://localhost:8080")] [InlineData("socks", "localhost", null, "socks://localhost")] [InlineData(null, "localhost", null, "http://localhost")] public void CanSetProxyWithSchemeHostAndPort(string scheme, string host, int? port, string expected) { string preferenceName = ""; object preferenceValue = null; var mockRequestContext = new Mock(); mockRequestContext.Setup(x => x.CanSetPreference(ProxyPreferenceKey)).Returns(true); mockRequestContext.Setup(x => x.SetPreference(ProxyPreferenceKey, It.IsAny>(), out It.Ref.IsAny)) .Callback(new SetPreferenceDelegate((string name, object value, out string errorMessage) => { preferenceName = name; preferenceValue = value; errorMessage = "OK"; })) .Returns(true); string msg; var result = mockRequestContext.Object.SetProxy(scheme, host, port, out msg); var dict = (Dictionary)preferenceValue; Assert.True(result); Assert.Equal("OK", msg); Assert.Equal(ProxyPreferenceKey, preferenceName); Assert.Equal(2, dict.Count); Assert.Equal("fixed_servers", dict["mode"]); Assert.Equal(expected, dict["server"]); } [Fact] public void SetProxyThrowsExceptionOnInvalidScheme() { var mockRequestContext = new Mock(); mockRequestContext.Setup(x => x.SetPreference(ProxyPreferenceKey, It.IsAny>(), out It.Ref.IsAny)).Returns(true); Assert.Throws(() => { string msg; mockRequestContext.Object.SetProxy("myscheme", "localhost", 0, out msg); }); } [Fact] public async Task CanGetCookieManagerForRequestContextAsync() { var requestContext = RequestContext .Configure() .Create(); var cookieManager = await requestContext.GetCookieManagerAsync(); var cookies = await cookieManager.VisitAllCookiesAsync(); Assert.NotNull(cookies); output.WriteLine("Cookie Count {0}", cookies.Count); } } }