Skip to content

Commit

Permalink
Add TestConnectedEvent test
Browse files Browse the repository at this point in the history
  • Loading branch information
budcribar committed Feb 26, 2024
1 parent 4e95bc3 commit 7b75953
Show file tree
Hide file tree
Showing 19 changed files with 214 additions and 815 deletions.
62 changes: 59 additions & 3 deletions testassets/NUnitTestProject/TestBlazorFormControl.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;
using PeakSWC.RemoteBlazorWebView.WindowsForms;
//using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using PeakSWC.RemoteBlazorWebView;
using Microsoft.Extensions.Logging;
Expand All @@ -11,14 +10,14 @@
using System;
using System.IO;
using System.Linq.Expressions;
using System.Windows.Controls;
using System.Diagnostics;
using PeakSWC.RemoteWebView;
using Grpc.Net.Client;
using System.Threading.Channels;
using System.Windows.Forms;
using System.Windows.Threading;


namespace WebdriverTestProject
{

Expand All @@ -32,8 +31,9 @@ public static class BlazorWebViewFormFactory
{
BlazorWebView? control = null;
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(new BlazorWebViewDeveloperTools { Enabled = true });
serviceCollection.AddRemoteWindowsFormsBlazorWebView();
//serviceCollection.AddRemoteBlazorWebViewDeveloperTools();

serviceCollection.AddLogging(loggingBuilder =>
{
loggingBuilder.SetMinimumLevel(LogLevel.Debug).AddFile("Logs.txt", retainedFileCountLimit: 1);
Expand All @@ -46,11 +46,24 @@ public static class BlazorWebViewFormFactory
control = new BlazorWebView();
control.Services = serviceCollection.BuildServiceProvider();
control.RootComponents.Add(rootComponent);


if (MainForm != null)
{
MainForm.Controls.Clear();
MainForm.SuspendLayout();
control.Dock = System.Windows.Forms.DockStyle.Fill;
control.Location = new System.Drawing.Point(0, 0);
control.Size = new System.Drawing.Size(1440, 1215);
control.StartPath = "/";

MainForm.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
MainForm.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
MainForm.ClientSize = new System.Drawing.Size(1440, 1215);

control.Parent = BlazorWebViewFormFactory.MainForm;
MainForm.Controls.Add(control);
MainForm.ResumeLayout(false);
MainForm.Show();
}

Expand Down Expand Up @@ -338,6 +351,49 @@ public void TestPropertiesOnTime()
});
}

[TestMethod]
public void TestConnectedEvent()
{
var rootComponent = new RootComponent
(
"#app",
typeof(Home),
new Dictionary<string, object?>()

);
var webView = BlazorWebViewFormFactory.CreateBlazorComponent(rootComponent);
Assert.IsNotNull(webView);
AutoResetEvent threadInitialized = new AutoResetEvent(false);
BlazorWebViewFormFactory.MainForm?.Invoke(() => {

webView.Id = Guid.NewGuid();
webView.ServerUri = new System.Uri("https://localhost:5001");

webView.EnableMirrors = true;
webView.Connected += (sender, e) =>
{
webView.WebView.CoreWebView2.Navigate($"{e.Url}mirror/{e.Id}");
var user = e.User.Length > 0 ? $"by user {e.User.Length}" : "";
BlazorWebViewFormFactory.MainForm.Text += $" Controlled remotely {user}from ip address {e.IpAddress}";
Task.Delay(3000).Wait();
threadInitialized.Set();
};
webView.ReadyToConnect += (sender, e) =>
{
webView.NavigateToString($"<a href='{e.Url}app/{e.Id}' target='_blank'> {e.Url}app/{e.Id}</a>");
Utilities.OpenUrlInBrowser($"{e.Url}app/{e.Id}");

};
webView.HostPage = @"wwwroot\index.html";

});
Assert.IsTrue(threadInitialized.WaitOne(10000));


}



public static Process process;
public TestContext? TestContext { get; set; }

Expand Down
115 changes: 114 additions & 1 deletion testassets/NUnitTestProject/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Security.Cryptography;
using System.Text.RegularExpressions;


namespace WebdriverTestProject
{
Expand Down Expand Up @@ -241,7 +245,116 @@ public static void Kill(string name) => Process.GetProcesses().Where(p => p.Proc
// Wait for exit before re-starting
x.WaitForExit();
});

#endregion

#region Javascript

public static void DeleteGeneratedJsFiles(string directoryPath)
{
try
{
string[] jsFiles = Directory.GetFiles(directoryPath, "*.js");
Regex filePattern = new Regex(@"^script\d+\.js$", RegexOptions.IgnoreCase);

foreach (string file in jsFiles)
{
string fileName = Path.GetFileName(file);
if (filePattern.IsMatch(fileName))
{
File.Delete(file);
Console.WriteLine($"Deleted: {file}");
}
}
Console.WriteLine("Target JavaScript files have been deleted.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
public static void GenJavascript(int numberOfFiles = 10)
{
string basePath = @"wwwroot"; // Set your base path
string indexPath = Path.Combine(basePath, "index.html");

StringBuilder indexFileContent = new StringBuilder(File.Exists(indexPath) ? File.ReadAllText(indexPath) : "<html><head></head><body></body></html>");

for (int i = 1; i <= numberOfFiles; i++)
{
string fileName = $"script{i}.js";
string filePath = Path.Combine(basePath, fileName);
string randomString = GenerateRandomString(1000);
string checksum = CalculateChecksum(randomString);

string jsContent = $@"
const string = '{randomString}';
const checksum = '{checksum}';
function verifyChecksum() {{
const calculatedChecksum = sha256(string);
if(calculatedChecksum !== checksum) {{
alert('Checksum verification failed for {fileName}.');
throw new Error('Checksum verification failed.');
}}
}}
async function sha256(message) {{
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}}
verifyChecksum();";

File.WriteAllText(filePath, jsContent);

// Add script tag for this file to index.html
int bodyEndIndex = indexFileContent.ToString().LastIndexOf("</body>");
indexFileContent.Insert(bodyEndIndex, $"<script src=\"{fileName}\"></script>\n");
}

File.WriteAllText(indexPath, indexFileContent.ToString());
}

static string GenerateRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}

static string CalculateChecksum(string input)
{
using (SHA256 sha256Hash = SHA256.Create())
{
byte[] data = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
}
public static void OpenUrlInBrowser(string url)
{
try
{
// Use the default browser's executable to open the URL
Process.Start(new ProcessStartInfo
{
FileName = url,
UseShellExecute = true // Important for .NET Core/5+/6+ compatibility
});
Console.WriteLine($"Opened {url} in the default browser.");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to open URL: {ex.Message}");
}
}
}

#endregion
}
21 changes: 20 additions & 1 deletion testassets/NUnitTestProject/WebdriverTestProject.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
</PackageReference>
<PackageReference Include="MSTest.TestFramework" Version="3.2.2" />
<PackageReference Include="PeakSWC.RemoteBlazorWebView.Wpf" Version="8.0.2" />
<PackageReference Include="PeakSWC.RemoteBlazorWebView.WindowsForms" Version="8.0.2" />
<!--<PackageReference Include="PeakSWC.RemoteBlazorWebView.WindowsForms" Version="8.0.2" />-->
<PackageReference Include="Selenium.WebDriver" Version="4.18.1" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<PackageReference Include="Google.Protobuf" Version="3.25.3" />
Expand All @@ -28,9 +28,28 @@
<ItemGroup>
<Compile Remove="TestRemotePackageBlazorForm.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RemoteBlazorWebView.WinForms\RemoteBlazorWebView.WindowsForms.csproj" />
<ProjectReference Include="..\..\src\RemoteBlazorWebView\RemoteBlazorWebView.csproj" />
</ItemGroup>

<ItemGroup>
<Protobuf Include="..\..\src\Protos\webview.proto" GrpcServices="Client" Link="Protos\webview.proto" />
</ItemGroup>

<ItemGroup>
<Content Update="wwwroot\css\app.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\css\site.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\favicon.ico">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\index.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>
18 changes: 18 additions & 0 deletions testassets/NUnitTestProject/wwwroot/css/app.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#blazor-error-ui {
background: lightyellow;
bottom: 0;
box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
display: none;
left: 0;
padding: 0.6rem 1.25rem 0.7rem 1.25rem;
position: fixed;
width: 100%;
z-index: 1000;
}

#blazor-error-ui .dismiss {
cursor: pointer;
position: absolute;
right: 0.75rem;
top: 0.5rem;
}

This file was deleted.

This file was deleted.

86 changes: 0 additions & 86 deletions testassets/NUnitTestProject/wwwroot/css/open-iconic/FONT-LICENSE

This file was deleted.

Loading

0 comments on commit 7b75953

Please sign in to comment.