diff --git a/CefSharp.Test/BrowserTests.cs b/CefSharp.Test/BrowserTests.cs new file mode 100644 index 000000000..e4238de00 --- /dev/null +++ b/CefSharp.Test/BrowserTests.cs @@ -0,0 +1,47 @@ +// Copyright © 2021 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.Threading.Tasks; +using CefSharp.Example; +using CefSharp.OffScreen; +using Xunit; + +namespace CefSharp.Test +{ + public abstract class BrowserTests : IAsyncLifetime + { + public ChromiumWebBrowser Browser { get; private set; } + public bool RequestContextIsolated { get; protected set; } + + protected void AssertInitialLoadComplete() + { + var t = Browser.WaitForInitialLoadAsync(); + + Assert.True(t.IsCompleted, "WaitForInitialLoadAsync Task.IsComplete"); + Assert.True(t.Result.Success, "WaitForInitialLoadAsync Result.Success"); + } + + Task IAsyncLifetime.DisposeAsync() + { + Browser?.Dispose(); + + return Task.CompletedTask; + } + + Task IAsyncLifetime.InitializeAsync() + { + IRequestContext requestContext = null; + + if (RequestContextIsolated) + { + requestContext = new RequestContext(); + requestContext.RegisterSchemeHandlerFactory("https", CefExample.ExampleDomain, new CefSharpSchemeHandlerFactory()); + } + + Browser = new ChromiumWebBrowser(CefExample.HelloWorldUrl, requestContext: requestContext, useLegacyRenderHandler: false); + + return Browser.WaitForInitialLoadAsync(); + } + } +} diff --git a/CefSharp.Test/ChromiumWebBrowserOffScreenFixture.cs b/CefSharp.Test/ChromiumWebBrowserOffScreenFixture.cs deleted file mode 100644 index 670afd42f..000000000 --- a/CefSharp.Test/ChromiumWebBrowserOffScreenFixture.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright © 2021 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.Threading.Tasks; -using CefSharp.Example; -using CefSharp.OffScreen; -using Xunit; - -namespace CefSharp.Test -{ - public class ChromiumWebBrowserOffScreenFixture : IAsyncLifetime - { - public ChromiumWebBrowser Browser { get; private set; } - - Task IAsyncLifetime.DisposeAsync() - { - Browser?.Dispose(); - - return Task.CompletedTask; - } - - Task IAsyncLifetime.InitializeAsync() - { - Browser = new ChromiumWebBrowser(CefExample.HelloWorldUrl, useLegacyRenderHandler: false); - - return Browser.WaitForInitialLoadAsync(); - } - } -} diff --git a/CefSharp.Test/CookieManager/CookieManagerFacts.cs b/CefSharp.Test/CookieManager/CookieManagerFacts.cs deleted file mode 100644 index 4eeece04c..000000000 --- a/CefSharp.Test/CookieManager/CookieManagerFacts.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright © 2022 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.Threading.Tasks; -using Xunit.Abstractions; -using Xunit; -using System; -using CefSharp.Example; -using System.Linq; - -namespace CefSharp.Test.CookieManager -{ - [Collection(CefSharpFixtureCollection.Key)] - public class CookieManagerFacts : IClassFixture - { - private readonly ITestOutputHelper output; - private readonly CefSharpFixture collectionFixture; - private readonly ChromiumWebBrowserOffScreenFixture classFixture; - - public CookieManagerFacts(ITestOutputHelper output, CefSharpFixture collectionFixture, ChromiumWebBrowserOffScreenFixture classFixture) - { - this.output = output; - this.collectionFixture = collectionFixture; - this.classFixture = classFixture; - } - - [Fact] - //https://github.com/cefsharp/CefSharp/issues/4234 - public async Task CanSetAndGetCookie() - { - const string CookieName = "CefSharpExpiryTestCookie"; - var testStartDate = DateTime.Now; - var expectedExpiry = DateTime.Now.AddDays(1); - - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var cookieManager = browser.GetCookieManager(); - - await cookieManager.DeleteCookiesAsync(CefExample.HelloWorldUrl, CookieName); - - var cookieSet = await cookieManager.SetCookieAsync(CefExample.HelloWorldUrl, new Cookie - { - Name = CookieName, - Value = "ILikeCookies", - Expires = expectedExpiry - }); - - Assert.True(cookieSet); - - var cookies = await cookieManager.VisitUrlCookiesAsync(CefExample.HelloWorldUrl, false); - var cookie = cookies.First(x => x.Name == CookieName); - - Assert.True(cookie.Expires.HasValue); - // Little bit of a loss in precision - Assert.Equal(expectedExpiry, cookie.Expires.Value, TimeSpan.FromMilliseconds(10)); - Assert.True(cookie.Creation > testStartDate, "Cookie Creation greater than test start."); - Assert.True(cookie.LastAccess > testStartDate, "Cookie LastAccess greater than test start."); - - output.WriteLine("Expected {0} : Actual {1}", expectedExpiry, cookie.Expires.Value); - } - } -} diff --git a/CefSharp.Test/CookieManager/CookieManagerTests.cs b/CefSharp.Test/CookieManager/CookieManagerTests.cs new file mode 100644 index 000000000..f3e54a089 --- /dev/null +++ b/CefSharp.Test/CookieManager/CookieManagerTests.cs @@ -0,0 +1,220 @@ +// Copyright © 2022 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.Threading.Tasks; +using Xunit.Abstractions; +using Xunit; +using System; +using CefSharp.Example; +using System.Linq; +using System.Collections.Generic; +using CefSharp.Enums; + +namespace CefSharp.Test.CookieManager +{ + [Collection(CefSharpFixtureCollection.Key)] + public class CookieManagerTests : RequestContextIsolatedBrowserTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture collectionFixture; + + public CookieManagerTests(ITestOutputHelper output, CefSharpFixture collectionFixture) + { + this.output = output; + this.collectionFixture = collectionFixture; + } + + [Fact] + public async Task ShouldWork() + { + AssertInitialLoadComplete(); + + const string expected = "password=123456"; + + var cookieManager = Browser.GetCookieManager(); + + var success = await cookieManager.SetCookieAsync(CefExample.HelloWorldUrl, new Cookie + { + Name = "password", + Value = "123456" + }); + + Assert.True(success); + + var actual = await Browser.EvaluateScriptAndAssertAsync("document.cookie"); + + Assert.Equal(expected, actual); + } + + [Fact] + public async Task ShouldSetMultipleCookies() + { + AssertInitialLoadComplete(); + + var expected = new string[] + { + "multiple-1=123456", + "multiple-2=bar" + }; + + var cookieManager = Browser.GetCookieManager(); + + var success = await cookieManager.SetCookieAsync(CefExample.HelloWorldUrl, new Cookie + { + Name = "multiple-1", + Value = "123456" + }); + + success &= await cookieManager.SetCookieAsync(CefExample.HelloWorldUrl, new Cookie + { + Name = "multiple-2", + Value = "bar" + }); + + Assert.True(success); + + var actual = await Browser.EvaluateScriptAndAssertAsync>(@"(() => { + const cookies = document.cookie.split(';'); + return cookies.map(cookie => cookie.trim()).sort(); + })();"); + + Assert.Equal(expected, actual); + } + + [Fact] + public async Task ShouldGetACookie() + { + AssertInitialLoadComplete(); + + var response = await Browser.EvaluateScriptAndAssertAsync(@"(() => { + document.cookie = 'username=John Doe'; + return document.cookie; + })();"); + + Assert.Equal("username=John Doe", response); + + var cookieManager = Browser.GetCookieManager(); + + var cookie = (await cookieManager.VisitAllCookiesAsync()).Single(); + + Assert.Equal("username", cookie.Name); + Assert.Equal("John Doe", cookie.Value); + Assert.Equal("cefsharp.example", cookie.Domain); + Assert.Equal("/", cookie.Path); + Assert.Null(cookie.Expires); + Assert.False(cookie.HttpOnly); + Assert.False(cookie.Secure); + Assert.Equal(CookieSameSite.Unspecified, cookie.SameSite); + } + + [Fact] + public async Task ShouldProperlyReportSecureCookie() + { + AssertInitialLoadComplete(); + + var response = await Browser.EvaluateScriptAndAssertAsync(@"(() => { + document.cookie = 'username=John Doe;Secure;'; + return document.cookie; + })();"); + + Assert.Equal("username=John Doe", response); + + var cookieManager = Browser.GetCookieManager(); + + var cookie = (await cookieManager.VisitAllCookiesAsync()).Single(); + + Assert.True(cookie.Secure); + } + + [Fact] + public async Task ShouldProperlyReportStrictSameSiteCookie() + { + AssertInitialLoadComplete(); + + var response = await Browser.EvaluateScriptAndAssertAsync(@"(() => { + document.cookie = 'username=John Doe;SameSite=Strict;'; + return document.cookie; + })();"); + + Assert.Equal("username=John Doe", response); + + var cookieManager = Browser.GetCookieManager(); + + var cookie = (await cookieManager.VisitAllCookiesAsync()).Single(); + + Assert.Equal(CookieSameSite.StrictMode, cookie.SameSite); + } + + [Fact] + //https://github.com/cefsharp/CefSharp/issues/4234 + public async Task CanSetAndGetCookie() + { + AssertInitialLoadComplete(); + + const string CookieName = "CefSharpExpiryTestCookie"; + var testStartDate = DateTime.Now; + var expectedExpiry = DateTime.Now.AddDays(1); + + Assert.False(Browser.IsLoading); + + var cookieManager = Browser.GetCookieManager(); + + await cookieManager.DeleteCookiesAsync(CefExample.HelloWorldUrl, CookieName); + + var cookieSet = await cookieManager.SetCookieAsync(CefExample.HelloWorldUrl, new Cookie + { + Name = CookieName, + Value = "ILikeCookies", + Expires = expectedExpiry + }); + + Assert.True(cookieSet); + + var cookies = await cookieManager.VisitUrlCookiesAsync(CefExample.HelloWorldUrl, false); + var cookie = cookies.First(x => x.Name == CookieName); + + Assert.True(cookie.Expires.HasValue); + // Little bit of a loss in precision + Assert.Equal(expectedExpiry, cookie.Expires.Value, TimeSpan.FromMilliseconds(10)); + Assert.True(cookie.Creation > testStartDate, "Cookie Creation greater than test start."); + Assert.True(cookie.LastAccess > testStartDate, "Cookie LastAccess greater than test start."); + + output.WriteLine("Expected {0} : Actual {1}", expectedExpiry, cookie.Expires.Value); + } + + [Fact] + public async Task ShouldClearCookies() + { + AssertInitialLoadComplete(); + + var cookieManager = Browser.GetCookieManager(); + + var cookieSet = await cookieManager.SetCookieAsync(CefExample.HelloWorldUrl, new Cookie + { + Name = "cookie1", + Value = "1" + }); + + Assert.True(cookieSet); + + var response = await Browser.EvaluateScriptAndAssertAsync("document.cookie"); + + Assert.Equal("cookie1=1", response); + + await cookieManager.DeleteCookiesAsync(); + + var cookies = await cookieManager.VisitAllCookiesAsync(); + + Assert.Empty(cookies); + + Browser.Reload(); + + await Browser.WaitForNavigationAsync(); + + response = await Browser.EvaluateScriptAndAssertAsync("document.cookie"); + + Assert.Equal(string.Empty, response); + } + } +} diff --git a/CefSharp.Test/DevTools/DevToolsClientFacts.cs b/CefSharp.Test/DevTools/DevToolsClientTests.cs similarity index 99% rename from CefSharp.Test/DevTools/DevToolsClientFacts.cs rename to CefSharp.Test/DevTools/DevToolsClientTests.cs index 8a3781164..b92484008 100644 --- a/CefSharp.Test/DevTools/DevToolsClientFacts.cs +++ b/CefSharp.Test/DevTools/DevToolsClientTests.cs @@ -21,12 +21,12 @@ namespace CefSharp.Test.DevTools { //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle [Collection(CefSharpFixtureCollection.Key)] - public class DevToolsClientFacts + public class DevToolsClientTests { private readonly ITestOutputHelper output; private readonly CefSharpFixture fixture; - public DevToolsClientFacts(ITestOutputHelper output, CefSharpFixture fixture) + public DevToolsClientTests(ITestOutputHelper output, CefSharpFixture fixture) { this.fixture = fixture; this.output = output; diff --git a/CefSharp.Test/DevTools/HeadersFacts.cs b/CefSharp.Test/DevTools/HeadersTests.cs similarity index 99% rename from CefSharp.Test/DevTools/HeadersFacts.cs rename to CefSharp.Test/DevTools/HeadersTests.cs index 75fb30a0c..73d9c8dc3 100644 --- a/CefSharp.Test/DevTools/HeadersFacts.cs +++ b/CefSharp.Test/DevTools/HeadersTests.cs @@ -7,7 +7,7 @@ using Xunit; namespace CefSharp.Test.DevTools { - public class HeadersFacts + public class HeadersTests { [Fact] public void HeadersTryGetValues() diff --git a/CefSharp.Test/Framework/AsyncExtensionFacts.cs b/CefSharp.Test/Framework/AsyncExtensionTests.cs similarity index 94% rename from CefSharp.Test/Framework/AsyncExtensionFacts.cs rename to CefSharp.Test/Framework/AsyncExtensionTests.cs index ddc6a814c..432260f64 100644 --- a/CefSharp.Test/Framework/AsyncExtensionFacts.cs +++ b/CefSharp.Test/Framework/AsyncExtensionTests.cs @@ -9,14 +9,11 @@ using Xunit.Abstractions; namespace CefSharp.Test.Framework { - /// - /// Async Extensions - This test doesn't need to be part of the - /// - public class AsyncExtensionFacts + public class AsyncExtensionTests { private readonly ITestOutputHelper output; - public AsyncExtensionFacts(ITestOutputHelper output) + public AsyncExtensionTests(ITestOutputHelper output) { this.output = output; } diff --git a/CefSharp.Test/Framework/BinderFacts.cs b/CefSharp.Test/Framework/BinderTests.cs similarity index 99% rename from CefSharp.Test/Framework/BinderFacts.cs rename to CefSharp.Test/Framework/BinderTests.cs index 1b2165f13..c2a683c1b 100644 --- a/CefSharp.Test/Framework/BinderFacts.cs +++ b/CefSharp.Test/Framework/BinderTests.cs @@ -13,7 +13,7 @@ namespace CefSharp.Test.Framework /// /// BinderFacts - Tests model default binder behavior /// - public class BinderFacts + public class BinderTests { private enum TestEnum { diff --git a/CefSharp.Test/Framework/CamelCaseNamingConverterFacts.cs b/CefSharp.Test/Framework/CamelCaseNamingConverterTests.cs similarity index 96% rename from CefSharp.Test/Framework/CamelCaseNamingConverterFacts.cs rename to CefSharp.Test/Framework/CamelCaseNamingConverterTests.cs index ec24e27e5..a8de2b4ab 100644 --- a/CefSharp.Test/Framework/CamelCaseNamingConverterFacts.cs +++ b/CefSharp.Test/Framework/CamelCaseNamingConverterTests.cs @@ -10,7 +10,7 @@ namespace CefSharp.Test.Framework /// /// JavascriptNameConverterFacts - Test the different name converters /// - public class CamelCaseNamingConverterFacts + public class CamelCaseNamingConverterTests { [Fact] public void CanConvertStringToJavascriptName() diff --git a/CefSharp.Test/Framework/CefTimeUtilsFacts.cs b/CefSharp.Test/Framework/CefTimeUtilsTests.cs similarity index 96% rename from CefSharp.Test/Framework/CefTimeUtilsFacts.cs rename to CefSharp.Test/Framework/CefTimeUtilsTests.cs index e9b5a43ab..0ef9d6548 100644 --- a/CefSharp.Test/Framework/CefTimeUtilsFacts.cs +++ b/CefSharp.Test/Framework/CefTimeUtilsTests.cs @@ -9,11 +9,11 @@ using Xunit.Abstractions; namespace CefSharp.Test.Framework { - public class CefTimeUtilsFacts + public class CefTimeUtilsTests { private readonly ITestOutputHelper output; - public CefTimeUtilsFacts(ITestOutputHelper output) + public CefTimeUtilsTests(ITestOutputHelper output) { this.output = output; } diff --git a/CefSharp.Test/Framework/ConcurrentMethodRunnerQueueFacts.cs b/CefSharp.Test/Framework/ConcurrentMethodRunnerQueueTest.cs similarity index 97% rename from CefSharp.Test/Framework/ConcurrentMethodRunnerQueueFacts.cs rename to CefSharp.Test/Framework/ConcurrentMethodRunnerQueueTest.cs index 67c4341ff..098d3cebb 100644 --- a/CefSharp.Test/Framework/ConcurrentMethodRunnerQueueFacts.cs +++ b/CefSharp.Test/Framework/ConcurrentMethodRunnerQueueTest.cs @@ -13,11 +13,11 @@ using Xunit.Abstractions; namespace CefSharp.Test.Framework { - public class ConcurrentMethodRunnerQueueFacts + public class ConcurrentMethodRunnerQueueTest { private readonly ITestOutputHelper output; - public ConcurrentMethodRunnerQueueFacts(ITestOutputHelper output) + public ConcurrentMethodRunnerQueueTest(ITestOutputHelper output) { this.output = output; } diff --git a/CefSharp.Test/Framework/HasHandlerFacts.cs b/CefSharp.Test/Framework/HasHandlerTests.cs similarity index 97% rename from CefSharp.Test/Framework/HasHandlerFacts.cs rename to CefSharp.Test/Framework/HasHandlerTests.cs index 515b9cd57..6fa0a596f 100644 --- a/CefSharp.Test/Framework/HasHandlerFacts.cs +++ b/CefSharp.Test/Framework/HasHandlerTests.cs @@ -4,7 +4,7 @@ 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 HasHandlerFacts + public class HasHandlerTests { [Fact] public void ShouldWorkForOffScreen() diff --git a/CefSharp.Test/Framework/LegacyCamelCaseJavascriptNameConverterFacts.cs b/CefSharp.Test/Framework/LegacyCamelCaseJavascriptNameConverterTests.cs similarity index 95% rename from CefSharp.Test/Framework/LegacyCamelCaseJavascriptNameConverterFacts.cs rename to CefSharp.Test/Framework/LegacyCamelCaseJavascriptNameConverterTests.cs index ded200559..e04f9d228 100644 --- a/CefSharp.Test/Framework/LegacyCamelCaseJavascriptNameConverterFacts.cs +++ b/CefSharp.Test/Framework/LegacyCamelCaseJavascriptNameConverterTests.cs @@ -10,7 +10,7 @@ namespace CefSharp.Test.Framework /// /// LegacyCamelCaseJavascriptNameConverterFacts - Test the different name converters /// - public class LegacyCamelCaseJavascriptNameConverterFacts + public class LegacyCamelCaseJavascriptNameConverterTests { [Fact] public void CanConvertStringToJavascriptName() diff --git a/CefSharp.Test/Framework/MethodRunnerQueueFacts.cs b/CefSharp.Test/Framework/MethodRunnerQueueTests.cs similarity index 95% rename from CefSharp.Test/Framework/MethodRunnerQueueFacts.cs rename to CefSharp.Test/Framework/MethodRunnerQueueTests.cs index 8b2f962bc..e542fe1e2 100644 --- a/CefSharp.Test/Framework/MethodRunnerQueueFacts.cs +++ b/CefSharp.Test/Framework/MethodRunnerQueueTests.cs @@ -7,7 +7,7 @@ using Xunit; namespace CefSharp.Test.Framework { - public class MethodRunnerQueueFacts + public class MethodRunnerQueueTests { [Fact] public void DisposeQueueThenEnqueueMethodInvocation() diff --git a/CefSharp.Test/Framework/MimeTypeMappingFacts.cs b/CefSharp.Test/Framework/MimeTypeMappingTests.cs similarity index 97% rename from CefSharp.Test/Framework/MimeTypeMappingFacts.cs rename to CefSharp.Test/Framework/MimeTypeMappingTests.cs index 7ad4aa1f9..5f54f47ba 100644 --- a/CefSharp.Test/Framework/MimeTypeMappingFacts.cs +++ b/CefSharp.Test/Framework/MimeTypeMappingTests.cs @@ -9,7 +9,7 @@ namespace CefSharp.Test.Framework /// /// MimeTypeMappingFacts - Tests file extension to mimeType mapping /// - public class MimeTypeMappingFacts + public class MimeTypeMappingTests { [Theory] [InlineData("html", "text/html")] diff --git a/CefSharp.Test/Framework/ParseUrlFacts.cs b/CefSharp.Test/Framework/ParseUrlTests.cs similarity index 90% rename from CefSharp.Test/Framework/ParseUrlFacts.cs rename to CefSharp.Test/Framework/ParseUrlTests.cs index 181b52882..1b222dce4 100644 --- a/CefSharp.Test/Framework/ParseUrlFacts.cs +++ b/CefSharp.Test/Framework/ParseUrlTests.cs @@ -7,11 +7,11 @@ using Xunit; namespace CefSharp.Test.Framework { - public class ParseUrlFacts + public class ParseUrlTests { private readonly ITestOutputHelper output; - public ParseUrlFacts(ITestOutputHelper output) + public ParseUrlTests(ITestOutputHelper output) { this.output = output; } diff --git a/CefSharp.Test/Framework/PathCheckFacts.cs b/CefSharp.Test/Framework/PathCheckTests.cs similarity index 98% rename from CefSharp.Test/Framework/PathCheckFacts.cs rename to CefSharp.Test/Framework/PathCheckTests.cs index b0694fc6b..f4063b962 100644 --- a/CefSharp.Test/Framework/PathCheckFacts.cs +++ b/CefSharp.Test/Framework/PathCheckTests.cs @@ -8,7 +8,7 @@ using Xunit; namespace CefSharp.Test.Framework { - public class PathCheckFacts + public class PathCheckTests { [Fact] public void IsPathAbsoluteValid() diff --git a/CefSharp.Test/Framework/RequestContextBuilderFacts.cs b/CefSharp.Test/Framework/RequestContextBuilderTests.cs similarity index 94% rename from CefSharp.Test/Framework/RequestContextBuilderFacts.cs rename to CefSharp.Test/Framework/RequestContextBuilderTests.cs index 95e428697..02a7c8ea3 100644 --- a/CefSharp.Test/Framework/RequestContextBuilderFacts.cs +++ b/CefSharp.Test/Framework/RequestContextBuilderTests.cs @@ -10,12 +10,12 @@ 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 RequestContextBuilderFacts + public class RequestContextBuilderTests { private CefSharpFixture fixture; private ITestOutputHelper output; - public RequestContextBuilderFacts(ITestOutputHelper output, CefSharpFixture fixture) + public RequestContextBuilderTests(ITestOutputHelper output, CefSharpFixture fixture) { this.fixture = fixture; this.output = output; diff --git a/CefSharp.Test/Framework/RequestContextExtensionFacts.cs b/CefSharp.Test/Framework/RequestContextExtensionTests.cs similarity index 96% rename from CefSharp.Test/Framework/RequestContextExtensionFacts.cs rename to CefSharp.Test/Framework/RequestContextExtensionTests.cs index 5531f64dd..15899364b 100644 --- a/CefSharp.Test/Framework/RequestContextExtensionFacts.cs +++ b/CefSharp.Test/Framework/RequestContextExtensionTests.cs @@ -13,7 +13,7 @@ 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 RequestContextExtensionFacts + public class RequestContextExtensionTests { private const string ProxyPreferenceKey = "proxy"; @@ -21,7 +21,7 @@ namespace CefSharp.Test.Framework private delegate void SetPreferenceDelegate(string name, object value, out string errorMessage); - public RequestContextExtensionFacts(ITestOutputHelper output) + public RequestContextExtensionTests(ITestOutputHelper output) { this.output = output; } diff --git a/CefSharp.Test/Framework/RequestContextFacts.cs b/CefSharp.Test/Framework/RequestContextTests.cs similarity index 96% rename from CefSharp.Test/Framework/RequestContextFacts.cs rename to CefSharp.Test/Framework/RequestContextTests.cs index 9583b3e2b..dc2b3ced9 100644 --- a/CefSharp.Test/Framework/RequestContextFacts.cs +++ b/CefSharp.Test/Framework/RequestContextTests.cs @@ -10,7 +10,7 @@ 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 RequestContextFacts + public class RequestContextTests { [Fact] public void IsSameAs() diff --git a/CefSharp.Test/Javascript/EvaluateScriptAsPromiseAsyncFacts.cs b/CefSharp.Test/Javascript/EvaluateScriptAsPromiseAsyncFacts.cs deleted file mode 100644 index 734f58eb2..000000000 --- a/CefSharp.Test/Javascript/EvaluateScriptAsPromiseAsyncFacts.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright © 2022 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.Threading.Tasks; -using CefSharp.Example; -using CefSharp.OffScreen; -using Xunit; -using Xunit.Abstractions; - -namespace CefSharp.Test.Javascript -{ - [Collection(CefSharpFixtureCollection.Key)] - public class EvaluateScriptAsPromiseAsyncFacts : IClassFixture - { - private readonly ITestOutputHelper output; - private readonly CefSharpFixture collectionFixture; - private readonly ChromiumWebBrowserOffScreenFixture classFixture; - - public EvaluateScriptAsPromiseAsyncFacts(ITestOutputHelper output, CefSharpFixture collectionFixture, ChromiumWebBrowserOffScreenFixture classFixture) - { - this.output = output; - this.collectionFixture = collectionFixture; - this.classFixture = classFixture; - } - - [Theory] - [InlineData("return 42;", true, "42")] - [InlineData("return new Promise(function(resolve, reject) { resolve(42); });", true, "42")] - [InlineData("return new Promise(function(resolve, reject) { reject('reject test'); });", false, "reject test")] - [InlineData("return await 42;", true, "42")] - [InlineData("return await (function() { throw('reject test'); })();", false, "reject test")] - [InlineData("var result = await fetch('./robots.txt'); return result.status;", true, "200")] - public async Task CanEvaluateScriptAsPromiseAsync(string script, bool success, string expected) - { - using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - - var javascriptResponse = await browser.EvaluateScriptAsPromiseAsync(script); - - Assert.Equal(success, javascriptResponse.Success); - - if (success) - { - Assert.Equal(expected, javascriptResponse.Result.ToString()); - } - else - { - Assert.Equal(expected, javascriptResponse.Message); - } - } - } - - [Theory] - [InlineData("return { a: 'CefSharp', b: 42, };", true, "CefSharp", "42")] - [InlineData("return new Promise(function(resolve, reject) { resolve({ a: 'CefSharp', b: 42, }); });", true, "CefSharp", "42")] - [InlineData("return new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { a: 'CefSharp', b: 42, }), 1000); });", true, "CefSharp", "42")] - [InlineData("return await { a: 'CefSharp', b: 42, };", true, "CefSharp", "42")] - [InlineData("return await new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { a: 'CefSharp', b: 42, }), 1000); }); ", true, "CefSharp", "42")] - [InlineData("function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }; async function getValAfterSleep() { await sleep(1000); return { a: 'CefSharp', b: 42 }; }; await sleep(2000); const result = await getValAfterSleep(); await sleep(2000); return result;", true, "CefSharp", "42")] - public async Task CanEvaluateScriptAsPromiseAsyncReturnObject(string script, bool success, string expectedA, string expectedB) - { - using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - - var javascriptResponse = await browser.EvaluateScriptAsPromiseAsync(script); - - Assert.Equal(success, javascriptResponse.Success); - - if (success) - { - dynamic result = javascriptResponse.Result; - Assert.Equal(expectedA, result.a.ToString()); - Assert.Equal(expectedB, result.b.ToString()); - } - else - { - throw new System.Exception("Failed"); - } - } - } - } -} diff --git a/CefSharp.Test/Javascript/EvaluateScriptAsPromiseAsyncTest.cs b/CefSharp.Test/Javascript/EvaluateScriptAsPromiseAsyncTest.cs new file mode 100644 index 000000000..74631cc9f --- /dev/null +++ b/CefSharp.Test/Javascript/EvaluateScriptAsPromiseAsyncTest.cs @@ -0,0 +1,69 @@ +// Copyright © 2022 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.Threading.Tasks; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.Javascript +{ + [Collection(CefSharpFixtureCollection.Key)] + public class EvaluateScriptAsPromiseAsyncTest : BrowserTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture collectionFixture; + + public EvaluateScriptAsPromiseAsyncTest(ITestOutputHelper output, CefSharpFixture collectionFixture) + { + this.output = output; + this.collectionFixture = collectionFixture; + } + + [Theory] + [InlineData("return 42;", "42")] + [InlineData("return new Promise(function(resolve, reject) { resolve(42); });", "42")] + [InlineData("return await 42;", "42")] + [InlineData("var result = await fetch('./home.html'); return result.status;", "200")] + public async Task ShouldWork(string script, string expected) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsPromiseAsync(script); + + Assert.True(javascriptResponse.Success); + Assert.Equal(expected, javascriptResponse.Result.ToString()); + } + + [Theory] + [InlineData("return new Promise(function(resolve, reject) { reject('reject test'); });", "reject test")] + [InlineData("return await (function() { throw('reject test'); })();", "reject test")] + public async Task ShouldFail(string script, string expected) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsPromiseAsync(script); + + Assert.False(javascriptResponse.Success); + Assert.Equal(expected, javascriptResponse.Message); + } + + [Theory] + [InlineData("return { a: 'CefSharp', b: 42, };", "CefSharp", "42")] + [InlineData("return new Promise(function(resolve, reject) { resolve({ a: 'CefSharp', b: 42, }); });", "CefSharp", "42")] + [InlineData("return new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { a: 'CefSharp', b: 42, }), 1000); });", "CefSharp", "42")] + [InlineData("return await { a: 'CefSharp', b: 42, };", "CefSharp", "42")] + [InlineData("return await new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { a: 'CefSharp', b: 42, }), 1000); }); ", "CefSharp", "42")] + [InlineData("function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }; async function getValAfterSleep() { await sleep(1000); return { a: 'CefSharp', b: 42 }; }; await sleep(2000); const result = await getValAfterSleep(); await sleep(2000); return result;", "CefSharp", "42")] + public async Task ShouldWorkWithObjects(string script, string expectedA, string expectedB) + { + var javascriptResponse = await Browser.EvaluateScriptAsPromiseAsync(script); + + Assert.True(javascriptResponse.Success); + + dynamic result = javascriptResponse.Result; + Assert.Equal(expectedA, result.a.ToString()); + Assert.Equal(expectedB, result.b.ToString()); + } + } +} diff --git a/CefSharp.Test/Javascript/EvaluateScriptAsyncFacts.cs b/CefSharp.Test/Javascript/EvaluateScriptAsyncFacts.cs deleted file mode 100644 index de3890112..000000000 --- a/CefSharp.Test/Javascript/EvaluateScriptAsyncFacts.cs +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright © 2021 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.Globalization; -using System.Threading.Tasks; -using Xunit; -using Xunit.Abstractions; - -namespace CefSharp.Test.Javascript -{ - [Collection(CefSharpFixtureCollection.Key)] - public class EvaluateScriptAsyncFacts : IClassFixture - { - private readonly ITestOutputHelper output; - private readonly CefSharpFixture collectionFixture; - private readonly ChromiumWebBrowserOffScreenFixture classFixture; - - public EvaluateScriptAsyncFacts(ITestOutputHelper output, CefSharpFixture collectionFixture, ChromiumWebBrowserOffScreenFixture classFixture) - { - this.output = output; - this.collectionFixture = collectionFixture; - this.classFixture = classFixture; - } - - [Theory] - [InlineData(double.MaxValue, "Number.MAX_VALUE")] - [InlineData(double.MaxValue / 2, "Number.MAX_VALUE / 2")] - //https://github.com/cefsharp/CefSharp/issues/3858 - public async Task CanEvaluateDoubleComputation(double expectedValue, string script) - { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync(script); - Assert.True(javascriptResponse.Success); - - var actualType = javascriptResponse.Result.GetType(); - - Assert.Equal(typeof(double), actualType); - Assert.Equal(expectedValue, (double)javascriptResponse.Result, 5); - - output.WriteLine("Script {0} : Result {1}", script, javascriptResponse.Result); - } - - [Theory] - [InlineData(0.5d)] - [InlineData(1.5d)] - [InlineData(-0.5d)] - [InlineData(-1.5d)] - [InlineData(100000.24500d)] - [InlineData(-100000.24500d)] - [InlineData((double)uint.MaxValue)] - [InlineData((double)int.MaxValue + 1)] - [InlineData((double)int.MaxValue + 10)] - [InlineData((double)int.MinValue - 1)] - [InlineData((double)int.MinValue - 10)] - [InlineData(((double)uint.MaxValue * 2))] - [InlineData(((double)uint.MaxValue * 2) + 0.1)] - //https://github.com/cefsharp/CefSharp/issues/3858 - public async Task CanEvaluateDoubleValues(double num) - { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync(num.ToString(CultureInfo.InvariantCulture)); - Assert.True(javascriptResponse.Success); - - var actualType = javascriptResponse.Result.GetType(); - - Assert.Equal(typeof(double), actualType); - Assert.Equal(num, (double)javascriptResponse.Result, 5); - - output.WriteLine("Expected {0} : Actual {1}", num, javascriptResponse.Result); - } - - [Theory] - [InlineData(0)] - [InlineData(-1)] - [InlineData(100)] - [InlineData(int.MaxValue)] - [InlineData(int.MinValue)] - //https://github.com/cefsharp/CefSharp/issues/3858 - public async Task CanEvaluateIntValues(object num) - { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync(num.ToString()); - Assert.True(javascriptResponse.Success); - - var actualType = javascriptResponse.Result.GetType(); - - Assert.Equal(typeof(int), actualType); - Assert.Equal(num, javascriptResponse.Result); - - output.WriteLine("Expected {0} : Actual {1}", num, javascriptResponse.Result); - } - - [Theory] - [InlineData("1970-01-01", "1970-01-01")] - [InlineData("1980-01-01", "1980-01-01")] - //https://github.com/cefsharp/CefSharp/issues/4234 - public async Task CanEvaluateDateValues(DateTime expected, string actual) - { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync($"new Date('{actual}');"); - Assert.True(javascriptResponse.Success); - - var actualType = javascriptResponse.Result.GetType(); - var actualDateTime = (DateTime)javascriptResponse.Result; - - Assert.Equal(typeof(DateTime), actualType); - Assert.Equal(expected.ToLocalTime(), actualDateTime); - - output.WriteLine("Expected {0} : Actual {1}", expected.ToLocalTime(), actualDateTime); - } - - [Theory] - [InlineData("new Promise(function(resolve, reject) { resolve(42); });", true, "42")] - [InlineData("new Promise(function(resolve, reject) { reject('reject test'); });", false, "reject test")] - [InlineData("Promise.resolve(42);", true, "42")] - [InlineData("(async () => { throw('reject test'); })();", false, "reject test")] - [InlineData("(async () => { var result = await fetch('https://cefsharp.example/HelloWorld.html'); return result.status;})();", true, "200")] - public async Task CanEvaluateScriptAsyncReturnPromisePrimative(string script, bool success, string expected) - { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - - var javascriptResponse = await browser.EvaluateScriptAsync(script); - - Assert.Equal(success, javascriptResponse.Success); - - if (success) - { - Assert.Equal(expected, javascriptResponse.Result.ToString()); - } - else - { - Assert.Equal(expected, javascriptResponse.Message); - } - } - - [Theory] - [InlineData("new Promise(function(resolve, reject) { resolve({ a: 'CefSharp', b: 42, }); });", "CefSharp", "42")] - [InlineData("new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { a: 'CefSharp', b: 42, }), 1000); });", "CefSharp", "42")] - [InlineData("(async () => { function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }; async function getValAfterSleep() { await sleep(1000); return { a: 'CefSharp', b: 42 }; }; await sleep(2000); const result = await getValAfterSleep(); await sleep(2000); return result; })();", "CefSharp", "42")] - public async Task CanEvaluateScriptAsyncReturnPromiseObject(string script, string expectedA, string expectedB) - { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - - var javascriptResponse = await browser.EvaluateScriptAsync(script); - - Assert.True(javascriptResponse.Success); - - dynamic result = javascriptResponse.Result; - Assert.Equal(expectedA, result.a.ToString()); - Assert.Equal(expectedB, result.b.ToString()); - } - } -} diff --git a/CefSharp.Test/Javascript/EvaluateScriptAsyncTests.cs b/CefSharp.Test/Javascript/EvaluateScriptAsyncTests.cs new file mode 100644 index 000000000..dadeee12b --- /dev/null +++ b/CefSharp.Test/Javascript/EvaluateScriptAsyncTests.cs @@ -0,0 +1,244 @@ +// Copyright © 2021 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.Globalization; +using System.Linq; +using System.Threading.Tasks; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.Javascript +{ + [Collection(CefSharpFixtureCollection.Key)] + public class EvaluateScriptAsyncTests : BrowserTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture collectionFixture; + + public EvaluateScriptAsyncTests(ITestOutputHelper output, CefSharpFixture collectionFixture) + { + this.output = output; + this.collectionFixture = collectionFixture; + } + + [Theory] + [InlineData(double.MaxValue, "Number.MAX_VALUE")] + [InlineData(double.MaxValue / 2, "Number.MAX_VALUE / 2")] + //https://github.com/cefsharp/CefSharp/issues/3858 + public async Task ShouldWorkForDoubleComputation(double expectedValue, string script) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsync(script); + Assert.True(javascriptResponse.Success); + + var actualType = javascriptResponse.Result.GetType(); + + Assert.Equal(typeof(double), actualType); + Assert.Equal(expectedValue, (double)javascriptResponse.Result, 5); + + output.WriteLine("Script {0} : Result {1}", script, javascriptResponse.Result); + } + + [Theory] + [InlineData(0.5d)] + [InlineData(1.5d)] + [InlineData(-0.5d)] + [InlineData(-1.5d)] + [InlineData(100000.24500d)] + [InlineData(-100000.24500d)] + [InlineData((double)uint.MaxValue)] + [InlineData((double)int.MaxValue + 1)] + [InlineData((double)int.MaxValue + 10)] + [InlineData((double)int.MinValue - 1)] + [InlineData((double)int.MinValue - 10)] + [InlineData(((double)uint.MaxValue * 2))] + [InlineData(((double)uint.MaxValue * 2) + 0.1)] + //https://github.com/cefsharp/CefSharp/issues/3858 + public async Task ShouldWorkForDouble(double num) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsync(num.ToString(CultureInfo.InvariantCulture)); + Assert.True(javascriptResponse.Success); + + var actualType = javascriptResponse.Result.GetType(); + + Assert.Equal(typeof(double), actualType); + Assert.Equal(num, (double)javascriptResponse.Result, 5); + + output.WriteLine("Expected {0} : Actual {1}", num, javascriptResponse.Result); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(100)] + [InlineData(int.MaxValue)] + [InlineData(int.MinValue)] + //https://github.com/cefsharp/CefSharp/issues/3858 + public async Task ShouldWorkForInt(object num) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsync(num.ToString()); + Assert.True(javascriptResponse.Success); + + var actualType = javascriptResponse.Result.GetType(); + + Assert.Equal(typeof(int), actualType); + Assert.Equal(num, javascriptResponse.Result); + + output.WriteLine("Expected {0} : Actual {1}", num, javascriptResponse.Result); + } + + [Theory] + [InlineData("1970-01-01", "1970-01-01")] + [InlineData("1980-01-01", "1980-01-01")] + //https://github.com/cefsharp/CefSharp/issues/4234 + public async Task ShouldWorkForDate(DateTime expected, string actual) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsync($"new Date('{actual}');"); + Assert.True(javascriptResponse.Success); + + var actualType = javascriptResponse.Result.GetType(); + var actualDateTime = (DateTime)javascriptResponse.Result; + + Assert.Equal(typeof(DateTime), actualType); + Assert.Equal(expected.ToLocalTime(), actualDateTime); + + output.WriteLine("Expected {0} : Actual {1}", expected.ToLocalTime(), actualDateTime); + } + + [Theory] + [InlineData("new Promise(function(resolve, reject) { resolve(42); });", "42")] + [InlineData("Promise.resolve(42);", "42")] + [InlineData("(async () => { var result = await fetch('https://cefsharp.example/HelloWorld.html'); return result.status;})();", "200")] + public async Task ShouldWorkForPromisePrimative(string script, string expected) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsync(script); + + Assert.True(javascriptResponse.Success); + Assert.Equal(expected, javascriptResponse.Result.ToString()); + } + + [Theory] + [InlineData("new Promise(function(resolve, reject) { reject('reject test'); });", "reject test")] + [InlineData("(async () => { throw('reject test'); })();", "reject test")] + public async Task ShouldFailForPromisePrimative(string script, string expected) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsync(script); + + Assert.False(javascriptResponse.Success); + Assert.Equal(expected, javascriptResponse.Message); + } + + [Theory] + [InlineData("new Promise(function(resolve, reject) { resolve({ a: 'CefSharp', b: 42, }); });", "CefSharp", "42")] + [InlineData("new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { a: 'CefSharp', b: 42, }), 1000); });", "CefSharp", "42")] + [InlineData("(async () => { function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }; async function getValAfterSleep() { await sleep(1000); return { a: 'CefSharp', b: 42 }; }; await sleep(2000); const result = await getValAfterSleep(); await sleep(2000); return result; })();", "CefSharp", "42")] + public async Task ShouldWorkForPromisePrimativeObject(string script, string expectedA, string expectedB) + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsync(script); + + Assert.True(javascriptResponse.Success); + + dynamic result = javascriptResponse.Result; + Assert.Equal(expectedA, result.a.ToString()); + Assert.Equal(expectedB, result.b.ToString()); + } + + [Fact] + public async Task ShouldLoadGoogleAndEvaluateScript() + { + AssertInitialLoadComplete(); + + var loadResponse = await Browser.LoadUrlAsync("www.google.com"); + + Assert.True(loadResponse.Success); + + var mainFrame = Browser.GetMainFrame(); + Assert.True(mainFrame.IsValid); + Assert.Contains("www.google", mainFrame.Url); + + var response = await Browser.EvaluateScriptAndAssertAsync("2 + 2"); + Assert.Equal(4, response); + output.WriteLine("Result of 2 + 2: {0}", response); + } + + [Fact] + public async Task CanEvaluateScriptInParallel() + { + AssertInitialLoadComplete(); + + var tasks = Enumerable.Range(0, 100).Select(i => Task.Run(async () => + { + var javascriptResponse = await Browser.EvaluateScriptAsync("2 + 2"); + + if (javascriptResponse.Success) + { + return (int)javascriptResponse.Result; + } + + return -1; + })).ToList(); + + await Task.WhenAll(tasks); + + Assert.All(tasks, (t) => + { + Assert.Equal(4, t.Result); + }); + } + + [Theory] + [InlineData("[1,2,,5]", new object[] { 1, 2, null, 5 })] + [InlineData("[1,2,,]", new object[] { 1, 2, null })] + [InlineData("[,2,3]", new object[] { null, 2, 3 })] + [InlineData("[,2,,3,,4,,,,5,,,]", new object[] { null, 2, null, 3, null, 4, null, null, null, 5, null, null })] + public async Task CanEvaluateScriptAsyncReturnPartiallyEmptyArrays(string javascript, object[] expected) + { + AssertInitialLoadComplete(); + + var result = await Browser.EvaluateScriptAsync(javascript); + + Assert.True(result.Success); + Assert.Equal(expected, result.Result); + } + + /// + /// Use the EvaluateScriptAsync (IWebBrowser, String,Object[]) overload and pass in string params + /// that require encoding. Test case for https://github.com/cefsharp/CefSharp/issues/2339 + /// + /// A task + [Fact] + public async Task CanEvaluateScriptAsyncWithEncodedStringArguments() + { + AssertInitialLoadComplete(); + + var javascriptResponse = await Browser.EvaluateScriptAsync("var testfunc=function(s) { return s; }"); + Assert.True(javascriptResponse.Success); + + // now call the function we just created + string[] teststrings = new string[]{"Mary's\tLamb & \r\nOther Things", + "[{test:\"Mary's Lamb & \\nOther Things\", 'other': \"\", 'and': null}]" }; + foreach (var test in teststrings) + { + javascriptResponse = await Browser.EvaluateScriptAsync("testfunc", test); + Assert.True(javascriptResponse.Success); + Assert.Equal(test, (string)javascriptResponse.Result); + output.WriteLine("{0} passes {1}", test, javascriptResponse.Result); + } + } + } +} diff --git a/CefSharp.Test/Javascript/JavascriptCallbackFacts.cs b/CefSharp.Test/Javascript/JavascriptCallbackTests.cs similarity index 75% rename from CefSharp.Test/Javascript/JavascriptCallbackFacts.cs rename to CefSharp.Test/Javascript/JavascriptCallbackTests.cs index 29508d308..18422f52c 100644 --- a/CefSharp.Test/Javascript/JavascriptCallbackFacts.cs +++ b/CefSharp.Test/Javascript/JavascriptCallbackTests.cs @@ -11,17 +11,15 @@ using Xunit.Abstractions; namespace CefSharp.Test.Javascript { [Collection(CefSharpFixtureCollection.Key)] - public class JavascriptCallbackFacts : IClassFixture + public class JavascriptCallbackTests : BrowserTests { private readonly ITestOutputHelper output; private readonly CefSharpFixture collectionFixture; - private readonly ChromiumWebBrowserOffScreenFixture classFixture; - public JavascriptCallbackFacts(ITestOutputHelper output, CefSharpFixture collectionFixture, ChromiumWebBrowserOffScreenFixture classFixture) + public JavascriptCallbackTests(ITestOutputHelper output, CefSharpFixture collectionFixture) { this.output = output; this.collectionFixture = collectionFixture; - this.classFixture = classFixture; } [Theory] @@ -29,13 +27,11 @@ namespace CefSharp.Test.Javascript [InlineData("(function() { return Promise.resolve('53')})", "53")] [InlineData("(function() { return Promise.resolve(true)})", true)] [InlineData("(function() { return Promise.resolve(false)})", false)] - public async Task CanEvaluatePromise(string script, object expected) + public async Task ShouldWorkForPromise(string script, object expected) { - var browser = classFixture.Browser; + AssertInitialLoadComplete(); - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync(script); + var javascriptResponse = await Browser.EvaluateScriptAsync(script); Assert.True(javascriptResponse.Success); var callback = (IJavascriptCallback)javascriptResponse.Result; @@ -54,13 +50,11 @@ namespace CefSharp.Test.Javascript [InlineData("(function() { return Promise.reject(42)})", "42")] [InlineData("(function() { return Promise.reject(false)})", "false")] [InlineData("(function() { return Promise.reject(null)})", "null")] - public async Task CanEvaluatePromiseRejected(string script, string expected) + public async Task ShouldFailForPromise(string script, string expected) { - var browser = classFixture.Browser; + AssertInitialLoadComplete(); - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync(script); + var javascriptResponse = await Browser.EvaluateScriptAsync(script); Assert.True(javascriptResponse.Success); var callback = (IJavascriptCallback)javascriptResponse.Result; @@ -78,13 +72,9 @@ namespace CefSharp.Test.Javascript [InlineData(double.MaxValue, "Number.MAX_VALUE")] [InlineData(double.MaxValue / 2, "Number.MAX_VALUE / 2")] //https://github.com/cefsharp/CefSharp/issues/3858 - public async Task CanEvaluateDoubleComputation(double expectedValue, string script) + public async Task ShouldWorkForDoubleComputation(double expectedValue, string script) { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync("(function() { return " + script + "})"); + var javascriptResponse = await Browser.EvaluateScriptAsync("(function() { return " + script + "})"); Assert.True(javascriptResponse.Success); var callback = (IJavascriptCallback)javascriptResponse.Result; @@ -113,13 +103,9 @@ namespace CefSharp.Test.Javascript [InlineData(((double)uint.MaxValue * 2))] [InlineData(((double)uint.MaxValue * 2) + 0.1)] //https://github.com/cefsharp/CefSharp/issues/3858 - public async Task CanEvaluateDoubleValues(double num) + public async Task ShouldWorkForDouble(double num) { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync("(function() { return " + num + "})"); + var javascriptResponse = await Browser.EvaluateScriptAsync("(function() { return " + num + "})"); Assert.True(javascriptResponse.Success); var callback = (IJavascriptCallback)javascriptResponse.Result; @@ -138,13 +124,9 @@ namespace CefSharp.Test.Javascript [InlineData(int.MaxValue)] [InlineData(int.MinValue)] //https://github.com/cefsharp/CefSharp/issues/3858 - public async Task CanEvaluateIntValues(object num) + public async Task ShouldWorkForInt(object num) { - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync("(function() { return " + num.ToString() + "})"); + var javascriptResponse = await Browser.EvaluateScriptAsync("(function() { return " + num.ToString() + "})"); Assert.True(javascriptResponse.Success); var callback = (IJavascriptCallback)javascriptResponse.Result; @@ -160,13 +142,11 @@ namespace CefSharp.Test.Javascript [InlineData("1970-01-01", "1970-01-01")] [InlineData("1980-01-01", "1980-01-01")] //https://github.com/cefsharp/CefSharp/issues/4234 - public async Task CanEvaluateDateValues(DateTime expected, string actual) + public async Task ShouldWorkForDate(DateTime expected, string actual) { - var browser = classFixture.Browser; + AssertInitialLoadComplete(); - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync("(function() { return new Date('" + actual + "');})"); + var javascriptResponse = await Browser.EvaluateScriptAsync("(function() { return new Date('" + actual + "');})"); Assert.True(javascriptResponse.Success); var callback = (IJavascriptCallback)javascriptResponse.Result; @@ -186,15 +166,13 @@ namespace CefSharp.Test.Javascript [InlineData("1980-01-01", DateTimeStyles.AssumeLocal)] [InlineData("1980-01-01", DateTimeStyles.AssumeUniversal)] //https://github.com/cefsharp/CefSharp/issues/4234 - public async Task CanEchoDateTime(string expected, DateTimeStyles dateTimeStyle) + public async Task ShouldEchoDateTime(string expected, DateTimeStyles dateTimeStyle) { + AssertInitialLoadComplete(); + var expectedDateTime = DateTime.Parse(expected, CultureInfo.InvariantCulture, dateTimeStyle); - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync("(function(p) { return p; })"); + var javascriptResponse = await Browser.EvaluateScriptAsync("(function(p) { return p; })"); Assert.True(javascriptResponse.Success); var callback = (IJavascriptCallback)javascriptResponse.Result; @@ -210,15 +188,13 @@ namespace CefSharp.Test.Javascript [Fact] //https://github.com/cefsharp/CefSharp/issues/4234 - public async Task CanEchoDateTimeNow() + public async Task ShouldEchoDateTimeNow() { + AssertInitialLoadComplete(); + var expectedDateTime = DateTime.Now; - var browser = classFixture.Browser; - - Assert.False(browser.IsLoading); - - var javascriptResponse = await browser.EvaluateScriptAsync("(function(p) { return p; })"); + var javascriptResponse = await Browser.EvaluateScriptAsync("(function(p) { return p; })"); Assert.True(javascriptResponse.Success); var callback = (IJavascriptCallback)javascriptResponse.Result; diff --git a/CefSharp.Test/JavascriptBinding/BindingTestObject.cs b/CefSharp.Test/JavascriptBinding/BindingTestObject.cs new file mode 100644 index 000000000..2fc702e44 --- /dev/null +++ b/CefSharp.Test/JavascriptBinding/BindingTestObject.cs @@ -0,0 +1,17 @@ +// Copyright © 2017 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. + +namespace CefSharp.Test.JavascriptBinding +{ + internal class BindingTestObject + { + public int EchoMethodCallCount { get; private set; } + public string Echo(string arg) + { + EchoMethodCallCount++; + + return arg; + } + } +} diff --git a/CefSharp.Test/JavascriptBinding/IntegrationTestFacts.cs b/CefSharp.Test/JavascriptBinding/IntegrationTests.cs similarity index 56% rename from CefSharp.Test/JavascriptBinding/IntegrationTestFacts.cs rename to CefSharp.Test/JavascriptBinding/IntegrationTests.cs index b872be25e..60d496c21 100644 --- a/CefSharp.Test/JavascriptBinding/IntegrationTestFacts.cs +++ b/CefSharp.Test/JavascriptBinding/IntegrationTests.cs @@ -2,12 +2,9 @@ // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. -using System.Diagnostics; using System.Threading.Tasks; -using CefSharp.Event; using CefSharp.Example; using CefSharp.Example.JavascriptBinding; -using CefSharp.Internals; using CefSharp.OffScreen; using Xunit; using Xunit.Abstractions; @@ -15,20 +12,16 @@ using Xunit.Abstractions; namespace CefSharp.Test.JavascriptBinding { /// - /// This is more a set of integration tests than it is unit tests, for now we need to - /// run our QUnit tests in an automated fashion and some other testing. + /// Automated QUnit Integration Tests /// - //TODO: Improve Test Naming, we need a naming scheme that fits these cases that's consistent - //(Ideally we implement consistent naming accross all test classes, though I'm open to a different - //naming convention as these are more integration tests than unit tests). //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle [Collection(CefSharpFixtureCollection.Key)] - public class IntegrationTestFacts + public class IntegrationTests { private readonly ITestOutputHelper output; private readonly CefSharpFixture fixture; - public IntegrationTestFacts(ITestOutputHelper output, CefSharpFixture fixture) + public IntegrationTests(ITestOutputHelper output, CefSharpFixture fixture) { this.fixture = fixture; this.output = output; @@ -206,135 +199,5 @@ namespace CefSharp.Test.JavascriptBinding } } #endif - - [Fact] - public async Task IsObjectCachedWithInvalidObjectNameReturnsFalse() - { - using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl)) - { - await browser.WaitForInitialLoadAsync(); - - //We'll execute twice using the different cased (camelcase naming and standard) - var response = await browser.EvaluateScriptAsync("CefSharp.IsObjectCached('doesntexist')"); - - Assert.True(response.Success); - Assert.False((bool)response.Result); - - response = await browser.EvaluateScriptAsync("cefSharp.isObjectCached('doesntexist')"); - - Assert.True(response.Success); - Assert.False((bool)response.Result); - } - } - - [Fact] - public async Task JsBindingGlobalObjectNameCustomValueExecuteIsObjectCachedSuccess() - { - using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl, automaticallyCreateBrowser: false)) - { - var settings = browser.JavascriptObjectRepository.Settings; - settings.JavascriptBindingApiGlobalObjectName = "bindingApiObject"; - - //To modify the settings we need to defer browser creation slightly - browser.CreateBrowser(); - - await browser.WaitForInitialLoadAsync(); - - var result = await browser.EvaluateScriptAsync("bindingApiObject.isObjectCached('doesntexist') === false"); - - Assert.True(result.Success); - } - } - - [Fact] - public async Task JsBindingGlobalApiDisabled() - { - using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl, automaticallyCreateBrowser: false)) - { - var settings = browser.JavascriptObjectRepository.Settings; - settings.JavascriptBindingApiEnabled = false; - - //To modify the settings we need to defer browser creation slightly - browser.CreateBrowser(); - - var loadResponse = await browser.WaitForInitialLoadAsync(); - - Assert.True(loadResponse.Success); - - var response1 = await browser.EvaluateScriptAsync("typeof window.cefSharp === 'undefined'"); - var response2 = await browser.EvaluateScriptAsync("typeof window.CefSharp === 'undefined'"); - - Assert.True(response1.Success); - Assert.True((bool)response1.Result); - - Assert.True(response2.Success); - Assert.True((bool)response2.Result); - } - } - - [Fact] - public async Task JsBindingGlobalApiEnabled() - { - using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl, automaticallyCreateBrowser: false)) - { - var settings = browser.JavascriptObjectRepository.Settings; - settings.JavascriptBindingApiEnabled = true; - - //To modify the settings we need to defer browser creation slightly - browser.CreateBrowser(); - - await browser.WaitForInitialLoadAsync(); - - var response1 = await browser.EvaluateScriptAsync("typeof window.cefSharp === 'undefined'"); - var response2 = await browser.EvaluateScriptAsync("typeof window.CefSharp === 'undefined'"); - - Assert.True(response1.Success); - Assert.False((bool)response1.Result); - - Assert.True(response2.Success); - Assert.False((bool)response2.Result); - } - } - - [Theory] - [InlineData("CefSharp.RenderProcessId")] - [InlineData("cefSharp.renderProcessId")] - public async Task JsBindingRenderProcessId(string script) - { - using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl)) - { - await browser.WaitForInitialLoadAsync(); - - var result = await browser.EvaluateScriptAsync(script); - - Assert.True(result.Success); - - using (var process = Process.GetProcessById(Assert.IsType(result.Result))) - { - Assert.Equal("CefSharp.BrowserSubprocess", process.ProcessName); - } - } - } - - [Fact] - //Issue https://github.com/cefsharp/CefSharp/issues/3470 - //Verify workaround passes - public async Task CanCallCefSharpBindObjectAsyncWithoutParams() - { - using (var browser = new ChromiumWebBrowser(CefExample.HelloWorldUrl)) - { - await browser.WaitForInitialLoadAsync(); - - //TODO: See if we can avoid GetAwaiter().GetResult() - var evt = Assert.Raises( - x => browser.JavascriptObjectRepository.ResolveObject += x, - y => browser.JavascriptObjectRepository.ResolveObject -= y, - () => { browser.EvaluateScriptAsync("CefSharp.BindObjectAsync();").GetAwaiter().GetResult(); }); - - Assert.NotNull(evt); - - Assert.Equal(JavascriptObjectRepository.AllObjects, evt.Arguments.ObjectName); - } - } } } diff --git a/CefSharp.Test/JavascriptBinding/JavaScriptObjectRepositoryFacts.cs b/CefSharp.Test/JavascriptBinding/JavaScriptObjectRepositoryTests.cs similarity index 93% rename from CefSharp.Test/JavascriptBinding/JavaScriptObjectRepositoryFacts.cs rename to CefSharp.Test/JavascriptBinding/JavaScriptObjectRepositoryTests.cs index 03c0b9981..c1679612f 100644 --- a/CefSharp.Test/JavascriptBinding/JavaScriptObjectRepositoryFacts.cs +++ b/CefSharp.Test/JavascriptBinding/JavaScriptObjectRepositoryTests.cs @@ -27,10 +27,10 @@ internal class SomeElseClass namespace CefSharp.Test.JavascriptBinding { - public class JavaScriptObjectRepositoryFacts + public class JavaScriptObjectRepositoryTests { [Fact] - public void CanRegisterJavascriptObjectBindWhenNamespaceIsNull() + public void ShouldRegisterJavascriptObjectBindWhenNamespaceIsNull() { IJavascriptObjectRepositoryInternal javascriptObjectRepository = new JavascriptObjectRepository(); var name = nameof(NoNamespaceClass); @@ -61,7 +61,7 @@ namespace CefSharp.Test.JavascriptBinding #if !NETCOREAPP [Fact] - public void CanRegisterJavascriptObjectPropertyBindWhenNamespaceIsNull() + public void ShouldRegisterJavascriptObjectPropertyBindWhenNamespaceIsNull() { IJavascriptObjectRepositoryInternal javascriptObjectRepository = new JavascriptObjectRepository(); var name = nameof(NoNamespaceClass); diff --git a/CefSharp.Test/JavascriptBinding/JavascriptBindingTests.cs b/CefSharp.Test/JavascriptBinding/JavascriptBindingTests.cs new file mode 100644 index 000000000..ca405795a --- /dev/null +++ b/CefSharp.Test/JavascriptBinding/JavascriptBindingTests.cs @@ -0,0 +1,211 @@ +// 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.Diagnostics; +using System.Threading.Tasks; +using CefSharp.Event; +using CefSharp.Example; +using CefSharp.Internals; +using CefSharp.OffScreen; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.JavascriptBinding +{ + [Collection(CefSharpFixtureCollection.Key)] + public class JavascriptBindingTests : BrowserTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public JavascriptBindingTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [Fact] + //Issue https://github.com/cefsharp/CefSharp/issues/3470 + //Verify workaround passes + public async Task ShouldWork() + { + AssertInitialLoadComplete(); + + var evt = await Assert.RaisesAsync( + x => Browser.JavascriptObjectRepository.ResolveObject += x, + y => Browser.JavascriptObjectRepository.ResolveObject -= y, + () => Browser.EvaluateScriptAsync("CefSharp.BindObjectAsync();")); + + Assert.NotNull(evt); + + Assert.Equal(JavascriptObjectRepository.AllObjects, evt.Arguments.ObjectName); + } + + [Fact] + public async Task ShouldWorkWhenUsingCustomGlobalObjectName() + { + using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl, automaticallyCreateBrowser: false)) + { + var settings = browser.JavascriptObjectRepository.Settings; + settings.JavascriptBindingApiGlobalObjectName = "bindingApiObject"; + + //To modify the settings we need to defer browser creation slightly + browser.CreateBrowser(); + + await browser.WaitForInitialLoadAsync(); + + var result = await browser.EvaluateScriptAsync("bindingApiObject.isObjectCached('doesntexist') === false"); + + Assert.True(result.Success); + } + } + + [Theory] + //We'll execute twice using the different cased (camelcase naming and standard) + [InlineData("CefSharp.IsObjectCached('doesntexist')")] + [InlineData("cefSharp.isObjectCached('doesntexist')")] + public async Task ShouldFailWhenIsObjectCachedCalledWithInvalidObjectName(string script) + { + var loadResponse = await Browser.LoadUrlAsync(CefExample.BindingApiCustomObjectNameTestUrl); + + Assert.True(loadResponse.Success); + + var response = await Browser.EvaluateScriptAsync(script); + + Assert.True(response.Success); + Assert.False((bool)response.Result); + } + + [Fact] + public async Task ShouldDisableJsBindingApi() + { + using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl, automaticallyCreateBrowser: false)) + { + var settings = browser.JavascriptObjectRepository.Settings; + settings.JavascriptBindingApiEnabled = false; + + //To modify the settings we need to defer browser creation slightly + browser.CreateBrowser(); + + var loadResponse = await browser.WaitForInitialLoadAsync(); + + Assert.True(loadResponse.Success); + + var response1 = await browser.EvaluateScriptAsync("typeof window.cefSharp === 'undefined'"); + var response2 = await browser.EvaluateScriptAsync("typeof window.CefSharp === 'undefined'"); + + Assert.True(response1.Success); + Assert.True((bool)response1.Result); + + Assert.True(response2.Success); + Assert.True((bool)response2.Result); + } + } + + [Fact] + public async Task ShouldEnableJsBindingApi() + { + using (var browser = new ChromiumWebBrowser(CefExample.BindingApiCustomObjectNameTestUrl, automaticallyCreateBrowser: false)) + { + var settings = browser.JavascriptObjectRepository.Settings; + settings.JavascriptBindingApiEnabled = true; + + //To modify the settings we need to defer browser creation slightly + browser.CreateBrowser(); + + await browser.WaitForInitialLoadAsync(); + + var response1 = await browser.EvaluateScriptAsync("typeof window.cefSharp === 'undefined'"); + var response2 = await browser.EvaluateScriptAsync("typeof window.CefSharp === 'undefined'"); + + Assert.True(response1.Success); + Assert.False((bool)response1.Result); + + Assert.True(response2.Success); + Assert.False((bool)response2.Result); + } + } + + [Theory] + [InlineData("CefSharp.RenderProcessId")] + [InlineData("cefSharp.renderProcessId")] + public async Task ShouldReturnRenderProcessId(string script) + { + var result = await Browser.EvaluateScriptAsync(script); + + Assert.True(result.Success); + + using (var process = Process.GetProcessById(Assert.IsType(result.Result))) + { + Assert.Equal("CefSharp.BrowserSubprocess", process.ProcessName); + } + } + + [Fact] + public async Task ShouldWorkAfterACrossOriginNavigation() + { + const string script = @" + (async function() + { + await CefSharp.BindObjectAsync('bound'); + return await bound.echo('test'); + })();"; + + var boundObj = new BindingTestObject(); + +#if NETCOREAPP + Browser.JavascriptObjectRepository.Register("bound", boundObj); +#else + Browser.JavascriptObjectRepository.Register("bound", boundObj, true); +#endif + + await Browser.LoadUrlAsync("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url"); + await Browser.EvaluateScriptAndAssertAsync(script); + await Browser.LoadUrlAsync("https://www.google.com"); + await Browser.EvaluateScriptAndAssertAsync(script); + + Assert.Equal(2, boundObj.EchoMethodCallCount); + } + + [Fact] + public async Task ShouldFireResolveObject() + { + AssertInitialLoadComplete(); + + var objRepository = Browser.JavascriptObjectRepository; + + var evt = await Assert.RaisesAsync( + a => objRepository.ResolveObject += a, + a => objRepository.ResolveObject -= a, + () => Browser.EvaluateScriptAsync("(async function() { await CefSharp.BindObjectAsync('first'); })();")); + + Assert.NotNull(evt); + Assert.Equal("first", evt.Arguments.ObjectName); + } + + [Fact] + public async Task ShouldFireResolveObjectForUnregisteredObject() + { + AssertInitialLoadComplete(); + + var objRepository = Browser.JavascriptObjectRepository; + + var boundObj = new BindingTestObject(); + +#if NETCOREAPP + objRepository.Register("first", boundObj); +#else + objRepository.Register("first", boundObj, true); +#endif + + var evt = await Assert.RaisesAsync( + a => objRepository.ResolveObject += a, + a => objRepository.ResolveObject -= a, + () => Browser.EvaluateScriptAsync("(async function() { await CefSharp.BindObjectAsync('first', 'second'); })();")); + + Assert.NotNull(evt); + Assert.Equal("second", evt.Arguments.ObjectName); + } + } +} diff --git a/CefSharp.Test/OffScreen/BrowserRefCountTests.cs b/CefSharp.Test/OffScreen/BrowserRefCountTests.cs new file mode 100644 index 000000000..1a51aaa76 --- /dev/null +++ b/CefSharp.Test/OffScreen/BrowserRefCountTests.cs @@ -0,0 +1,58 @@ +// Copyright © 2022 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.Threading; +using CefSharp.Internals; +using CefSharp.OffScreen; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.OffScreen +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class BrowserRefCountTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public BrowserRefCountTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [Fact] + public void ShouldWork() + { + var currentCount = BrowserRefCounter.Instance.Count; + + var manualResetEvent = new ManualResetEvent(false); + + var browser = new ChromiumWebBrowser("https://google.com", useLegacyRenderHandler: false); + + browser.LoadingStateChanged += (sender, e) => + { + if (!e.IsLoading) + { + manualResetEvent.Set(); + } + }; + + manualResetEvent.WaitOne(); + + //TODO: Refactor this so reference is injected into browser + Assert.Equal(currentCount + 1, BrowserRefCounter.Instance.Count); + + browser.Dispose(); + + Cef.WaitForBrowsersToClose(10000); + + output.WriteLine("BrowserRefCounter Log"); + output.WriteLine(BrowserRefCounter.Instance.GetLog()); + + Assert.Equal(0, BrowserRefCounter.Instance.Count); + } + } +} diff --git a/CefSharp.Test/OffScreen/DownloadHandlerTests.cs b/CefSharp.Test/OffScreen/DownloadHandlerTests.cs new file mode 100644 index 000000000..755abcf65 --- /dev/null +++ b/CefSharp.Test/OffScreen/DownloadHandlerTests.cs @@ -0,0 +1,71 @@ +// Copyright © 2022 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.Threading.Tasks; +using CefSharp.OffScreen; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.OffScreen +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class DownloadHandlerTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public DownloadHandlerTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [Theory] + [InlineData("https://code.jquery.com/jquery-3.4.1.min.js")] + public async Task ShouldWorkWithoutAskingUser(string url) + { + var tcs = new TaskCompletionSource(TaskContinuationOptions.RunContinuationsAsynchronously); + + using (var chromiumWebBrowser = new ChromiumWebBrowser(url, useLegacyRenderHandler: false)) + { + var userTempPath = System.IO.Path.GetTempPath(); + + chromiumWebBrowser.DownloadHandler = + Fluent.DownloadHandler.UseFolder(userTempPath, + (chromiumBrowser, browser, downloadItem, callback) => + { + if (downloadItem.IsComplete) + { + tcs.SetResult(downloadItem.FullPath); + } + else if (downloadItem.IsCancelled) + { + tcs.SetResult(null); + } + }); + + await chromiumWebBrowser.WaitForInitialLoadAsync(); + + chromiumWebBrowser.StartDownload(url); + + var downloadedFilePath = await tcs.Task; + + Assert.NotNull(downloadedFilePath); + Assert.Contains(userTempPath, downloadedFilePath); + Assert.True(System.IO.File.Exists(downloadedFilePath)); + + var downloadedFileContent = System.IO.File.ReadAllText(downloadedFilePath); + + Assert.NotEqual(0, downloadedFileContent.Length); + + var htmlSrc = await chromiumWebBrowser.GetSourceAsync(); + + Assert.Contains(downloadedFileContent.Substring(0, 100), htmlSrc); + + System.IO.File.Delete(downloadedFilePath); + } + } + } +} diff --git a/CefSharp.Test/OffScreen/OffScreenBrowserBasicFacts.cs b/CefSharp.Test/OffScreen/OffScreenBrowserBasicFacts.cs deleted file mode 100644 index fcf757566..000000000 --- a/CefSharp.Test/OffScreen/OffScreenBrowserBasicFacts.cs +++ /dev/null @@ -1,843 +0,0 @@ -// Copyright © 2017 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.Drawing; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using CefSharp.DevTools.Page; -using CefSharp.Example; -using CefSharp.Example.Handlers; -using CefSharp.Internals; -using CefSharp.OffScreen; -using CefSharp.Web; -using Xunit; -using Xunit.Abstractions; - -namespace CefSharp.Test.OffScreen -{ - //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle - [Collection(CefSharpFixtureCollection.Key)] - public class OffScreenBrowserBasicFacts - { - //TODO: Move into own file/namespace - public class AsyncBoundObject - { - public bool MethodCalled { get; set; } - public string Echo(string arg) - { - MethodCalled = true; - return arg; - } - } - - private readonly ITestOutputHelper output; - private readonly CefSharpFixture fixture; - - public OffScreenBrowserBasicFacts(ITestOutputHelper output, CefSharpFixture fixture) - { - this.fixture = fixture; - this.output = output; - } - - [Fact] - public async Task CanLoadGoogle() - { - using (var browser = new ChromiumWebBrowser("www.google.com", useLegacyRenderHandler:false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("www.google", mainFrame.Url); - Assert.Equal(200, response.HttpStatusCode); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [Fact] - public async Task ShouldRespectDisposed() - { - ChromiumWebBrowser browser; - - using (browser = new ChromiumWebBrowser(CefExample.DefaultUrl, useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Equal(CefExample.DefaultUrl, mainFrame.Url); - Assert.Equal(200, response.HttpStatusCode); - - output.WriteLine("Url {0}", mainFrame.Url); - } - - Assert.True(browser.IsDisposed); - - Assert.Throws(() => - { - browser.Copy(); - }); - } - - [Fact] - public async Task CanLoadInvalidDomain() - { - using (var browser = new ChromiumWebBrowser("notfound.cefsharp.test", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("notfound.cefsharp.test", mainFrame.Url); - Assert.Equal(CefErrorCode.NameNotResolved, response.ErrorCode); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [Fact] - public async Task CanLoadExpiredBadSsl() - { - using (var browser = new ChromiumWebBrowser("https://expired.badssl.com/", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("", mainFrame.Url); - Assert.Equal(-1, response.HttpStatusCode); - Assert.Equal(CefErrorCode.CertDateInvalid, response.ErrorCode); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [Fact] - public void BrowserRefCountDecrementedOnDispose() - { - var currentCount = BrowserRefCounter.Instance.Count; - - var manualResetEvent = new ManualResetEvent(false); - - var browser = new ChromiumWebBrowser("https://google.com", useLegacyRenderHandler: false); - browser.LoadingStateChanged += (sender, e) => - { - if (!e.IsLoading) - { - manualResetEvent.Set(); - } - }; - - manualResetEvent.WaitOne(); - - //TODO: Refactor this so reference is injected into browser - Assert.Equal(currentCount + 1, BrowserRefCounter.Instance.Count); - - browser.Dispose(); - - Cef.WaitForBrowsersToClose(10000); - - output.WriteLine("BrowserRefCounter Log"); - output.WriteLine(BrowserRefCounter.Instance.GetLog()); - - Assert.Equal(0, BrowserRefCounter.Instance.Count); - } - - [Fact] - public async Task CanCreateBrowserAsync() - { - using (var chromiumWebBrowser = new ChromiumWebBrowser("http://www.google.com", automaticallyCreateBrowser: false, useLegacyRenderHandler: false)) - { - var browser = await chromiumWebBrowser.CreateBrowserAsync(); - - Assert.NotNull(browser); - Assert.False(browser.HasDocument); - Assert.NotEqual(0, browser.Identifier); - Assert.False(browser.IsDisposed); - } - } - - [Fact] - public async Task CanLoadGoogleAndEvaluateScript() - { - using (var browser = new ChromiumWebBrowser("www.google.com", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("www.google", mainFrame.Url); - - var javascriptResponse = await browser.EvaluateScriptAsync("2 + 2"); - Assert.True(javascriptResponse.Success); - Assert.Equal(4, (int)javascriptResponse.Result); - output.WriteLine("Result of 2 + 2: {0}", javascriptResponse.Result); - } - } - - [Fact] - public async Task CanEvaluateScriptInParallel() - { - using (var browser = new ChromiumWebBrowser("www.google.com", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var tasks = Enumerable.Range(0, 100).Select(i => Task.Run(async () => - { - var javascriptResponse = await browser.EvaluateScriptAsync("2 + 2"); - - if (javascriptResponse.Success) - { - return (int)javascriptResponse.Result; - } - - return -1; - })).ToList(); - - await Task.WhenAll(tasks); - - Assert.All(tasks, (t) => - { - Assert.Equal(4, t.Result); - }); - } - } - - [Theory] - [InlineData("[1,2,,5]", new object[] { 1, 2, null, 5 })] - [InlineData("[1,2,,]", new object[] { 1, 2, null })] - [InlineData("[,2,3]", new object[] { null, 2, 3 })] - [InlineData("[,2,,3,,4,,,,5,,,]", new object[] { null, 2, null, 3, null, 4, null, null, null, 5, null, null })] - public async Task CanEvaluateScriptAsyncReturnPartiallyEmptyArrays(string javascript, object[] expected) - { - using (var browser = new ChromiumWebBrowser(CefExample.HelloWorldUrl, useLegacyRenderHandler: false)) - { - await browser.WaitForInitialLoadAsync(); - - var result = await browser.EvaluateScriptAsync(javascript); - - Assert.True(result.Success); - Assert.Equal(expected, result.Result); - } - } - - [Fact] - public async Task CrossSiteNavigationJavascriptBinding() - { - const string script = @" - (async function() - { - await CefSharp.BindObjectAsync('bound'); - bound.echo('test'); - })();"; - - var boundObj = new AsyncBoundObject(); - - using (var browser = new ChromiumWebBrowser("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url", useLegacyRenderHandler: false)) - { -#if NETCOREAPP - browser.JavascriptObjectRepository.Register("bound", boundObj); -#else - browser.JavascriptObjectRepository.Register("bound", boundObj, true); -#endif - - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - browser.GetMainFrame().ExecuteJavaScriptAsync(script); - - await Task.Delay(2000); - Assert.True(boundObj.MethodCalled); - - boundObj.MethodCalled = false; - - browser.Load("https://www.google.com"); - await browser.WaitForInitialLoadAsync(); - browser.GetMainFrame().ExecuteJavaScriptAsync(script); - await Task.Delay(2000); - Assert.True(boundObj.MethodCalled); - } - } - - [Fact] - public async Task JavascriptBindingMultipleObjects() - { - const string script = @" - (async function() - { - await CefSharp.BindObjectAsync('first'); - await CefSharp.BindObjectAsync('first', 'second'); - })();"; - - var objectNames = new List(); - var boundObj = new AsyncBoundObject(); - - using (var browser = new ChromiumWebBrowser("https://www.google.com", useLegacyRenderHandler: false)) - { - browser.JavascriptObjectRepository.ResolveObject += (s, e) => - { - objectNames.Add(e.ObjectName); -#if NETCOREAPP - e.ObjectRepository.Register(e.ObjectName, boundObj); -#else - e.ObjectRepository.Register(e.ObjectName, boundObj, isAsync: true); -#endif - }; - - await browser.WaitForInitialLoadAsync(); - browser.GetMainFrame().ExecuteJavaScriptAsync(script); - - await Task.Delay(2000); - Assert.Equal(new[] { "first", "second" }, objectNames); - } - } - - /// - /// Use the EvaluateScriptAsync (IWebBrowser, String,Object[]) overload and pass in string params - /// that require encoding. Test case for https://github.com/cefsharp/CefSharp/issues/2339 - /// - /// A task - [Fact] - public async Task CanEvaluateScriptAsyncWithEncodedStringArguments() - { - using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - - var javascriptResponse = await browser.EvaluateScriptAsync("var testfunc=function(s) { return s; }"); - Assert.True(javascriptResponse.Success); - - // now call the function we just created - string[] teststrings = new string[]{"Mary's\tLamb & \r\nOther Things", - "[{test:\"Mary's Lamb & \\nOther Things\", 'other': \"\", 'and': null}]" }; - foreach (var test in teststrings) - { - javascriptResponse = await browser.EvaluateScriptAsync("testfunc", test); - Assert.True(javascriptResponse.Success); - Assert.Equal(test, (string)javascriptResponse.Result); - output.WriteLine("{0} passes {1}", test, javascriptResponse.Result); - } - } - } - - [Fact] - public async Task CanMakeFrameUrlRequest() - { - using (var browser = new ChromiumWebBrowser("https://code.jquery.com/jquery-3.4.1.min.js", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - - var taskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var wasCached = false; - var requestClient = new Example.UrlRequestClient((IUrlRequest req, byte[] responseBody) => - { - wasCached = req.ResponseWasCached; - taskCompletionSource.TrySetResult(Encoding.UTF8.GetString(responseBody)); - }); - - //Can be created on any valid CEF Thread, here we'll use the CEF UI Thread - await Cef.UIThreadTaskFactory.StartNew(delegate - { - var request = mainFrame.CreateRequest(false); - - request.Method = "GET"; - request.Url = "https://code.jquery.com/jquery-3.4.1.min.js"; - var urlRequest = mainFrame.CreateUrlRequest(request, requestClient); - }); - - var stringResult = await taskCompletionSource.Task; - - Assert.True(!string.IsNullOrEmpty(stringResult)); - Assert.True(wasCached); - } - } - - [Theory] - [InlineData("https://code.jquery.com/jquery-3.4.1.min.js")] - public async Task CanDownloadUrlForFrame(string url) - { - using (var browser = new ChromiumWebBrowser(url, useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var htmlSrc = await browser.GetSourceAsync(); - - Assert.NotNull(htmlSrc); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - - var data = await mainFrame.DownloadUrlAsync(url); - - Assert.NotNull(data); - Assert.True(data.Length > 0); - - var stringResult = Encoding.UTF8.GetString(data).Substring(0, 100); - - Assert.Contains(stringResult, htmlSrc); - } - } - - [Theory] - [InlineData("https://code.jquery.com/jquery-3.4.1.min.js")] - public async Task CanDownloadFileToFolderWithoutAskingUser(string url) - { - var tcs = new TaskCompletionSource(TaskContinuationOptions.RunContinuationsAsynchronously); - - using (var chromiumWebBrowser = new ChromiumWebBrowser(url, useLegacyRenderHandler: false)) - { - var userTempPath = System.IO.Path.GetTempPath(); - - chromiumWebBrowser.DownloadHandler = - Fluent.DownloadHandler.UseFolder(userTempPath, - (chromiumBrowser, browser, downloadItem, callback) => - { - if(downloadItem.IsComplete) - { - tcs.SetResult(downloadItem.FullPath); - } - else if(downloadItem.IsCancelled) - { - tcs.SetResult(null); - } - }); - - await chromiumWebBrowser.WaitForInitialLoadAsync(); - - chromiumWebBrowser.StartDownload(url); - - var downloadedFilePath = await tcs.Task; - - Assert.NotNull(downloadedFilePath); - Assert.Contains(userTempPath, downloadedFilePath); - Assert.True(System.IO.File.Exists(downloadedFilePath)); - - var downloadedFileContent = System.IO.File.ReadAllText(downloadedFilePath); - - Assert.NotEqual(0, downloadedFileContent.Length); - - var htmlSrc = await chromiumWebBrowser.GetSourceAsync(); - - Assert.Contains(downloadedFileContent.Substring(0, 100), htmlSrc); - - System.IO.File.Delete(downloadedFilePath); - } - } - - [Fact] - public async Task CanMakeUrlRequest() - { - var taskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - IUrlRequest urlRequest = null; - int statusCode = -1; - - //Can be created on any valid CEF Thread, here we'll use the CEF UI Thread - await Cef.UIThreadTaskFactory.StartNew(delegate - { - var requestClient = new Example.UrlRequestClient((IUrlRequest req, byte[] responseBody) => - { - statusCode = req.Response.StatusCode; - taskCompletionSource.TrySetResult(Encoding.UTF8.GetString(responseBody)); - }); - - var request = new Request - { - Method = "GET", - Url = "https://code.jquery.com/jquery-3.4.1.min.js" - }; - - //Global RequestContext will be used - urlRequest = new UrlRequest(request, requestClient); - }); - - var stringResult = await taskCompletionSource.Task; - - Assert.True(!string.IsNullOrEmpty(stringResult)); - Assert.Equal(200, statusCode); - } - - [Theory] - //TODO: Add more urls - [InlineData("http://www.google.com", "http://cefsharp.github.io/")] - public async Task CanExecuteJavascriptInMainFrameAfterNavigatingToDifferentOrigin(string firstUrl, string secondUrl) - { - using (var browser = new ChromiumWebBrowser(firstUrl, useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - Assert.True(browser.CanExecuteJavascriptInMainFrame); - - await browser.LoadUrlAsync(secondUrl); - - Assert.True(browser.CanExecuteJavascriptInMainFrame); - - await browser.LoadUrlAsync(firstUrl); - - Assert.True(browser.CanExecuteJavascriptInMainFrame); - } - } - - [Theory] - [InlineData("http://httpbin.org/post")] - public async Task CanLoadRequestWithPostData(string url) - { - const string data = "Testing123"; - //When Chromium Site Isolation is enabled we must first navigate to - //a web page of the same origin to use LoadRequest - //When Site Isolation is disabled we can navigate to any web page - //https://magpcss.org/ceforum/viewtopic.php?f=10&t=18672&p=50266#p50249 - using (var browser = new ChromiumWebBrowser("http://httpbin.org/", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var request = new Request - { - Url = "http://httpbin.org/post", - Method = "POST" - }; - var postData = new PostData(); - postData.AddElement(new PostDataElement - { - Bytes = Encoding.UTF8.GetBytes(data) - }); - - request.PostData = postData; - - await browser.LoadRequestAsync(request); - - var mainFrame = browser.GetMainFrame(); - Assert.Equal(url, mainFrame.Url); - - var navEntry = await browser.GetVisibleNavigationEntryAsync(); - - Assert.Equal((int)HttpStatusCode.OK, navEntry.HttpStatusCode); - Assert.True(navEntry.HasPostData); - - var source = await browser.GetTextAsync(); - - Assert.Contains(data, source); - } - } - - [SkipIfRunOnAppVeyorFact] - public async Task CanLoadHttpWebsiteUsingProxy() - { - fixture.StartProxyServerIfRequired(); - - var requestContext = RequestContext - .Configure() - .WithProxyServer("127.0.0.1", 8080) - .Create(); - - using (var browser = new ChromiumWebBrowser("http://cefsharp.github.io/", requestContext: requestContext, useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("cefsharp.github.io", mainFrame.Url); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [SkipIfRunOnAppVeyorFact] - public async Task CanLoadHttpWebsiteUsingSetProxyAsync() - { - fixture.StartProxyServerIfRequired(); - - var tcs = new TaskCompletionSource(); - - var requestContext = RequestContext - .Configure() - .OnInitialize((ctx) => - { - tcs.SetResult(true); - }) - .Create(); - - //Wait for our RequestContext to have initialized. - await tcs.Task; - - var setProxyResponse = await requestContext.SetProxyAsync("127.0.0.1", 8080); - - Assert.True(setProxyResponse.Success); - - using (var browser = new ChromiumWebBrowser("http://cefsharp.github.io/", requestContext: requestContext, useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("cefsharp.github.io", mainFrame.Url); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [SkipIfRunOnAppVeyorFact] - public async Task CanLoadHttpWebsiteUsingSetProxyOnUiThread() - { - fixture.StartProxyServerIfRequired(); - - var tcs = new TaskCompletionSource(); - - var requestContext = RequestContext - .Configure() - .OnInitialize((ctx) => - { - tcs.SetResult(true); - }) - .Create(); - - //Wait for our RequestContext to have initialized. - await tcs.Task; - - var success = false; - - //To execute on the CEF UI Thread you can use - await Cef.UIThreadTaskFactory.StartNew(delegate - { - string errorMessage; - - if (!requestContext.CanSetPreference("proxy")) - { - //Unable to set proxy, if you set proxy via command line args it cannot be modified. - success = false; - - return; - } - - success = requestContext.SetProxy("127.0.0.1", 8080, out errorMessage); - }); - - Assert.True(success); - - using (var browser = new ChromiumWebBrowser("http://cefsharp.github.io/", requestContext: requestContext, useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("cefsharp.github.io", mainFrame.Url); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [Fact] - public async Task CanWaitForBrowserInitialLoadAfterLoad() - { - using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("www.google.com", mainFrame.Url); - Assert.Equal(CefErrorCode.None, response.ErrorCode); - Assert.Equal(200, response.HttpStatusCode); - - output.WriteLine("Url {0}", mainFrame.Url); - - response = await browser.WaitForInitialLoadAsync(); - - Assert.Equal(CefErrorCode.None, response.ErrorCode); - Assert.Equal(200, response.HttpStatusCode); - } - } - - [Fact] - public async Task CanCallTryGetBrowserCoreByIdWithInvalidId() - { - using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - var result = browser.TryGetBrowserCoreById(100, out IBrowser browserCore); - - Assert.False(result); - Assert.Null(browserCore); - } - } - - [Fact] - public async Task CanCallTryGetBrowserCoreByIdWithOwnId() - { - using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - var result = browser.TryGetBrowserCoreById(browser.BrowserCore.Identifier, out IBrowser browserCore); - - Assert.True(result); - Assert.NotNull(browserCore); - Assert.Equal(browser.BrowserCore.Identifier, browserCore.Identifier); - } - } - - [Fact] - public async Task CanCaptureScreenshotAsync() - { - using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler:false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var result1 = await browser.CaptureScreenshotAsync(); - Assert.Equal(1366, browser.Size.Width); - Assert.Equal(768, browser.Size.Height); - Assert.Equal(1, browser.DeviceScaleFactor); - using (var screenshot = Image.FromStream(new MemoryStream(result1))) - { - Assert.Equal(1366, screenshot.Width); - Assert.Equal(768, screenshot.Height); - } - - - var result2 = await browser.CaptureScreenshotAsync(viewport: new Viewport { Width = 1366, Height = 768, X = 100, Y = 200, Scale = 2 }); - Assert.Equal(1466, browser.Size.Width); - Assert.Equal(968, browser.Size.Height); - Assert.Equal(2, browser.DeviceScaleFactor); - using (var screenshot = Image.FromStream(new MemoryStream(result2))) - { - Assert.Equal(2732, screenshot.Width); - Assert.Equal(1536, screenshot.Height); - } - - - var result3 = await browser.CaptureScreenshotAsync(viewport: new Viewport { Width = 100, Height = 200, Scale = 2 }); - Assert.Equal(1466, browser.Size.Width); - Assert.Equal(968, browser.Size.Height); - Assert.Equal(2, browser.DeviceScaleFactor); - using (var screenshot = Image.FromStream(new MemoryStream(result3))) - { - Assert.Equal(200, screenshot.Width); - Assert.Equal(400, screenshot.Height); - } - - var result4 = await browser.CaptureScreenshotAsync(viewport: new Viewport { Width = 100, Height = 200, Scale = 1 }); - Assert.Equal(1466, browser.Size.Width); - Assert.Equal(968, browser.Size.Height); - Assert.Equal(1, browser.DeviceScaleFactor); - using (var screenshot = Image.FromStream(new MemoryStream(result4))) - { - Assert.Equal(100, screenshot.Width); - Assert.Equal(200, screenshot.Height); - } - } - } - - [Fact] - public async Task CanResizeWithDeviceScalingFactor() - { - using (var browser = new ChromiumWebBrowser("http://www.google.com")) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - Assert.Equal(1366, browser.Size.Width); - Assert.Equal(768, browser.Size.Height); - Assert.Equal(1, browser.DeviceScaleFactor); - - - await browser.ResizeAsync(800, 600, 2); - - Assert.Equal(800, browser.Size.Width); - Assert.Equal(600, browser.Size.Height); - Assert.Equal(2, browser.DeviceScaleFactor); - - using (var screenshot = browser.ScreenshotOrNull()) - { - Assert.Equal(1600, screenshot.Width); - Assert.Equal(1200, screenshot.Height); - } - - await browser.ResizeAsync(400, 300); - - Assert.Equal(400, browser.Size.Width); - Assert.Equal(300, browser.Size.Height); - Assert.Equal(2, browser.DeviceScaleFactor); - - using (var screenshot = browser.ScreenshotOrNull()) - { - Assert.Equal(800, screenshot.Width); - Assert.Equal(600, screenshot.Height); - } - - await browser.ResizeAsync(1366, 768, 1); - - Assert.Equal(1366, browser.Size.Width); - Assert.Equal(768, browser.Size.Height); - Assert.Equal(1, browser.DeviceScaleFactor); - - using (var screenshot = browser.ScreenshotOrNull()) - { - Assert.Equal(1366, screenshot.Width); - Assert.Equal(768, screenshot.Height); - } - } - } - -#if DEBUG - [Fact] - public async Task CanLoadMultipleBrowserInstancesSequentially() - { - for (int i = 0; i < 1000; i++) - { - using (var browser = new ChromiumWebBrowser(new HtmlString("Testing"), useLegacyRenderHandler: false)) - { - var response = await browser.WaitForInitialLoadAsync(); - - Assert.True(response.Success); - - var source = await browser.GetSourceAsync(); - - Assert.Contains("Testing", source); - } - } - } -#endif - } -} diff --git a/CefSharp.Test/OffScreen/OffScreenBrowserTests.cs b/CefSharp.Test/OffScreen/OffScreenBrowserTests.cs new file mode 100644 index 000000000..93df75d5b --- /dev/null +++ b/CefSharp.Test/OffScreen/OffScreenBrowserTests.cs @@ -0,0 +1,317 @@ +// Copyright © 2017 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.Net; +using System.Text; +using System.Threading.Tasks; +using CefSharp.Example; +using CefSharp.OffScreen; +using CefSharp.Web; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.OffScreen +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class OffScreenBrowserTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public OffScreenBrowserTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [Fact] + public async Task ShouldWorkWhenLoadingGoogle() + { + using (var browser = new ChromiumWebBrowser("www.google.com", useLegacyRenderHandler:false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(response.Success); + Assert.True(mainFrame.IsValid); + Assert.Contains("www.google", mainFrame.Url); + Assert.Equal(200, response.HttpStatusCode); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + + [Theory] + [InlineData("http://httpbin.org/post")] + public async Task ShouldWorkWhenLoadingRequestWithPostData(string url) + { + const string data = "Testing123"; + //When Chromium Site Isolation is enabled we must first navigate to + //a web page of the same origin to use LoadRequest + //When Site Isolation is disabled we can navigate to any web page + //https://magpcss.org/ceforum/viewtopic.php?f=10&t=18672&p=50266#p50249 + using (var browser = new ChromiumWebBrowser("http://httpbin.org/", useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var request = new Request + { + Url = "http://httpbin.org/post", + Method = "POST" + }; + var postData = new PostData(); + postData.AddElement(new PostDataElement + { + Bytes = Encoding.UTF8.GetBytes(data) + }); + + request.PostData = postData; + + await browser.LoadRequestAsync(request); + + var mainFrame = browser.GetMainFrame(); + Assert.Equal(url, mainFrame.Url); + + var navEntry = await browser.GetVisibleNavigationEntryAsync(); + + Assert.Equal((int)HttpStatusCode.OK, navEntry.HttpStatusCode); + Assert.True(navEntry.HasPostData); + + var source = await browser.GetTextAsync(); + + Assert.Contains(data, source); + } + } + + [Fact] + public async Task ShouldFailWhenLoadingInvalidDomain() + { + using (var browser = new ChromiumWebBrowser("notfound.cefsharp.test", useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(mainFrame.IsValid); + Assert.Contains("notfound.cefsharp.test", mainFrame.Url); + Assert.Equal(CefErrorCode.NameNotResolved, response.ErrorCode); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + + [Fact] + public async Task ShouldFailWhenLoadingBadSsl() + { + using (var browser = new ChromiumWebBrowser("https://expired.badssl.com/", useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(mainFrame.IsValid); + Assert.Contains("", mainFrame.Url); + Assert.Equal(-1, response.HttpStatusCode); + Assert.Equal(CefErrorCode.CertDateInvalid, response.ErrorCode); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + + [Fact] + public async Task ShouldRespectDisposed() + { + ChromiumWebBrowser browser; + + using (browser = new ChromiumWebBrowser(CefExample.DefaultUrl, useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(response.Success); + Assert.True(mainFrame.IsValid); + Assert.Equal(CefExample.DefaultUrl, mainFrame.Url); + Assert.Equal(200, response.HttpStatusCode); + + output.WriteLine("Url {0}", mainFrame.Url); + } + + Assert.True(browser.IsDisposed, $"Browser IsDisposed:{browser.IsDisposed}"); + + Assert.Throws(() => + { + browser.Copy(); + }); + } + + [Fact] + public async Task ShouldWorkWhenBrowserCreatedAsync() + { + using (var chromiumWebBrowser = new ChromiumWebBrowser("http://www.google.com", automaticallyCreateBrowser: false, useLegacyRenderHandler: false)) + { + var browser = await chromiumWebBrowser.CreateBrowserAsync(); + + Assert.NotNull(browser); + Assert.False(browser.HasDocument); + Assert.NotEqual(0, browser.Identifier); + Assert.False(browser.IsDisposed); + } + } + + [Fact] + public async Task ShouldMakeFrameUrlRequest() + { + using (var browser = new ChromiumWebBrowser("https://code.jquery.com/jquery-3.4.1.min.js", useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(response.Success); + Assert.True(mainFrame.IsValid); + + var taskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var wasCached = false; + var requestClient = new Example.UrlRequestClient((IUrlRequest req, byte[] responseBody) => + { + wasCached = req.ResponseWasCached; + taskCompletionSource.TrySetResult(Encoding.UTF8.GetString(responseBody)); + }); + + //Can be created on any valid CEF Thread, here we'll use the CEF UI Thread + await Cef.UIThreadTaskFactory.StartNew(delegate + { + var request = mainFrame.CreateRequest(false); + + request.Method = "GET"; + request.Url = "https://code.jquery.com/jquery-3.4.1.min.js"; + var urlRequest = mainFrame.CreateUrlRequest(request, requestClient); + }); + + var stringResult = await taskCompletionSource.Task; + + Assert.True(!string.IsNullOrEmpty(stringResult)); + Assert.True(wasCached); + } + } + + [Theory] + [InlineData("https://code.jquery.com/jquery-3.4.1.min.js")] + public async Task ShouldDownloadUrlForFrame(string url) + { + using (var browser = new ChromiumWebBrowser(url, useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var htmlSrc = await browser.GetSourceAsync(); + + Assert.NotNull(htmlSrc); + + var mainFrame = browser.GetMainFrame(); + Assert.True(mainFrame.IsValid); + + var data = await mainFrame.DownloadUrlAsync(url); + + Assert.NotNull(data); + Assert.True(data.Length > 0); + + var stringResult = Encoding.UTF8.GetString(data).Substring(0, 100); + + Assert.Contains(stringResult, htmlSrc); + } + } + + [Theory] + //TODO: Add more urls + [InlineData("http://www.google.com", "http://cefsharp.github.io/")] + public async Task CanExecuteJavascriptInMainFrameAfterNavigatingToDifferentOrigin(string firstUrl, string secondUrl) + { + using (var browser = new ChromiumWebBrowser(firstUrl, useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + Assert.True(browser.CanExecuteJavascriptInMainFrame); + + await browser.LoadUrlAsync(secondUrl); + + Assert.True(browser.CanExecuteJavascriptInMainFrame); + + await browser.LoadUrlAsync(firstUrl); + + Assert.True(browser.CanExecuteJavascriptInMainFrame); + } + } + + [Fact] + public async Task ShouldWaitForBrowserInitialLoadAfterSubsequentLoad() + { + using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(mainFrame.IsValid); + Assert.Contains("www.google.com", mainFrame.Url); + Assert.Equal(CefErrorCode.None, response.ErrorCode); + Assert.Equal(200, response.HttpStatusCode); + + output.WriteLine("Url {0}", mainFrame.Url); + + response = await browser.WaitForInitialLoadAsync(); + + Assert.Equal(CefErrorCode.None, response.ErrorCode); + Assert.Equal(200, response.HttpStatusCode); + } + } + + [Fact] + public async Task ShouldFailWhenCallingTryGetBrowserCoreByIdWithInvalidId() + { + using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var result = browser.TryGetBrowserCoreById(100, out IBrowser browserCore); + + Assert.False(result); + Assert.Null(browserCore); + } + } + + [Fact] + public async Task ShouldWorkWhenCallingTryGetBrowserCoreByIdWithOwnId() + { + using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var result = browser.TryGetBrowserCoreById(browser.BrowserCore.Identifier, out IBrowser browserCore); + + Assert.True(result); + Assert.NotNull(browserCore); + Assert.Equal(browser.BrowserCore.Identifier, browserCore.Identifier); + } + } + + [SkipIfRunOnAppVeyorFact] + public async Task ShouldWorkWhenCreatingOneThousandBrowserSequentially() + { + for (int i = 0; i < 1000; i++) + { + using (var browser = new ChromiumWebBrowser(new HtmlString("Testing"), useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var source = await browser.GetSourceAsync(); + + Assert.Contains("Testing", source); + } + } + } + } +} diff --git a/CefSharp.Test/OffScreen/RequestContextTests.cs b/CefSharp.Test/OffScreen/RequestContextTests.cs new file mode 100644 index 000000000..0d1e6b08d --- /dev/null +++ b/CefSharp.Test/OffScreen/RequestContextTests.cs @@ -0,0 +1,134 @@ +// Copyright © 2022 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.Threading.Tasks; +using CefSharp.OffScreen; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.OffScreen +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class RequestContextTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public RequestContextTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [SkipIfRunOnAppVeyorFact] + public async Task ShouldWorkWithProxy() + { + fixture.StartProxyServerIfRequired(); + + var requestContext = RequestContext + .Configure() + .WithProxyServer("127.0.0.1", 8080) + .Create(); + + using (var browser = new ChromiumWebBrowser("http://cefsharp.github.io/", requestContext: requestContext, useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(response.Success); + Assert.True(mainFrame.IsValid); + Assert.Contains("cefsharp.github.io", mainFrame.Url); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + + [SkipIfRunOnAppVeyorFact] + public async Task ShouldWorkWithSetProxyAsync() + { + fixture.StartProxyServerIfRequired(); + + var tcs = new TaskCompletionSource(); + + var requestContext = RequestContext + .Configure() + .OnInitialize((ctx) => + { + tcs.SetResult(true); + }) + .Create(); + + //Wait for our RequestContext to have initialized. + await tcs.Task; + + var setProxyResponse = await requestContext.SetProxyAsync("127.0.0.1", 8080); + + Assert.True(setProxyResponse.Success); + + using (var browser = new ChromiumWebBrowser("http://cefsharp.github.io/", requestContext: requestContext, useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(response.Success); + Assert.True(mainFrame.IsValid); + Assert.Contains("cefsharp.github.io", mainFrame.Url); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + + [SkipIfRunOnAppVeyorFact] + public async Task ShouldWorkWithProxySetOnUiThread() + { + fixture.StartProxyServerIfRequired(); + + var tcs = new TaskCompletionSource(); + + var requestContext = RequestContext + .Configure() + .OnInitialize((ctx) => + { + tcs.SetResult(true); + }) + .Create(); + + //Wait for our RequestContext to have initialized. + await tcs.Task; + + var success = false; + + //To execute on the CEF UI Thread you can use + await Cef.UIThreadTaskFactory.StartNew(delegate + { + string errorMessage; + + if (!requestContext.CanSetPreference("proxy")) + { + //Unable to set proxy, if you set proxy via command line args it cannot be modified. + success = false; + + return; + } + + success = requestContext.SetProxy("127.0.0.1", 8080, out errorMessage); + }); + + Assert.True(success); + + using (var browser = new ChromiumWebBrowser("http://cefsharp.github.io/", requestContext: requestContext, useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(response.Success); + Assert.True(mainFrame.IsValid); + Assert.Contains("cefsharp.github.io", mainFrame.Url); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + } +} diff --git a/CefSharp.Test/OffScreen/ScreenshotTests.cs b/CefSharp.Test/OffScreen/ScreenshotTests.cs new file mode 100644 index 000000000..5be4bbdeb --- /dev/null +++ b/CefSharp.Test/OffScreen/ScreenshotTests.cs @@ -0,0 +1,131 @@ +// Copyright © 2022 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 Xunit.Abstractions; +using Xunit; +using System.Threading.Tasks; +using CefSharp.DevTools.Page; +using System.IO; +using CefSharp.OffScreen; +using System.Drawing; + +namespace CefSharp.Test.OffScreen +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class ScreenshotTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public ScreenshotTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [Fact] + public async Task ShouldWork() + { + using (var browser = new ChromiumWebBrowser("http://www.google.com", useLegacyRenderHandler: false)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var result1 = await browser.CaptureScreenshotAsync(); + Assert.Equal(1366, browser.Size.Width); + Assert.Equal(768, browser.Size.Height); + Assert.Equal(1, browser.DeviceScaleFactor); + using (var screenshot = Image.FromStream(new MemoryStream(result1))) + { + Assert.Equal(1366, screenshot.Width); + Assert.Equal(768, screenshot.Height); + } + + var result2 = await browser.CaptureScreenshotAsync(viewport: new Viewport { Width = 1366, Height = 768, X = 100, Y = 200, Scale = 2 }); + Assert.Equal(1466, browser.Size.Width); + Assert.Equal(968, browser.Size.Height); + Assert.Equal(2, browser.DeviceScaleFactor); + using (var screenshot = Image.FromStream(new MemoryStream(result2))) + { + Assert.Equal(2732, screenshot.Width); + Assert.Equal(1536, screenshot.Height); + } + + var result3 = await browser.CaptureScreenshotAsync(viewport: new Viewport { Width = 100, Height = 200, Scale = 2 }); + Assert.Equal(1466, browser.Size.Width); + Assert.Equal(968, browser.Size.Height); + Assert.Equal(2, browser.DeviceScaleFactor); + using (var screenshot = Image.FromStream(new MemoryStream(result3))) + { + Assert.Equal(200, screenshot.Width); + Assert.Equal(400, screenshot.Height); + } + + var result4 = await browser.CaptureScreenshotAsync(viewport: new Viewport { Width = 100, Height = 200, Scale = 1 }); + Assert.Equal(1466, browser.Size.Width); + Assert.Equal(968, browser.Size.Height); + Assert.Equal(1, browser.DeviceScaleFactor); + using (var screenshot = Image.FromStream(new MemoryStream(result4))) + { + Assert.Equal(100, screenshot.Width); + Assert.Equal(200, screenshot.Height); + } + } + } + + [Fact] + public async Task ShouldWorkWhenResizingWithDeviceScalingFactor() + { + using (var browser = new ChromiumWebBrowser("http://www.google.com")) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + Assert.Equal(1366, browser.Size.Width); + Assert.Equal(768, browser.Size.Height); + Assert.Equal(1, browser.DeviceScaleFactor); + + + await browser.ResizeAsync(800, 600, 2); + + Assert.Equal(800, browser.Size.Width); + Assert.Equal(600, browser.Size.Height); + Assert.Equal(2, browser.DeviceScaleFactor); + + using (var screenshot = browser.ScreenshotOrNull()) + { + Assert.Equal(1600, screenshot.Width); + Assert.Equal(1200, screenshot.Height); + } + + await browser.ResizeAsync(400, 300); + + Assert.Equal(400, browser.Size.Width); + Assert.Equal(300, browser.Size.Height); + Assert.Equal(2, browser.DeviceScaleFactor); + + using (var screenshot = browser.ScreenshotOrNull()) + { + Assert.Equal(800, screenshot.Width); + Assert.Equal(600, screenshot.Height); + } + + await browser.ResizeAsync(1366, 768, 1); + + Assert.Equal(1366, browser.Size.Width); + Assert.Equal(768, browser.Size.Height); + Assert.Equal(1, browser.DeviceScaleFactor); + + using (var screenshot = browser.ScreenshotOrNull()) + { + Assert.Equal(1366, screenshot.Width); + Assert.Equal(768, screenshot.Height); + } + } + } + } +} diff --git a/CefSharp.Test/PostMessage/IntegrationTestFacts.cs b/CefSharp.Test/PostMessage/IntegrationTestFacts.cs deleted file mode 100644 index 64e4a3472..000000000 --- a/CefSharp.Test/PostMessage/IntegrationTestFacts.cs +++ /dev/null @@ -1,79 +0,0 @@ -// 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.Threading.Tasks; -using CefSharp.OffScreen; -using CefSharp.Web; -using Xunit; -using Xunit.Abstractions; - -namespace CefSharp.Test.PostMessage -{ - /// - /// This is more a set of integration tests than it is unit tests, for now we need to - /// run our QUnit tests in an automated fashion and some other testing. - /// - //TODO: Improve Test Naming, we need a naming scheme that fits these cases that's consistent - //(Ideally we implement consistent naming accross all test classes, though I'm open to a different - //naming convention as these are more integration tests than unit tests). - //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle - [Collection(CefSharpFixtureCollection.Key)] - public class IntegrationTestFacts - { - private readonly ITestOutputHelper output; - private readonly CefSharpFixture fixture; - - public IntegrationTestFacts(ITestOutputHelper output, CefSharpFixture fixture) - { - this.fixture = fixture; - this.output = output; - } - - [Theory] - [InlineData("Event", "Event1")] - [InlineData("Event", "Event2")] - [InlineData("CustomEvent", "Event1")] - [InlineData("CustomEvent", "Event2")] - public async Task JavascriptCustomEvent(string jsEventObject, string eventToRaise) - { - const string Script = @" - const postMessageHandler = e => { cefSharp.postMessage(e.type); }; - window.addEventListener(""Event1"", postMessageHandler, false); - window.addEventListener(""Event2"", postMessageHandler, false);"; - - string rawHtml = $"

