Skip to content

Commit

Permalink
chore(generator): IWorker (microsoft#1263)
Browse files Browse the repository at this point in the history
  • Loading branch information
avodovnik authored Mar 8, 2021
1 parent 8de47d2 commit 69ebad3
Show file tree
Hide file tree
Showing 8 changed files with 263 additions and 137 deletions.
36 changes: 35 additions & 1 deletion src/PlaywrightSharp.Tests/WorkersTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using PlaywrightSharp.Tests.BaseTests;
using PlaywrightSharp.Xunit;
Expand Down Expand Up @@ -123,6 +125,38 @@ public async Task ShouldClearUponNavigation()
Assert.Empty(Page.Workers);
}

[Fact]
public async Task WorkerShouldWaitOnClose()
{
await Page.GoToAsync(TestConstants.EmptyPage);
var workerCreatedTask = Page.WaitForEventAsync(PageEvent.Worker);
await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))");
var worker = (await workerCreatedTask).Worker;

Assert.Single(Page.Workers);

var t = worker.WaitForCloseAsync();
await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");
await t;
Assert.Empty(Page.Workers);
}

[Fact]
public async Task WorkerShouldFailOnTimeout()
{
await Page.GoToAsync(TestConstants.EmptyPage);
var workerCreatedTask = Page.WaitForEventAsync(PageEvent.Worker);
await Page.EvaluateAsync("() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], { type: 'application/javascript' })))");
var worker = (await workerCreatedTask).Worker;

Assert.Single(Page.Workers);

var t = worker.WaitForCloseAsync(1);
await Task.Delay(100);
await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");
await Assert.ThrowsAsync<TimeoutException>(async () => await t);
}

[PlaywrightTest("workers.spec.ts", "should clear upon cross-process navigation")]
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
public async Task ShouldClearUponCrossProcessNavigation()
Expand Down Expand Up @@ -154,7 +188,7 @@ public async Task ShouldReportNetworkActivity()
var requestTask = Page.WaitForRequestAsync(url);
var responseTask = Page.WaitForResponseAsync(url);

await worker.Worker.EvaluateAsync("url => fetch(url).then(response => response.text()).then(console.log)", url);
await worker.Worker.EvaluateAsync<JsonElement>("url => fetch(url).then(response => response.text()).then(console.log)", url);

await TaskUtils.WhenAll(requestTask, responseTask);

