Skip to content

Commit 1808ccc

Browse files
authored
Launcher tests (#1796)
1 parent e3fb28f commit 1808ccc

File tree

10 files changed

+152
-15
lines changed

10 files changed

+152
-15
lines changed
211 Bytes
Binary file not shown.

lib/PuppeteerSharp.Tests/LauncherTests/BrowserFetcherTests.cs

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
using System.Collections.Generic;
1010
using PuppeteerSharp.Xunit;
1111

12-
namespace PuppeteerSharp.Tests.PuppeteerTests
12+
namespace PuppeteerSharp.Tests.LauncherTests
1313
{
1414
[Collection(TestConstants.TestFixtureCollectionName)]
1515
public class BrowserFetcherTests : PuppeteerBaseTest
@@ -72,6 +72,60 @@ public async Task ShouldDownloadAndExtractLinuxBinary()
7272
}
7373
}
7474

75+
[PuppeteerTest("launcher.spec.ts", "BrowserFetcher", "should download and extract firefox linux binary")]
76+
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
77+
public async Task ShouldDownloadAndExtractFirefoxLinuxBinary()
78+
{
79+
var browserFetcher = Puppeteer.CreateBrowserFetcher(new BrowserFetcherOptions
80+
{
81+
Platform = Platform.Linux,
82+
Path = _downloadsFolder,
83+
Host = TestConstants.ServerUrl,
84+
Product = Product.Firefox
85+
});
86+
var expectedVersion = "75.0a1";
87+
var revisionInfo = browserFetcher.RevisionInfo(expectedVersion);
88+
89+
Server.SetRedirect(
90+
revisionInfo.Url.Substring(TestConstants.ServerUrl.Length),
91+
"/firefox.zip");
92+
Assert.False(revisionInfo.Local);
93+
Assert.Equal(Platform.Linux, revisionInfo.Platform);
94+
Assert.False(await browserFetcher.CanDownloadAsync("100000"));
95+
Assert.True(await browserFetcher.CanDownloadAsync(expectedVersion));
96+
97+
try
98+
{
99+
revisionInfo = await browserFetcher.DownloadAsync(expectedVersion);
100+
Assert.True(revisionInfo.Local);
101+
Assert.Equal("FIREFOX LINUX BINARY\n", File.ReadAllText(revisionInfo.ExecutablePath));
102+
103+
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
104+
{
105+
#if NETCOREAPP //This will not be run on net4x anyway.
106+
Mono.Unix.FileAccessPermissions permissions = ConvertPermissions(LinuxSysCall.ExecutableFilePermissions);
107+
108+
Assert.Equal(permissions, UnixFileSystemInfo.GetFileSystemEntry(revisionInfo.ExecutablePath).FileAccessPermissions & permissions);
109+
#endif
110+
}
111+
Assert.Equal(new[] { expectedVersion }, browserFetcher.LocalRevisions());
112+
browserFetcher.Remove(expectedVersion);
113+
Assert.Empty(browserFetcher.LocalRevisions());
114+
115+
//Download should return data from a downloaded version
116+
//This section is not in the Puppeteer test.
117+
await browserFetcher.DownloadAsync(expectedVersion);
118+
Server.Reset();
119+
revisionInfo = await browserFetcher.DownloadAsync(expectedVersion);
120+
Assert.True(revisionInfo.Local);
121+
Assert.Equal("FIREFOX LINUX BINARY\n", File.ReadAllText(revisionInfo.ExecutablePath));
122+
}
123+
finally
124+
{
125+
EnsureDownloadsFolderIsDeleted();
126+
}
127+
}
128+
75129
#if NETCOREAPP
76130
private Mono.Unix.FileAccessPermissions ConvertPermissions(Helpers.Linux.FileAccessPermissions executableFilePermissions)
77131
{

lib/PuppeteerSharp.Tests/LauncherTests/PuppeteerConnectTests.cs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,39 @@ await Task.WhenAll(
8787
}
8888
}
8989