testing

"; - int scriptId = 0; - - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - //Load a dummy page initially so we can then add our script using - //Page.AddScriptToEvaluateOnNewDocument (via DevTools) - using (var browser = new ChromiumWebBrowser(new HtmlString("Initial Load"), useLegacyRenderHandler: false)) - { - await browser.WaitForInitialLoadAsync(); - - using (var devToolsClient = browser.GetDevToolsClient()) - { - var result = await devToolsClient.Page.AddScriptToEvaluateOnNewDocumentAsync(Script); - scriptId = int.Parse(result.Identifier); - - //We must use Page.Enable for the script to be added - await devToolsClient.Page.EnableAsync(); - } - - browser.LoadHtml(rawHtml); - - browser.JavascriptMessageReceived += (o, e) => - { - tcs.SetResult((string)e.Message); - }; - - var responseFromJavascript = await tcs.Task; - - Assert.True(scriptId > 0); - Assert.Equal(eventToRaise, responseFromJavascript); - } - } - } -} diff --git a/CefSharp.Test/PostMessage/PostMessageTests.cs b/CefSharp.Test/PostMessage/PostMessageTests.cs new file mode 100644 index 000000000..88a61cd08 --- /dev/null +++ b/CefSharp.Test/PostMessage/PostMessageTests.cs @@ -0,0 +1,79 @@ +// 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.Threading.Tasks; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.PostMessage +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class PostMessageTests : BrowserTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public PostMessageTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [Fact] + public async Task ShouldWork() + { + AssertInitialLoadComplete(); + + var evt = await Assert.RaisesAsync( + a => Browser.JavascriptMessageReceived += a, + a => Browser.JavascriptMessageReceived -= a, + () => Browser.EvaluateScriptAsync("cefSharp.postMessage('test');")); + + Assert.NotNull(evt); + Assert.Equal("test", evt.Arguments.Message); + } + + [Theory] + [InlineData("Event", "Event1")] + [InlineData("Event", "Event2")] + [InlineData("CustomEvent", "Event1")] + [InlineData("CustomEvent", "Event2")] + public async Task ShouldWorkForCustomEvent(string jsEventObject, string expected) + { + const string Script = @" + const postMessageHandler = e => { cefSharp.postMessage(e.type); }; + window.addEventListener(""Event1"", postMessageHandler, false); + window.addEventListener(""Event2"", postMessageHandler, false);"; + + string rawHtml = $"

