Skip to content

Commit 5018c83

Browse files
authored
Use handle instead of globals (#2184)
* some progress * tiny refactors * Refactor SetContext * Injected: Use handle instead of globals * fix add script code * Rename puppeteer util * Fix query objects tests * Remove extra GetDocument function * Remove unused class * remove unused usings * Fix another test * code factor
1 parent 2cee48d commit 5018c83

File tree

16 files changed

+245
-512
lines changed

16 files changed

+245
-512
lines changed

lib/PuppeteerSharp.TestServer/PuppeteerSharp.TestServer.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
1515
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
1616
</ItemGroup>
17-
<Target Name="testCertCheck" BeforeTargets="BeforeBuild" Condition="!Exists('testCert.cer')" >
17+
<Target Name="testCertCheck" BeforeTargets="BeforeBuild" Condition="!Exists('testCert.cer')">
1818
<Error Text="Follow https://github.com/hardkoded/puppeteer-sharp/blob/master/CONTRIBUTING.md#getting-setup to setup a development certificate." />
1919
</Target>
2020
</Project>

lib/PuppeteerSharp.Tests/ClickTests/ClickTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ await Task.WhenAll(
7777
newPage.Mouse.ClickAsync(1, 2));
7878
}
7979

80-
[PuppeteerTest("click.spec.ts", "Page.click", "should click the button after navigation ")]
80+
[PuppeteerTest("click.spec.ts", "Page.click", "should click the button after navigation")]
8181
[PuppeteerFact]
8282
public async Task ShouldClickTheButtonAfterNavigation()
8383
{

lib/PuppeteerSharp.Tests/EvaluationTests/PageEvaluateTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ public async Task ShouldThrowIfUnderlyingElementWasDisposed()
279279
var element = await Page.QuerySelectorAsync("section");
280280
Assert.NotNull(element);
281281
await element.DisposeAsync();
282-
var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
282+
var exception = await Assert.ThrowsAnyAsync<PuppeteerException>(()
283283
=> Page.EvaluateFunctionAsync<string>("e => e.textContent", element));
284284
Assert.Contains("JSHandle is disposed", exception.Message);
285285
}
@@ -290,7 +290,7 @@ public async Task ShouldThrowIfElementHandlesAreFromOtherFrames()
290290
{
291291
await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);
292292
var bodyHandle = await Page.FirstChildFrame().QuerySelectorAsync("body");
293-
var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
293+
var exception = await Assert.ThrowsAnyAsync<PuppeteerException>(()
294294
=> Page.EvaluateFunctionAsync<string>("body => body.innerHTML", bodyHandle));
295295
Assert.Contains("JSHandles can be evaluated only in the context they were created", exception.Message);
296296
}

lib/PuppeteerSharp.Tests/InjectedTests/InjectedTests.cs

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Reflection.Metadata;
22
using System.Threading.Tasks;
3+
using Newtonsoft.Json.Linq;
34
using PuppeteerSharp.Tests.Attributes;
45
using PuppeteerSharp.Xunit;
56
using Xunit;
@@ -14,15 +15,31 @@ public InjectedTests(ITestOutputHelper output) : base(output)
1415
{
1516
}
1617

17-
[PuppeteerTest("injected.spec.ts", "InjectedUtil tests", "should work")]
18+
[PuppeteerTest("injected.spec.ts", "PuppeteerUtil tests", "should work")]
1819
[PuppeteerFact]
1920
public async Task ShouldWork()
2021
{
21-
var result = await (Page.MainFrame as Frame)
22-
.SecondaryWorld.EvaluateFunctionAsync<bool>(@"() => {
23-
return typeof InjectedUtil === 'object';
24-
}");
22+
var world = (Page.MainFrame as Frame).PuppeteerWorld;
23+
var result = await world.EvaluateFunctionAsync<bool>(@"
24+
PuppeteerUtil => {
25+
return typeof PuppeteerUtil === 'object';
26+
}",
27+
await world.GetPuppeteerUtilAsync());
2528
Assert.True(result);
2629
}
30+
31+
[PuppeteerTest("injected.spec.ts", "createFunction tests", "should work")]
32+
[PuppeteerFact]
33+
public async Task CreateFunctionShouldWork()
34+
{
35+
var world = (Page.MainFrame as Frame).PuppeteerWorld;
36+
var result = await (Page.MainFrame as Frame)
37+
.PuppeteerWorld.EvaluateFunctionAsync<int>(@"({createFunction}, fnString) => {
38+
return createFunction(fnString)(4);
39+
}",
40+
await world.GetPuppeteerUtilAsync(),
41+
"() => 4");
42+
Assert.Equal(4, result);
43+
}
2744
}
2845
}