90+
[PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should support targetFilter option")]
91+
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
92+
public async Task ShouldSupportTargetFilter()
93+
{
94+
await using (var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))
95+
{
96+
var page1 = await originalBrowser.NewPageAsync();
97+
await page1.GoToAsync(TestConstants.EmptyPage);
98+
99+
var page2 = await originalBrowser.NewPageAsync();
100+
await page2.GoToAsync(TestConstants.EmptyPage + "?should-be-ignored");
101+
102+
var browser = await Puppeteer.ConnectAsync(new ConnectOptions {
103+
BrowserWSEndpoint = originalBrowser.WebSocketEndpoint,
104+
TargetFilter = (TargetInfo targetInfo) => !targetInfo.Url.Contains("should-be-ignored"),
105+
});
106+
107+
var pages = await browser.PagesAsync();
108+
109+
await page2.CloseAsync();
110+
await page1.CloseAsync();
111+
await browser.CloseAsync();
112+
113+
Assert.Equal(
114+
new string[]
115+
{
116+
"about:blank",
117+
TestConstants.EmptyPage
118+
},
119+
pages.Select((Page p) => p.Url).OrderBy(t => t));
120+
}
121+
}
122+
90123
[PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to reconnect to a disconnected browser")]
91124
[SkipBrowserFact(skipFirefox: true)]
92125
public async Task ShouldBeAbleToReconnectToADisconnectedBrowser()
@@ -140,6 +173,30 @@ async void TargetCreated(object sender, TargetChangedArgs e)
140173
Assert.Equal(42, await page2.EvaluateExpressionAsync<int>("7 * 6"));
141174
await browserOne.CloseAsync();
142175
}
176+
177+
[PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to reconnect")]
178+
[SkipBrowserFact(skipFirefox: true)]
179+
public async Task ShouldBeAbleToReconnect()
180+
{
181+
var browserOne = await Puppeteer.LaunchAsync(new LaunchOptions());
182+
var browserWSEndpoint = browserOne.WebSocketEndpoint;
183+
var page1 = await browserOne.NewPageAsync();
184+
await page1.GoToAsync(TestConstants.EmptyPage);
185+
browserOne.Disconnect();
186+
187+
var browserTwo = await Puppeteer.ConnectAsync(new ConnectOptions
188+
{
189+
BrowserWSEndpoint = browserWSEndpoint
190+
});
191+
192+
var pages = await browserTwo.PagesAsync();
193+
var pageTwo = pages.First(page => page.Url == TestConstants.EmptyPage);
194+
await pageTwo.ReloadAsync();
195+
var bodyHandle = await pageTwo.WaitForSelectorAsync("body", new WaitForSelectorOptions { Timeout = 10000 });
196+
await bodyHandle.DisposeAsync();
197+
await browserTwo.CloseAsync();
198+
}
199+
143200
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
144201
public async Task ShouldSupportCustomWebSocket()
145202
{

lib/PuppeteerSharp.Tests/WontImplementTests.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ public WontImplementTests(ITestOutputHelper output) : base(output)
2121
[PuppeteerTest("navigation.spec.ts", "should not leak listeners during bad navigation")]
2222
[PuppeteerTest("navigation.spec.ts", "should not leak listeners during navigation of 11 pages")]
2323
[PuppeteerTest("navigation.spec.ts", "should throw if networkidle is passed as an option")]
24+
[PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "should report the correct product")] //We don't use the product in this way
25+
[PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "falls back to launching chrome if there is an unknown product but logs a warning")]
2426
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
2527
public void TheseTesstWontBeImplemented()
2628
{

lib/PuppeteerSharp/Browser.cs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -42,20 +42,13 @@ public class Browser : IDisposable, IAsyncDisposable
4242
/// </summary>
4343
private const int CloseTimeout = 5000;
4444

45-
/// <summary>
46-
/// Initializes a new instance of the <see cref="Browser"/> class.
47-
/// </summary>
48-
/// <param name="connection">The connection</param>
49-
/// <param name="contextIds">The context ids></param>
50-
/// <param name="ignoreHTTPSErrors">The option to ignoreHTTPSErrors</param>
51-
/// <param name="defaultViewport">Default viewport</param>
52-
/// <param name="launcher">The launcher</param>
53-
public Browser(
45+
internal Browser(
5446
Connection connection,
5547
string[] contextIds,
5648
bool ignoreHTTPSErrors,
5749
ViewPortOptions defaultViewport,
58-
LauncherBase launcher)
50+
LauncherBase launcher,
51+
Func<TargetInfo, bool> targetFilter)
5952
{
6053
Connection = connection;
6154
IgnoreHTTPSErrors = ignoreHTTPSErrors;
@@ -72,6 +65,7 @@ public Browser(
7265

7366
Launcher = launcher;
7467
_logger = Connection.LoggerFactory.CreateLogger<Browser>();
68+
_targetFilterCallback = targetFilter ?? ((TargetInfo _) => true);
7569
}
7670

7771
#region Private members
@@ -80,6 +74,7 @@ public Browser(
8074

8175
private readonly Dictionary<string, BrowserContext> _contexts;
8276
private readonly ILogger<Browser> _logger;
77+
private readonly Func<TargetInfo, bool> _targetFilterCallback;
8378
private Task _closeTask;
8479

8580
#endregion
@@ -489,6 +484,12 @@ private async Task CreateTargetAsync(TargetCreatedResponse e)
489484
var targetInfo = e.TargetInfo;
490485
var browserContextId = targetInfo.BrowserContextId;
491486

487+
var shouldAttachToTarget = _targetFilterCallback(targetInfo);
488+
if (!shouldAttachToTarget)
489+
{
490+
return;
491+
}
492+
492493
if (!(browserContextId != null && _contexts.TryGetValue(browserContextId, out var context)))
493494
{
494495
context = DefaultContext;
@@ -519,9 +520,10 @@ internal static async Task<Browser> CreateAsync(
519520
string[] contextIds,
520521
bool ignoreHTTPSErrors,
521522
ViewPortOptions defaultViewPort,
522-
LauncherBase launcher)
523+
LauncherBase launcher,
524+
Func<TargetInfo, bool> targetFilter)
523525
{
524-
var browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewPort, launcher);
526+
var browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewPort, launcher, targetFilter);
525527
await connection.SendAsync("Target.setDiscoverTargets", new TargetSetDiscoverTargetsRequest
526528
{
527529
Discover = true

lib/PuppeteerSharp/BrowserFetcher.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,7 @@ private static void ExtractTar(string zipPath, string folderPath)
432432
process.StartInfo.FileName = "tar";
433433
process.StartInfo.Arguments = $"-xvjf \"{zipPath}\" -C \"{folderPath}\"";
434434
process.StartInfo.RedirectStandardOutput = true;
435+
process.StartInfo.UseShellExecute = false;
435436
process.Start();
436437
process.WaitForExit();
437438
}

lib/PuppeteerSharp/ConnectOptions.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,5 +85,10 @@ public class ConnectOptions : IBrowserOptions, IConnectionOptions
8585
/// can set this to <c>false</c> (default).
8686
/// </remarks>
8787
public bool EnqueueAsyncMessages { get; set; }
88+
89+
/// <summary>
90+
/// Callback to decide if Puppeteer should connect to a given target or not.
91+
/// </summary>
92+
public Func<TargetInfo, bool> TargetFilter { get; set; }
8893
}
8994
}

lib/PuppeteerSharp/IConnectionOptions.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,5 +46,10 @@ public interface IConnectionOptions
4646
/// Affects how responses to <see cref="CDPSession.SendAsync"/> are returned to the caller.
4747
/// </summary>
4848
bool EnqueueAsyncMessages { get; set; }
49+
50+
/// <summary>
51+
/// Callback to decide if Puppeteer should connect to a given target or not.
52+
/// </summary>
53+
public Func<TargetInfo, bool> TargetFilter { get; set; }
4954
}
5055
}

