Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto

###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp

###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary

###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary

###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
85 changes: 85 additions & 0 deletions .github/workflows/sanity-workflow.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# This job is to test different profiles in sdk branch against full-commit id
# This workflow targets nunit

name: C-sharp Playwright SDK Test workflow on workflow_dispatch

on:
workflow_dispatch:
inputs:
commit_sha:
description: 'The full commit id to build'
required: true

jobs:
comment-run:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
max-parallel: 3
matrix:
dotnet: ['6.0.x', '5.0.x', '7.0.x']
os: [ windows-latest ]
name: NUnit Repo ${{ matrix.dotnet }} - ${{ matrix.os }} Sample
env:
BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}

steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.inputs.commit_sha }}
- uses: actions/github-script@98814c53be79b1d30f795b907e553d8679345975
id: status-check-in-progress
env:
job_name: NUnit Repo ${{ matrix.dotnet }} - ${{ matrix.os }} Sample
commit_sha: ${{ github.event.inputs.commit_sha }}
with:
github-token: ${{ github.token }}
script: |
const result = await github.rest.checks.create({
owner: context.repo.owner,
repo: context.repo.repo,
name: process.env.job_name,
head_sha: process.env.commit_sha,
status: 'in_progress'
}).catch((err) => ({status: err.status, response: err.response}));
console.log(`The status-check response : ${result.status} Response : ${JSON.stringify(result.response)}`)
if (result.status !== 201) {
console.log('Failed to create check run')
}
- name: Setup dotnet
uses: actions/setup-dotnet@v3
with:
dotnet-version: ${{ matrix.dotnet }}

- name: Install dependencies
run: dotnet build

- name: Run sample tests
run: dotnet test --filter "Category=sample-test"

- name: Run local tests
run: dotnet test --filter "Category=sample-local-test"

- if: always()
uses: actions/github-script@98814c53be79b1d30f795b907e553d8679345975
id: status-check-completed
env:
conclusion: ${{ job.status }}
job_name: NUnit Repo ${{ matrix.dotnet }} - ${{ matrix.os }} Sample
commit_sha: ${{ github.event.inputs.commit_sha }}
with:
github-token: ${{ github.token }}
script: |
const result = await github.rest.checks.create({
owner: context.repo.owner,
repo: context.repo.repo,
name: process.env.job_name,
head_sha: process.env.commit_sha,
status: 'completed',
conclusion: process.env.conclusion
}).catch((err) => ({status: err.status, response: err.response}));
console.log(`The status-check response : ${result.status} Response : ${JSON.stringify(result.response)}`)
if (result.status !== 201) {
console.log('Failed to create check run')
}
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
packages
TestResults
TestResult.xml
bin
obj
.vs
.DS_Store
25 changes: 25 additions & 0 deletions CSharp-Playwright-BrowserStack.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 25.0.1706.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp-Playwright-BrowserStack", "CSharp-Playwright-BrowserStack\CSharp-Playwright-BrowserStack.csproj", "{D309DDB3-1E3B-428B-B00B-1257F2532079}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D309DDB3-1E3B-428B-B00B-1257F2532079}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D309DDB3-1E3B-428B-B00B-1257F2532079}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D309DDB3-1E3B-428B-B00B-1257F2532079}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D309DDB3-1E3B-428B-B00B-1257F2532079}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4977FC04-06AD-47AF-90C6-66010738CC2D}
EndGlobalSection
EndGlobal
109 changes: 109 additions & 0 deletions CSharp-Playwright-BrowserStack/BrowserStackNUnitTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using Microsoft.Playwright;
using Newtonsoft.Json;
using NUnit.Framework;
using BrowserStack;
using Newtonsoft.Json.Linq;