testing

"; + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + //Make sure to load an initial page so we can then add our script using + //Page.AddScriptToEvaluateOnNewDocument (via DevTools) + + using (var devToolsClient = Browser.GetDevToolsClient()) + { + var result = await devToolsClient.Page.AddScriptToEvaluateOnNewDocumentAsync(Script); + var scriptId = int.Parse(result.Identifier); + + //We must use Page.Enable for the script to be added + await devToolsClient.Page.EnableAsync(); + + Browser.LoadHtml(rawHtml); + + Browser.JavascriptMessageReceived += (o, e) => + { + tcs.SetResult((string)e.Message); + }; + + var actual = await tcs.Task; + + Assert.True(scriptId > 0); + Assert.Equal(expected, actual); + } + } + } +} diff --git a/CefSharp.Test/RequestContextIsolatedBrowserTests.cs b/CefSharp.Test/RequestContextIsolatedBrowserTests.cs new file mode 100644 index 000000000..5ac6dfced --- /dev/null +++ b/CefSharp.Test/RequestContextIsolatedBrowserTests.cs @@ -0,0 +1,23 @@ +// Copyright © 2023 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.Threading.Tasks; +using CefSharp.Example; +using CefSharp.OffScreen; +using Xunit; + +namespace CefSharp.Test +{ + /// + /// Each browser instance will be created with it's own + /// using an InMemory cache + /// + public abstract class RequestContextIsolatedBrowserTests : BrowserTests + { + protected RequestContextIsolatedBrowserTests() + { + RequestContextIsolated = true; + } + } +} diff --git a/CefSharp.Test/SchemeHandler/FolderSchemeHandlerFactoryTests.cs b/CefSharp.Test/SchemeHandler/FolderSchemeHandlerFactoryTests.cs index 6568c945f..a75af1fee 100644 --- a/CefSharp.Test/SchemeHandler/FolderSchemeHandlerFactoryTests.cs +++ b/CefSharp.Test/SchemeHandler/FolderSchemeHandlerFactoryTests.cs @@ -28,7 +28,7 @@ namespace CefSharp.Test.SchemeHandler } [Fact] - public async Task CanWork() + public async Task ShouldWork() { const string expected = "https://folderschemehandlerfactory.test/"; @@ -57,7 +57,7 @@ namespace CefSharp.Test.SchemeHandler } [Fact] - public async Task CanDeleteFileAfterLoading() + public async Task ShouldAllowFileDeletionAfterLoading() { const string expected = "https://folderschemehandlerfactory.test/"; const string html = "I'm going to be deleted after use!"; diff --git a/CefSharp.Test/Selector/WaitForSelectorAsyncTests.cs b/CefSharp.Test/Selector/WaitForSelectorAsyncTests.cs index 0459ed2ba..42b4dcd6d 100644 --- a/CefSharp.Test/Selector/WaitForSelectorAsyncTests.cs +++ b/CefSharp.Test/Selector/WaitForSelectorAsyncTests.cs @@ -1,3 +1,7 @@ +// Copyright © 2022 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 Xunit.Abstractions; using Xunit; using System.Threading.Tasks; diff --git a/CefSharp.Test/UrlRequest/UrlRequestTests.cs b/CefSharp.Test/UrlRequest/UrlRequestTests.cs new file mode 100644 index 000000000..03ac74f46 --- /dev/null +++ b/CefSharp.Test/UrlRequest/UrlRequestTests.cs @@ -0,0 +1,57 @@ +// Copyright © 2022 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.Text; +using System.Threading.Tasks; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.UrlRequest +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class UrlRequestTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public UrlRequestTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [Fact] + public async Task ShouldWork() + { + var taskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + IUrlRequest urlRequest = null; + int statusCode = -1; + + //Can be created on any valid CEF Thread, here we'll use the CEF UI Thread + await Cef.UIThreadTaskFactory.StartNew(delegate + { + var requestClient = new Example.UrlRequestClient((IUrlRequest req, byte[] responseBody) => + { + statusCode = req.Response.StatusCode; + taskCompletionSource.TrySetResult(Encoding.UTF8.GetString(responseBody)); + }); + + var request = new Request + { + Method = "GET", + Url = "https://code.jquery.com/jquery-3.4.1.min.js" + }; + + //Global RequestContext will be used + urlRequest = new CefSharp.UrlRequest(request, requestClient); + }); + + var stringResult = await taskCompletionSource.Task; + + Assert.True(!string.IsNullOrEmpty(stringResult)); + Assert.Equal(200, statusCode); + } + } +} diff --git a/CefSharp.Test/WebBrowserTestExtensions.cs b/CefSharp.Test/WebBrowserTestExtensions.cs index 227eb3f7c..e4b4397f0 100644 --- a/CefSharp.Test/WebBrowserTestExtensions.cs +++ b/CefSharp.Test/WebBrowserTestExtensions.cs @@ -6,11 +6,21 @@ using System; using System.Reflection; using System.Threading.Tasks; using CefSharp.OffScreen; +using Xunit; namespace CefSharp.Test { public static class WebBrowserTestExtensions { + public static async Task EvaluateScriptAndAssertAsync(this IChromiumWebBrowserBase browser, string script) + { + var response = await browser.EvaluateScriptAsync(script).ConfigureAwait(false); + + Assert.True(response.Success, response.Message); + + return (T)response.Result; + } + public static int PaintEventHandlerCount(this CefSharp.Wpf.ChromiumWebBrowser browser) { var field = typeof(CefSharp.Wpf.ChromiumWebBrowser).GetField("Paint", BindingFlags.NonPublic | BindingFlags.Instance); diff --git a/CefSharp.Test/WinForms/RequestContextTests.cs b/CefSharp.Test/WinForms/RequestContextTests.cs new file mode 100644 index 000000000..6cae221ac --- /dev/null +++ b/CefSharp.Test/WinForms/RequestContextTests.cs @@ -0,0 +1,69 @@ +// Copyright © 2017 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.Threading.Tasks; +using CefSharp.Example; +using CefSharp.WinForms; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.WinForms +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class RequestContextTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public RequestContextTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [WinFormsFact] + public async Task ShouldWork() + { + using (var browser = new ChromiumWebBrowser("www.google.com")) + { + browser.RequestContext = new RequestContext(); + + browser.Size = new System.Drawing.Size(1024, 768); + browser.CreateControl(); + + await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(mainFrame.IsValid); + Assert.Contains("www.google", mainFrame.Url); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + + [WinFormsFact] + public async Task ShouldWorkUsingBuilder() + { + using (var browser = new ChromiumWebBrowser("www.google.com")) + { + browser.RequestContext = RequestContext.Configure() + .WithSharedSettings(Cef.GetGlobalRequestContext()) + .Create(); + + browser.Size = new System.Drawing.Size(1024, 768); + browser.CreateControl(); + + await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(mainFrame.IsValid); + Assert.Contains("www.google", mainFrame.Url); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + } +} diff --git a/CefSharp.Test/WinForms/WinFormsBrowserBasicFacts.cs b/CefSharp.Test/WinForms/WinFormsBrowserTests.cs similarity index 66% rename from CefSharp.Test/WinForms/WinFormsBrowserBasicFacts.cs rename to CefSharp.Test/WinForms/WinFormsBrowserTests.cs index f41f03495..08bd376fd 100644 --- a/CefSharp.Test/WinForms/WinFormsBrowserBasicFacts.cs +++ b/CefSharp.Test/WinForms/WinFormsBrowserTests.cs @@ -13,19 +13,19 @@ namespace CefSharp.Test.WinForms { //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle [Collection(CefSharpFixtureCollection.Key)] - public class WinFormsBrowserBasicFacts + public class WinFormsBrowserTests { private readonly ITestOutputHelper output; private readonly CefSharpFixture fixture; - public WinFormsBrowserBasicFacts(ITestOutputHelper output, CefSharpFixture fixture) + public WinFormsBrowserTests(ITestOutputHelper output, CefSharpFixture fixture) { this.fixture = fixture; this.output = output; } [WinFormsFact] - public async Task CanLoadGoogle() + public async Task ShouldWorkWhenLoadingGoogle() { using (var browser = new ChromiumWebBrowser("www.google.com")) { @@ -33,8 +33,8 @@ namespace CefSharp.Test.WinForms browser.CreateControl(); await browser.WaitForInitialLoadAsync(); - var mainFrame = browser.GetMainFrame(); + Assert.True(mainFrame.IsValid); Assert.Contains("www.google", mainFrame.Url); @@ -43,20 +43,19 @@ namespace CefSharp.Test.WinForms } [WinFormsFact] - public async Task CanSetBrowserSettingsDisableImageLoadingViaObjectFactory() + public async Task ShouldDisableImageLoadingViaObjectFactory() { using (var browser = new ChromiumWebBrowser("www.google.com")) { var settings = Core.ObjectFactory.CreateBrowserSettings(true); settings.ImageLoading = CefState.Disabled; browser.BrowserSettings = settings; - browser.Size = new System.Drawing.Size(1024, 768); browser.CreateControl(); await browser.WaitForInitialLoadAsync(); - var mainFrame = browser.GetMainFrame(); + Assert.True(mainFrame.IsValid); Assert.Contains("www.google", mainFrame.Url); @@ -65,7 +64,7 @@ namespace CefSharp.Test.WinForms } [WinFormsFact] - public async Task CanSetBrowserSettingsDisableImageLoading() + public async Task ShouldDisableImageLoading() { using (var browser = new ChromiumWebBrowser("www.google.com")) { @@ -73,55 +72,12 @@ namespace CefSharp.Test.WinForms { ImageLoading = CefState.Disabled }; - browser.Size = new System.Drawing.Size(1024, 768); browser.CreateControl(); await browser.WaitForInitialLoadAsync(); - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("www.google", mainFrame.Url); - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [WinFormsFact] - public async Task CanSetRequestContextViaRequestContextBuilder() - { - using (var browser = new ChromiumWebBrowser("www.google.com")) - { - browser.RequestContext = RequestContext.Configure() - .WithSharedSettings(Cef.GetGlobalRequestContext()) - .Create(); - - browser.Size = new System.Drawing.Size(1024, 768); - browser.CreateControl(); - - await browser.WaitForInitialLoadAsync(); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("www.google", mainFrame.Url); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [WinFormsFact] - public async Task CanSetRequestContext() - { - using (var browser = new ChromiumWebBrowser("www.google.com")) - { - browser.RequestContext = new RequestContext(); - - browser.Size = new System.Drawing.Size(1024, 768); - browser.CreateControl(); - - await browser.WaitForInitialLoadAsync(); - - var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); Assert.Contains("www.google", mainFrame.Url); @@ -140,8 +96,8 @@ namespace CefSharp.Test.WinForms browser.CreateControl(); await browser.WaitForInitialLoadAsync(); - var mainFrame = browser.GetMainFrame(); + Assert.True(mainFrame.IsValid); Assert.Equal(CefExample.DefaultUrl, mainFrame.Url); diff --git a/CefSharp.Test/Wpf/RequestContextTests.cs b/CefSharp.Test/Wpf/RequestContextTests.cs new file mode 100644 index 000000000..740c526a7 --- /dev/null +++ b/CefSharp.Test/Wpf/RequestContextTests.cs @@ -0,0 +1,66 @@ +// Copyright © 2017 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.Threading.Tasks; +using System.Windows; +using CefSharp.Wpf; +using Xunit; +using Xunit.Abstractions; + +namespace CefSharp.Test.Wpf +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + [BrowserRefCountDebugging(typeof(ChromiumWebBrowser))] + public class RequestContextTests + { + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public RequestContextTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [WpfFact] + public async Task ShouldWork() + { + using (var browser = new ChromiumWebBrowser("www.google.com")) + { + browser.RequestContext = new RequestContext(); + browser.CreateBrowser(null, new Size(1024, 786)); + + await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(mainFrame.IsValid); + Assert.Contains("www.google", mainFrame.Url); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + + [WpfFact] + public async Task ShouldWorkUsingBuilder() + { + using (var browser = new ChromiumWebBrowser("www.google.com")) + { + browser.RequestContext = RequestContext.Configure() + .WithSharedSettings(Cef.GetGlobalRequestContext()) + .Create(); + + browser.CreateBrowser(null, new Size(1024, 786)); + + await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); + + Assert.True(mainFrame.IsValid); + Assert.Contains("www.google", mainFrame.Url); + + output.WriteLine("Url {0}", mainFrame.Url); + } + } + } +} diff --git a/CefSharp.Test/Wpf/WpfBrowserBasicFacts.cs b/CefSharp.Test/Wpf/WpfBrowserTests.cs similarity index 62% rename from CefSharp.Test/Wpf/WpfBrowserBasicFacts.cs rename to CefSharp.Test/Wpf/WpfBrowserTests.cs index 354ccb844..1fd1a1765 100644 --- a/CefSharp.Test/Wpf/WpfBrowserBasicFacts.cs +++ b/CefSharp.Test/Wpf/WpfBrowserTests.cs @@ -15,25 +15,25 @@ namespace CefSharp.Test.Wpf //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle [Collection(CefSharpFixtureCollection.Key)] [BrowserRefCountDebugging(typeof(ChromiumWebBrowser))] - public class WpfBrowserBasicFacts + public class WpfBrowserTests { private readonly ITestOutputHelper output; private readonly CefSharpFixture fixture; - public WpfBrowserBasicFacts(ITestOutputHelper output, CefSharpFixture fixture) + public WpfBrowserTests(ITestOutputHelper output, CefSharpFixture fixture) { this.fixture = fixture; this.output = output; } [WpfFact] - public async Task CanLoadGoogle() + public async Task ShouldWorkWhenLoadingGoogle() { using (var browser = new ChromiumWebBrowser(null, "www.google.com", new Size(1024, 786))) { await browser.WaitForInitialLoadAsync(); - var mainFrame = browser.GetMainFrame(); + Assert.True(mainFrame.IsValid); Assert.Contains("www.google", mainFrame.Url); @@ -42,15 +42,14 @@ namespace CefSharp.Test.Wpf } [WpfFact] - public async Task CanCallLoadUrlAsyncImmediately() + public async Task ShouldWorkWhenLoadUrlAsyncImmediately() { using (var browser = new ChromiumWebBrowser(null, string.Empty, new Size(1024, 786))) { var response = await browser.LoadUrlAsync("www.google.com"); + var mainFrame = browser.GetMainFrame(); Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); Assert.Contains("www.google", mainFrame.Url); @@ -59,57 +58,17 @@ namespace CefSharp.Test.Wpf } [WpfFact] - public async Task CanCallLoadUrlImmediately() + public async Task ShouldWorkWhenLoadUrlImmediately() { using (var browser = new ChromiumWebBrowser()) { - browser.Load("www.google.com"); + browser.LoadUrl("www.google.com"); browser.CreateBrowser(null, new Size(1024, 786)); var response = await browser.WaitForInitialLoadAsync(); + var mainFrame = browser.GetMainFrame(); Assert.True(response.Success); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("www.google", mainFrame.Url); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [WpfFact] - public async Task CanSetRequestContext() - { - using (var browser = new ChromiumWebBrowser("www.google.com")) - { - browser.RequestContext = new RequestContext(); - browser.CreateBrowser(null, new Size(1024, 786)); - - await browser.WaitForInitialLoadAsync(); - - var mainFrame = browser.GetMainFrame(); - Assert.True(mainFrame.IsValid); - Assert.Contains("www.google", mainFrame.Url); - - output.WriteLine("Url {0}", mainFrame.Url); - } - } - - [WpfFact] - public async Task CanSetRequestContextViaBuilder() - { - using (var browser = new ChromiumWebBrowser("www.google.com")) - { - browser.RequestContext = RequestContext.Configure() - .WithSharedSettings(Cef.GetGlobalRequestContext()) - .Create(); - - browser.CreateBrowser(null, new Size(1024, 786)); - - await browser.WaitForInitialLoadAsync(); - - var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); Assert.Contains("www.google", mainFrame.Url);