lib/PuppeteerSharp/LaunchOptions.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,5 +176,10 @@ public string[] IgnoredDefaultArgs
176176
/// can set this to <c>false</c> (default).
177177
/// </remarks>
178178
public bool EnqueueAsyncMessages { get; set; }
179+
180+
/// <summary>
181+
/// Callback to decide if Puppeteer should connect to a given target or not.
182+
/// </summary>
183+
public Func<TargetInfo, bool> TargetFilter { get; set; }
179184
}
180185
}

lib/PuppeteerSharp/Launcher.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public async Task<Browser> LaunchAsync(LaunchOptions options)
6969
.ConfigureAwait(false);
7070

7171
var browser = await Browser
72-
.CreateAsync(connection, Array.Empty<string>(), options.IgnoreHTTPSErrors, options.DefaultViewport, Process)
72+
.CreateAsync(connection, Array.Empty<string>(), options.IgnoreHTTPSErrors, options.DefaultViewport, Process, options.TargetFilter)
7373
.ConfigureAwait(false);
7474

7575
await browser.WaitForTargetAsync(t => t.Type == TargetType.Page).ConfigureAwait(false);
@@ -110,7 +110,13 @@ public async Task<Browser> ConnectAsync(ConnectOptions options)
110110
var connection = await Connection.Create(browserWSEndpoint, options, _loggerFactory).ConfigureAwait(false);
111111
var response = await connection.SendAsync<GetBrowserContextsResponse>("Target.getBrowserContexts").ConfigureAwait(false);
112112
return await Browser
113-
.CreateAsync(connection, response.BrowserContextIds, options.IgnoreHTTPSErrors, options.DefaultViewport, null)
113+
.CreateAsync(
114+
connection,
115+
response.BrowserContextIds,
116+
options.IgnoreHTTPSErrors,
117+
options.DefaultViewport,
118+
null,
119+
options.TargetFilter)
114120
.ConfigureAwait(false);
115121
}
116122
catch (Exception ex)

0 commit comments

Comments
 (0)