namespace CSharpPlaywrightBrowserStack
{
[TestFixture]
public class BrowserStackNUnitTest
{
protected IBrowser browser;
protected IPage page;
protected string profile;
protected string environment;
protected string configFile;

private Local browserStackLocal;

public BrowserStackNUnitTest(string profile, string environment, string configFile)
{
this.profile = profile;
this.environment = environment;
this.configFile = configFile;
}

[SetUp]
public async Task Init()
{
// Get Configuration for correct profile
string currentDirectory = Directory.GetCurrentDirectory();
string path = Path.Combine(currentDirectory, configFile);
JObject config = JObject.Parse(File.ReadAllText(path));
if (config is null)
throw new Exception("Configuration not found!");

// Get Environment specific capabilities
JObject capabilitiesJsonArr = config.GetValue("environments") as JObject;
JObject capabilities = capabilitiesJsonArr.GetValue(environment) as JObject;

// Get Common Capabilities
JObject commonCapabilities = config.GetValue("capabilities") as JObject;

// Merge Capabilities
capabilities.Merge(commonCapabilities);

// Get username and accesskey
string? username = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME");
if (username is null)
username = config.GetValue("user").ToString();

string? accessKey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY");
if (accessKey is null)
accessKey = config.GetValue("key").ToString();

capabilities["browserstack.user"] = username;
capabilities["browserstack.key"] = accessKey;

// Start Local if browserstack.local is set to true
if (profile.Equals("local") && accessKey is not null)
{
capabilities["browserstack.local"] = true;
browserStackLocal = new Local();
List<KeyValuePair<string, string>> bsLocalArgs = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("key", accessKey)
};
foreach (var localOption in config.GetValue("localOptions") as JObject)
{
if (localOption.Value is not null)
{
bsLocalArgs.Add(new KeyValuePair<string, string>(localOption.Key, localOption.Value.ToString()));
}
}
browserStackLocal.start(bsLocalArgs);
}

string capsJson = JsonConvert.SerializeObject(capabilities);
string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capsJson);

var playwright = await Playwright.CreateAsync();
browser = await playwright.Chromium.ConnectAsync(cdpUrl);
page = await browser.NewPageAsync();
}

[TearDown]
public async Task Cleanup()
{
if (browser != null)
{
browser.CloseAsync();
}
if (browserStackLocal != null)
{
browserStackLocal.stop();
}
}

public static async Task SetStatus(IPage browserPage, bool passed)
{
if (browserPage is not null)
{
if (passed)
await browserPage.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \"Test Passed!\"}}");
else
await browserPage.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Test Failed!\"}}");
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>CSharpPlaywrightBrowserStack</RootNamespace>
<AssemblyName>CSharpPlaywrightBrowserStack</AssemblyName>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="log4net" Version="2.0.15" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="BrowserStackLocal" Version="2.3.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit.Analyzers" Version="3.6.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="Microsoft.Playwright" Version="1.36.0" />

<Content Include="local.conf.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="parallel.conf.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="single.conf.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Remove="local.conf.json" />
<None Remove="parallel.conf.json" />
<None Remove="single.conf.json" />
</ItemGroup>
</Project>
31 changes: 31 additions & 0 deletions CSharp-Playwright-BrowserStack/LocalTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using NUnit.Framework;

namespace CSharpPlaywrightBrowserStack
{
[TestFixture("local", "chrome", "local.conf.json")]
[Category("sample-local-test")]
public class LocalTest : BrowserStackNUnitTest
{
public LocalTest(string profile, string environment, string configFile) : base(profile, environment, configFile) { }

[Test]
public async Task HealthCheck()
{
try
{
// Navigate to the base url
await page.GotoAsync("http://bs-local.com:45454/");

// Verify if BrowserStackLocal running
var title = await page.TitleAsync();
StringAssert.Contains("BrowserStack Local", title);
SetStatus(page, title.Contains("BrowserStack Local"));
} catch (Exception)
{
SetStatus(page, false);
throw;
}
}
}
}

14 changes: 14 additions & 0 deletions CSharp-Playwright-BrowserStack/ParallelTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using NUnit.Framework;

namespace CSharpPlaywrightBrowserStack
{
[TestFixture("parallel", "chrome", "parallel.conf.json")]
[TestFixture("parallel", "playwright-firefox", "parallel.conf.json")]
[TestFixture("parallel", "playwright-webkit", "parallel.conf.json")]
[Parallelizable(ParallelScope.Fixtures)]
[Category("sample-parallel-test")]
public class ParallelTest : SingleTest
{
public ParallelTest(string profile, string environment, string configFile) : base(profile, environment, configFile) { }
}
}
Loading