Expand Down
133 changes: 133 additions & 0 deletions src/PlaywrightSharp/Contracts/IWorker.generated.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* MIT License
*
* Copyright (c) Microsoft Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* ------------------------------------------------------------------------------
* <auto-generated>
* This code was generated by a tool at:
* /utils/doclint/generateDotnetApi.js
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
* </auto-generated>
* ------------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace PlaywrightSharp
{
/// <summary>
/// <para>
/// The Worker class represents a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)">WebWorker</a>.
/// <c>worker</c> event is emitted on the page object to signal a worker creation. <c>close</c>
/// event is emitted on the worker object when the worker is gone.
/// </para>
/// <code>
/// Page.Worker += (_, worker) =&gt;<br/>
/// {<br/>
/// Console.WriteLine($"Worker created: {worker.Url}");<br/>
/// worker.Close += (_, _) =&gt; Console.WriteLine($"Worker closed {worker.Url}");<br/>
/// };<br/>
/// <br/>
/// Console.WriteLine("Current Workers:");<br/>
/// foreach(var pageWorker in Page.Workers)<br/>
/// {<br/>
/// Console.WriteLine($"\tWorker: {pageWorker.Url}");<br/>
/// }
/// </code>
/// </summary>
public partial interface IWorker
{
/// <summary>
/// <para>
/// Emitted when this dedicated <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)">WebWorker</a>
/// is terminated.
/// </para>
/// </summary>
event EventHandler Close;

/// <summary>
/// <para>Returns the return value of <paramref name="expression"/>.</para>
/// <para>
/// If the function passed to the <see cref="IWorker.EvaluateAsync"/> returns a [Promise],
/// then <see cref="IWorker.EvaluateAsync"/> would wait for the promise to resolve and
/// return its value.
/// </para>
/// <para>
/// If the function passed to the <see cref="IWorker.EvaluateAsync"/> returns a non-[Serializable]
/// value, then <see cref="IWorker.EvaluateAsync"/> returns <c>undefined</c>. Playwright
/// also supports transferring some additional values that are not serializable by <c>JSON</c>:
/// <c>-0</c>, <c>NaN</c>, <c>Infinity</c>, <c>-Infinity</c>.
/// </para>
/// </summary>
/// <param name="expression">
/// JavaScript expression to be evaluated in the browser context. If it looks like a
/// function declaration, it is interpreted as a function. Otherwise, evaluated as an
/// expression.
/// </param>
/// <param name="arg">Optional argument to pass to <paramref name="expression"/>.</param>
Task<T> EvaluateAsync<T>(string expression, object arg = null);

/// <summary>
/// <para>Returns the return value of <paramref name="expression"/> as a <see cref="IJSHandle"/>.</para>
/// <para>
/// The only difference between <see cref="IWorker.EvaluateAsync"/> and <see cref="IWorker.EvaluateHandleAsync"/>
/// is that <see cref="IWorker.EvaluateHandleAsync"/> returns <see cref="IJSHandle"/>.
/// </para>
/// <para>
/// If the function passed to the <see cref="IWorker.EvaluateHandleAsync"/> returns
/// a [Promise], then <see cref="IWorker.EvaluateHandleAsync"/> would wait for the promise
/// to resolve and return its value.
/// </para>
/// </summary>
/// <param name="expression">
/// JavaScript expression to be evaluated in the browser context. If it looks like a
/// function declaration, it is interpreted as a function. Otherwise, evaluated as an
/// expression.
/// </param>
/// <param name="arg">Optional argument to pass to <paramref name="expression"/>.</param>
Task<IJSHandle> EvaluateHandleAsync(string expression, object arg = null);

string Url { get; }


#pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved
/// <summary><para>Performs action and waits for the Worker to close.</para></summary>
/// <param name="timeout">
/// Maximum time to wait for in milliseconds. Defaults to <c>30000</c> (30 seconds).
/// Pass <c>0</c> to disable timeout. The default value can be changed by using the
/// <see cref="IBrowserContext.SetDefaultTimeout"/>.
/// </param>
Task<IWorker> WaitForCloseAsync(float? timeout = null);
#pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace PlaywrightSharp.Contracts.Models
{
/// <summary>
/// Represents an `Undefined` argument.
/// </summary>
public sealed class UndefinedEvaluationArgument : IEquatable<UndefinedEvaluationArgument>
{
/// <summary>
/// Initializes a new instance of the <see cref="UndefinedEvaluationArgument"/> class.
/// </summary>
private UndefinedEvaluationArgument()
{
// NOOP
}

/// <summary>
/// Gets a representation of the <c>Undefined</c> argument.
/// </summary>
public static UndefinedEvaluationArgument Undefined { get; } = new UndefinedEvaluationArgument();

/// <inheritdoc/>
public bool Equals(UndefinedEvaluationArgument other) => ReferenceEquals(this, other);

/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as UndefinedEvaluationArgument);

/// <inheritdoc/>
public override int GetHashCode() => base.GetHashCode();
}
}
92 changes: 0 additions & 92 deletions src/PlaywrightSharp/IWorker.cs

This file was deleted.

5 changes: 5 additions & 0 deletions src/PlaywrightSharp/ScriptsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ internal static T ParseEvaluateResult<T>(JsonElement? result)

internal static EvaluateArgument SerializedArgument(object args)
{
if (args is EvaluateArgument evaluateArgument)
{
return evaluateArgument;
}

var result = new EvaluateArgument();
var guids = new List<EvaluateArgumentGuidElement>();

Expand Down
7 changes: 3 additions & 4 deletions src/PlaywrightSharp/Transport/Channels/WorkerChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,17 @@ internal Task<JSHandleChannel> EvaluateExpressionHandleAsync(string script, bool
{
["expression"] = script,
["isFunction"] = isFunction,
["arg"] = arg,
["arg"] = ScriptsHelper.SerializedArgument(arg),
});

internal Task<JsonElement?> EvaluateExpressionAsync(
string script,
bool isFunction,
object arg,
bool serializeArgument = false)
object arg)
{
JsonSerializerOptions serializerOptions;

if (serializeArgument)
if (!(arg is EvaluateArgument))
{
serializerOptions = JsonExtensions.GetNewDefaultSerializerOptions(false);
arg = new EvaluateArgument
Expand Down
Loading

0 comments on commit 69ebad3

Please sign in to comment.