lib/PuppeteerSharp.Tests/PageTests/AddStyleTagTests.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,9 @@ public async Task ShouldWorkWithAUrl()
4040
public async Task ShouldThrowAnErrorIfLoadingFromUrlFail()
4141
{
4242
await Page.GoToAsync(TestConstants.EmptyPage);
43-
var exception = await Assert.ThrowsAsync<PuppeteerException>(()
43+
var exception = await Assert.ThrowsAnyAsync<PuppeteerException>(()
4444
=> Page.AddStyleTagAsync(new AddTagOptions { Url = "/nonexistfile.js" }));
45-
Assert.Equal("Loading style from /nonexistfile.js failed", exception.Message);
45+
Assert.Contains("Could not load style", exception.Message);
4646
}
4747

4848
[PuppeteerTest("page.spec.ts", "Page.addStyleTag", "should work with a path")]
@@ -99,7 +99,7 @@ public async Task ShouldThrowWhenAddedWithContentToTheCSPPage()
9999
public async Task ShouldThrowWhenAddedWithURLToTheCSPPage()
100100
{
101101
await Page.GoToAsync(TestConstants.ServerUrl + "/csp.html");
102-
var exception = await Assert.ThrowsAsync<PuppeteerException>(
102+
var exception = await Assert.ThrowsAnyAsync<PuppeteerException>(
103103
() => Page.AddStyleTagAsync(new AddTagOptions
104104
{
105105
Url = TestConstants.CrossProcessUrl + "/injectedstyle.css"

lib/PuppeteerSharp.Tests/PageTests/QueryObjectsTests.cs

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,32 @@ public QueryObjectsTests(ITestOutputHelper output) : base(output)
1717
[SkipBrowserFact(skipFirefox: true)]
1818
public async Task ShouldWork()
1919
{
20-
// Instantiate an object
21-
await Page.EvaluateExpressionAsync("window.set = new Set(['hello', 'world'])");
22-
var prototypeHandle = await Page.EvaluateExpressionHandleAsync("Set.prototype");
23-
var objectsHandle = await Page.QueryObjectsAsync(prototypeHandle);
24-
var count = await Page.EvaluateFunctionAsync<int>("objects => objects.length", objectsHandle);
25-
Assert.Equal(1, count);
26-
var values = await Page.EvaluateFunctionAsync<string[]>("objects => Array.from(objects[0].values())", objectsHandle);
27-
Assert.Equal(new[] { "hello", "world" }, values);
28-
}
20+
// Create a custom class
21+
var classHandle = await Page.EvaluateFunctionHandleAsync(@"() => {
22+
return class CustomClass { };
23+
}");
24+
25+
// Create an instance.
26+
await Page.EvaluateFunctionAsync(@"CustomClass => {
27+
self.customClass = new CustomClass();
28+
}", classHandle);
29+
30+
// Validate only one has been added.
31+
var prototypeHandle = await Page.EvaluateFunctionHandleAsync(@"CustomClass => {
32+
return CustomClass.prototype;
33+
}", classHandle);
2934

30-
[PuppeteerTest("page.spec.ts", "ExecutionContext.queryObjects", "should work for non-blank page")]
31-
[SkipBrowserFact(skipFirefox: true)]
32-
public async Task ShouldWorkForNonBlankPage()
33-
{
34-
// Instantiate an object
35-
await Page.GoToAsync(TestConstants.EmptyPage);
36-
await Page.EvaluateFunctionAsync("() => window.set = new Set(['hello', 'world'])");
37-
var prototypeHandle = await Page.EvaluateFunctionHandleAsync("() => Set.prototype");
3835
var objectsHandle = await Page.QueryObjectsAsync(prototypeHandle);
39-
var count = await Page.EvaluateFunctionAsync<int>("objects => objects.length", objectsHandle);
40-
Assert.Equal(1, count);
36+
Assert.Equal(
37+
1,
38+
await Page.EvaluateFunctionAsync(@"objects => {
39+
return objects.length;
40+
}", objectsHandle));
41+
42+
// Check that instances.
43+
Assert.True(await Page.EvaluateFunctionAsync<bool>(@"objects => {
44+
return objects[0] === self.customClass;
45+
}", objectsHandle));
4146
}
4247

4348
[PuppeteerTest("page.spec.ts", "ExecutionContext.queryObjects", "should fail for disposed handles")]

lib/PuppeteerSharp.Tests/PuppeteerSharp.Tests.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
<Folder Include="EmulationTests\" />
3131
<Folder Include="FixturesTests\" />
3232
<Folder Include="HeadfulTests\" />
33-
<Folder Include="InjectedTests\" />
33+
<Folder Include="PuppeteerUtilTests\" />
3434
</ItemGroup>
3535
<ItemGroup>
3636
<ProjectReference Include="..\PuppeteerSharp.TestServer\PuppeteerSharp.TestServer.csproj" />
@@ -53,6 +53,6 @@
5353
<None Remove="Emulation\" />
5454
<None Remove="FixturesTests\" />
5555
<None Remove="HeadfulTests\" />
56-
<None Remove="InjectedTests\" />
56+
<None Remove="PuppeteerUtilTests\" />
5757
</ItemGroup>
5858
</Project>

lib/PuppeteerSharp/AriaQueryHandlerFactory.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,13 @@ async Task<IElementHandle> QueryOne(IElementHandle element, string selector)
3434
return null;
3535
}
3636

37-
return await ((ElementHandle)element).Frame.SecondaryWorld.AdoptBackendNodeAsync(id).ConfigureAwait(false);
37+
return await ((ElementHandle)element).Frame.PuppeteerWorld.AdoptBackendNodeAsync(id).ConfigureAwait(false);
3838
}
3939

4040
async Task<IElementHandle> WaitFor(IElementHandle root, string selector, WaitForSelectorOptions options)
4141
{
4242
var frame = ((ElementHandle)root).Frame;
43-
var element = (await frame.SecondaryWorld.AdoptHandleAsync(root).ConfigureAwait(false)) as IElementHandle;
43+
var element = (await frame.PuppeteerWorld.AdoptHandleAsync(root).ConfigureAwait(false)) as IElementHandle;
4444

4545
Task<IElementHandle> Func(string selector) => QueryOne(element, selector);
4646

@@ -50,7 +50,7 @@ async Task<IElementHandle> WaitFor(IElementHandle root, string selector, WaitFor
5050
Function = (Func<string, Task<IElementHandle>>)Func,
5151
};
5252

53-
return await frame.SecondaryWorld.WaitForSelectorInPageAsync(
53+
return await frame.PuppeteerWorld.WaitForSelectorInPageAsync(
5454
@"(_, selector) => globalThis.ariaQuerySelector(selector)",
5555
selector,
5656
options,

lib/PuppeteerSharp/Connection.cs

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,8 @@ namespace PuppeteerSharp
1919
/// </summary>
2020
public class Connection : IDisposable, ICDPConnection
2121
{
22-
/// <summary>
23-
/// Gets default web socket factory implementation.
24-
/// </summary>
25-
[Obsolete("Use " + nameof(WebSocketTransport) + "." + nameof(WebSocketTransport.DefaultWebSocketFactory) + " instead")]
26-
public static readonly WebSocketFactory DefaultWebSocketFactory = WebSocketTransport.DefaultWebSocketFactory;
27-
2822
private readonly ILogger _logger;
29-
private readonly TaskQueue _callbackQueue = new TaskQueue();
23+
private readonly TaskQueue _callbackQueue = new();
3024

3125
private readonly ConcurrentDictionary<int, MessageTask> _callbacks;
3226
private readonly ConcurrentDictionary<string, CDPSession> _sessions;

lib/PuppeteerSharp/CustomQueriesManager.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,9 +154,9 @@ private static InternalQueryHandler MakeQueryHandler(CustomQueryHandler handler)
154154
internalHandler.WaitFor = async (IElementHandle root, string selector, WaitForSelectorOptions options) =>
155155
{
156156
var frame = (root as ElementHandle).Frame;
157-
var element = await frame.SecondaryWorld.AdoptHandleAsync(root).ConfigureAwait(false);
157+
var element = await frame.PuppeteerWorld.AdoptHandleAsync(root).ConfigureAwait(false);
158158

159-
return await frame.SecondaryWorld.WaitForSelectorInPageAsync(handler.QueryOne, selector, options).ConfigureAwait(false);
159+
return await frame.PuppeteerWorld.WaitForSelectorInPageAsync(handler.QueryOne, selector, options).ConfigureAwait(false);
160160
};
161161
}
162162

0 commit comments

Comments
 (0)