diff --git a/playwright-dotnet/PlaywrightDotnetTests.csproj b/playwright-dotnet/PlaywrightDotnetTests.csproj new file mode 100644 index 0000000..217af50 --- /dev/null +++ b/playwright-dotnet/PlaywrightDotnetTests.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + + + + + + + + diff --git a/playwright-dotnet/PlaywrightIPhoneTest.cs b/playwright-dotnet/PlaywrightIPhoneTest.cs new file mode 100644 index 0000000..4d6ffb9 --- /dev/null +++ b/playwright-dotnet/PlaywrightIPhoneTest.cs @@ -0,0 +1,51 @@ +using Microsoft.Playwright; +using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +class PlaywrightIPhoneTest +{ + public static async Task main(string[] args) + { + using var playwright = await Playwright.CreateAsync(); + + Dictionary browserstackOptions = new Dictionary(); + browserstackOptions.Add("name", "Test on Playwright emulated IPhone 11 Pro"); + browserstackOptions.Add("build", "playwright-dotnet-4"); + browserstackOptions.Add("browser", "playwright-webkit"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + browserstackOptions.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + browserstackOptions.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + string capsJson = JsonConvert.SerializeObject(browserstackOptions); + string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capsJson); + + await using var browser = await playwright.Chromium.ConnectAsync(cdpUrl); + + var context = await browser.NewContextAsync(playwright.Devices["iPhone 11 Pro"]); // Complete list of devices - https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json + + var page = await context.NewPageAsync(); + try { + await page.GotoAsync("https://www.google.co.in/"); + await page.Locator("[aria-label='Search']").ClickAsync(); + await page.FillAsync("[aria-label='Search']", "BrowserStack"); + await page.Keyboard.PressAsync("Enter"); + await page.WaitForTimeoutAsync(1000); + var title = await page.TitleAsync(); + + if (title == "BrowserStack - Google Search") + { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + await MarkTestStatus("passed", "Title matched", page); + } else { + await MarkTestStatus("failed", "Title did not match", page); + } + } + catch (Exception err) { + await MarkTestStatus("failed", err.Message, page); + } + await browser.CloseAsync(); + } + public static async Task MarkTestStatus(string status, string reason, IPage page) { + await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} diff --git a/playwright-dotnet/PlaywrightLocalTest.cs b/playwright-dotnet/PlaywrightLocalTest.cs new file mode 100644 index 0000000..92fba74 --- /dev/null +++ b/playwright-dotnet/PlaywrightLocalTest.cs @@ -0,0 +1,51 @@ +using Microsoft.Playwright; +using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +class PlaywrightLocalTest +{ + public static async Task main(string[] args) + { + using var playwright = await Playwright.CreateAsync(); + + Dictionary browserstackOptions = new Dictionary(); + browserstackOptions.Add("name", "Playwright local sample test"); + browserstackOptions.Add("build", "playwright-dotnet-3"); + browserstackOptions.Add("os", "osx"); + browserstackOptions.Add("os_version", "catalina"); + browserstackOptions.Add("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + browserstackOptions.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + browserstackOptions.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + browserstackOptions.Add("browserstack.local", "true"); + string capsJson = JsonConvert.SerializeObject(browserstackOptions); + string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capsJson); + + await using var browser = await playwright.Chromium.ConnectAsync(cdpUrl); + var page = await browser.NewPageAsync(); + try { + await page.GotoAsync("https://www.google.co.in/"); + await page.Locator("[aria-label='Search']").ClickAsync(); + await page.FillAsync("[aria-label='Search']", "BrowserStack"); + await page.Locator("[aria-label='Google Search'] >> nth=0").ClickAsync(); + var title = await page.TitleAsync(); + + if (title == "BrowserStack - Google Search") + { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + await MarkTestStatus("passed", "Title matched", page); + } + else { + await MarkTestStatus("failed", "Title did not match", page); + } + } + catch (Exception err){ + await MarkTestStatus("failed", err.Message, page); + } + await browser.CloseAsync(); + } + public static async Task MarkTestStatus(string status, string reason, IPage page) { + await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} diff --git a/playwright-dotnet/PlaywrightParallelTest.cs b/playwright-dotnet/PlaywrightParallelTest.cs new file mode 100644 index 0000000..d95eada --- /dev/null +++ b/playwright-dotnet/PlaywrightParallelTest.cs @@ -0,0 +1,121 @@ +using Microsoft.Playwright; +using System; +using System.Threading; +using Newtonsoft.Json; +using System.Collections; + +class PlaywrightParallelTest +{ + public static async Task main(string[] args) + { + // The following capability variables contains the set of os/browser environments where you want to run your tests. You can choose to alter this list according to your needs. Read more on https://browserstack.com/docs/automate/playwright/browsers-and-os + try { + ArrayList capabilitiesList = getCapabilitiesList(); + Task[] taskList = new Task[capabilitiesList.Count]; + + for (int i = 0; i < capabilitiesList.Count; i++) + { + string capsJson; + capsJson = JsonConvert.SerializeObject(capabilitiesList[i]); + var task = Executetestwithcaps(capsJson); + taskList[i] = task; + } + + await Task.WhenAll(taskList); + + } catch (Exception e) { + Console.WriteLine(e); + } + } + static ArrayList getCapabilitiesList() + { + ArrayList capabilitiesList = new ArrayList(); + + Dictionary catalinaChromeCap = new Dictionary(); + catalinaChromeCap.Add("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaChromeCap.Add("browser_version", "latest"); + catalinaChromeCap.Add("os", "osx"); + catalinaChromeCap.Add("os_version", "catalina"); + catalinaChromeCap.Add("name", "Branded Google Chrome on Catalina"); + catalinaChromeCap.Add("build", "playwright-dotnet-2"); + catalinaChromeCap.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + catalinaChromeCap.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + capabilitiesList.Add(catalinaChromeCap); + + Dictionary catalinaEdgeCap = new Dictionary(); + catalinaEdgeCap.Add("browser", "edge"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaEdgeCap.Add("browser_version", "latest"); + catalinaEdgeCap.Add("os", "osx"); + catalinaEdgeCap.Add("os_version", "catalina"); + catalinaEdgeCap.Add("name", "Branded Microsoft Edge on Catalina"); + catalinaEdgeCap.Add("build", "playwright-dotnet-2"); + catalinaEdgeCap.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + catalinaEdgeCap.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + capabilitiesList.Add(catalinaEdgeCap); + + Dictionary catalinaFirefoxCap = new Dictionary(); + catalinaFirefoxCap.Add("browser", "playwright-firefox"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaFirefoxCap.Add("os", "osx"); + catalinaFirefoxCap.Add("os_version", "catalina"); + catalinaFirefoxCap.Add("name", "Playwright firefox on Catalina"); + catalinaFirefoxCap.Add("build", "playwright-dotnet-2"); + catalinaFirefoxCap.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + catalinaFirefoxCap.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + capabilitiesList.Add(catalinaFirefoxCap); + + Dictionary catalinaWebkitCap = new Dictionary(); + catalinaWebkitCap.Add("browser", "playwright-webkit"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaWebkitCap.Add("os", "osx"); + catalinaWebkitCap.Add("os_version", "catalina"); + catalinaWebkitCap.Add("name", "Playwright webkit on Catalina"); + catalinaWebkitCap.Add("build", "playwright-dotnet-2"); + catalinaWebkitCap.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + catalinaWebkitCap.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + capabilitiesList.Add(catalinaWebkitCap); + + Dictionary catalinaChromiumCap = new Dictionary(); + catalinaChromiumCap.Add("browser", "playwright-chromium"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaChromiumCap.Add("os", "osx"); + catalinaChromiumCap.Add("os_version", "catalina"); + catalinaChromiumCap.Add("name", "Playwright webkit on Catalina"); + catalinaChromiumCap.Add("build", "playwright-dotnet-2"); + catalinaChromiumCap.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + catalinaChromiumCap.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + capabilitiesList.Add(catalinaChromiumCap); + + return capabilitiesList; + } + + //Executetestwithcaps function takes capabilities from 'SampleTestCase' function and executes the test + public static async Task Executetestwithcaps(string capabilities) + { + using var playwright = await Playwright.CreateAsync(); + string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capabilities); + + await using var browser = await playwright.Chromium.ConnectAsync(cdpUrl); + var page = await browser.NewPageAsync(); + try { + await page.GotoAsync("https://www.google.co.in/"); + await page.Locator("[aria-label='Search']").ClickAsync(); + await page.FillAsync("[aria-label='Search']", "BrowserStack"); + await page.Locator("[aria-label='Google Search'] >> nth=0").ClickAsync(); + var title = await page.TitleAsync(); + + if (title == "BrowserStack - Google Search") + { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + await MarkTestStatus("passed", "Title matched", page); + } else + { + await MarkTestStatus("failed", "Title did not match", page); + } + } + catch (Exception err) { + await MarkTestStatus("failed", err.Message, page); + } + await browser.CloseAsync(); + } + public static async Task MarkTestStatus(string status, string reason, IPage page) { + await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} diff --git a/playwright-dotnet/PlaywrightPixelTest.cs b/playwright-dotnet/PlaywrightPixelTest.cs new file mode 100644 index 0000000..f95ec9c --- /dev/null +++ b/playwright-dotnet/PlaywrightPixelTest.cs @@ -0,0 +1,52 @@ +using Microsoft.Playwright; +using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +class PlaywrightPixelTest +{ + public static async Task main(string[] args) + { + using var playwright = await Playwright.CreateAsync(); + + Dictionary browserstackOptions = new Dictionary(); + browserstackOptions.Add("name", "Test on Playwright emulated Pixel 5"); + browserstackOptions.Add("build", "playwright-dotnet-4"); + browserstackOptions.Add("browser", "playwright-webkit"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + browserstackOptions.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + browserstackOptions.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + string capsJson = JsonConvert.SerializeObject(browserstackOptions); + string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capsJson); + + await using var browser = await playwright.Chromium.ConnectAsync(cdpUrl); + + var context = await browser.NewContextAsync(playwright.Devices["Pixel 5"]); // Complete list of devices - https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json + + var page = await context.NewPageAsync(); + try { + await page.GotoAsync("https://www.google.co.in/"); + await page.Locator("[aria-label='Search']").ClickAsync(); + await page.FillAsync("[aria-label='Search']", "BrowserStack"); + await page.Keyboard.PressAsync("Enter"); + await page.WaitForTimeoutAsync(1000); + var title = await page.TitleAsync(); + + if (title == "BrowserStack - Google Search") + { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + await MarkTestStatus("passed", "Title matched", page); + } else { + await MarkTestStatus("failed", "Title did not match", page); + } + } + catch (Exception err) { + await MarkTestStatus("failed", err.Message, page); + } + await browser.CloseAsync(); + } + + public static async Task MarkTestStatus(string status, string reason, IPage page) { + await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} diff --git a/playwright-dotnet/PlaywrightTest.cs b/playwright-dotnet/PlaywrightTest.cs new file mode 100644 index 0000000..78a2320 --- /dev/null +++ b/playwright-dotnet/PlaywrightTest.cs @@ -0,0 +1,51 @@ +using Microsoft.Playwright; +using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +class PlaywrightTest +{ + public static async Task main(string[] args) + { + using var playwright = await Playwright.CreateAsync(); + + Dictionary browserstackOptions = new Dictionary(); + browserstackOptions.Add("name", "Playwright first sample test"); + browserstackOptions.Add("build", "playwright-dotnet-1"); + browserstackOptions.Add("os", "osx"); + browserstackOptions.Add("os_version", "catalina"); + browserstackOptions.Add("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + browserstackOptions.Add("browserstack.username", "BROWSERSTACK_USERNAME"); + browserstackOptions.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + string capsJson = JsonConvert.SerializeObject(browserstackOptions); + string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capsJson); + + await using var browser = await playwright.Chromium.ConnectAsync(cdpUrl); + var page = await browser.NewPageAsync(); + try { + await page.GotoAsync("https://www.google.co.in/"); + await page.Locator("[aria-label='Search']").ClickAsync(); + await page.FillAsync("[aria-label='Search']", "BrowserStack"); + await page.Locator("[aria-label='Google Search'] >> nth=0").ClickAsync(); + var title = await page.TitleAsync(); + + if (title == "BrowserStack - Google Search") + { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + await MarkTestStatus("passed", "Title matched", page); + } + else { + await MarkTestStatus("failed", "Title did not match", page); + } + } + catch (Exception err) { + await MarkTestStatus("failed", err.Message, page); + } + await browser.CloseAsync(); + } + + public static async Task MarkTestStatus(string status, string reason, IPage page) { + await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} diff --git a/playwright-dotnet/Program.cs b/playwright-dotnet/Program.cs new file mode 100644 index 0000000..82b4ad9 --- /dev/null +++ b/playwright-dotnet/Program.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; + +namespace PlaywrightTesting +{ + class Program + { + public static async Task Main(string[] args) + { + switch (args[0]) + { + case "single": + Console.WriteLine("Running Single Test"); + await PlaywrightTest.main(args); // redirects to class main() method + break; + case "parallel": + Console.WriteLine("Running Parallel Test"); + await PlaywrightParallelTest.main(args); + break; + case "local": + Console.WriteLine("Running Local Test"); + await PlaywrightLocalTest.main(args); + break; + case "iphonetest": + Console.WriteLine("Running iPhone Test"); + await PlaywrightIPhoneTest.main(args); + break; + case "pixeltest": + Console.WriteLine("Running Pixel Test"); + await PlaywrightPixelTest.main(args); + break; + default: + Console.WriteLine("Running Single Test by default"); + await PlaywrightTest.main(args); + break; + } + } + } +} diff --git a/playwright-dotnet/README.md b/playwright-dotnet/README.md new file mode 100644 index 0000000..1aa0413 --- /dev/null +++ b/playwright-dotnet/README.md @@ -0,0 +1,36 @@ +# Testing with playwright-browserstack in C# + +[Playwright](https://playwright.dev/dotnet/) Integration with BrowserStack. + +![BrowserStack Logo](https://d98b8t1nnulk5.cloudfront.net/production/images/layout/logo-header.png?1469004780) + +## Setup + +* Clone the repo and run `cd Playwright-dotnet` +* Run `dotnet build` + +## Running your tests + +- To run a single test, run `dotnet run single` +- To run a parallel test, run command `dotnet run parallel` + + ### Run sample test on privately hosted websites + + **Using Command-line Interface** + 1. You have to download the BrowserStack Local binary from the links below (depending on your environment): + * [OS X (10.7 and above)](https://www.browserstack.com/browserstack-local/BrowserStackLocal-darwin-x64.zip) + * [Linux 32-bit](https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-ia32.zip) + * [Linux 64-bit](https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-x64.zip) + * [Windows (XP and above)](https://www.browserstack.com/browserstack-local/BrowserStackLocal-win32.zip) + 2. Once you have downloaded and unzipped the file, you can initiate the binary by running the command: `./BrowserStackLocal --key YOUR_ACCESS_KEY` + 3. Once you see the terminal say "[SUCCESS]" You can now access your local server(s) in our remote browser”, your local testing connection is considered established. + 4. You can then run the sample Local test using `dotnet run local` + +Understand how many parallel sessions you need by using our [Parallel Test Calculator](https://www.browserstack.com/automate/parallel-calculator?ref=github) + + +## Notes +* You can view your test results on the [BrowserStack Automate dashboard](https://www.browserstack.com/automate) + +## Additional Resources +* [Documentation for writing Automate test scripts with BrowserStack](https://www.browserstack.com/docs/automate/playwright) diff --git a/playwright-java/README.md b/playwright-java/README.md new file mode 100644 index 0000000..70dc770 --- /dev/null +++ b/playwright-java/README.md @@ -0,0 +1,45 @@ +# Testing with playwright-browserstack in Java + +[Playwright](https://playwright.dev/java/) Integration with BrowserStack. + +![BrowserStack Logo](https://d98b8t1nnulk5.cloudfront.net/production/images/layout/logo-header.png?1469004780) + +## Setup + +* Clone the repo and run `cd playwright-java` + +## Running your tests + +- To run a single test, run + `mvn -Dexec.mainClass="com.browserstack.PlaywrightSingleTest" -Dexec.classpathScope=test test-compile exec:java +` +- To run parallel tests, run + `mvn -Dexec.mainClass="com.browserstack.PlaywrightParallelTest" -Dexec.classpathScope=test test-compile exec:java +` + + ### Run sample test on privately hosted websites + + **Using Language Bindings** + 1. Run + `mvn -Dexec.mainClass="com.browserstack.PlaywrightLocalUsingBindingsTest" -Dexec.classpathScope=test test-compile exec:java` + + **Using Command-line Interface** + + 1. You have to download the BrowserStack Local binary from the links below (depending on your environment): + * [OS X (10.7 and above)](https://www.browserstack.com/browserstack-local/BrowserStackLocal-darwin-x64.zip) + * [Linux 32-bit](https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-ia32.zip) + * [Linux 64-bit](https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-x64.zip) + * [Windows (XP and above)](https://www.browserstack.com/browserstack-local/BrowserStackLocal-win32.zip) + 2. Once you have downloaded and unzipped the file, you can initiate the binary by running the command: `./BrowserStackLocal --key YOUR_ACCESS_KEY` + 3. Once you see the terminal say "[SUCCESS]" You can now access your local server(s) in our remote browser”, your local testing connection is considered established. + 4. You can then run the sample Local test using + `mvn -Dexec.mainClass="com.browserstack.PlaywrightLocalTest" -Dexec.classpathScope=test test-compile exec:java` + +Understand how many parallel sessions you need by using our [Parallel Test Calculator](https://www.browserstack.com/automate/parallel-calculator?ref=github) + + +## Notes +* You can view your test results on the [BrowserStack Automate dashboard](https://www.browserstack.com/automate) + +## Additional Resources +* [Documentation for writing Automate test scripts with BrowserStack](https://www.browserstack.com/docs/automate/playwright) diff --git a/playwright-java/pom.xml b/playwright-java/pom.xml new file mode 100644 index 0000000..ccb220a --- /dev/null +++ b/playwright-java/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + org.example + playwright-java + 1.0-SNAPSHOT + + + 11 + 11 + + + + com.microsoft.playwright + playwright + 1.19.0 + compile + + + com.browserstack + browserstack-local-java + 1.0.6 + compile + + + diff --git a/playwright-java/src/test/java/com/browserstack/PlaywrightLocalTest.java b/playwright-java/src/test/java/com/browserstack/PlaywrightLocalTest.java new file mode 100644 index 0000000..1ed944d --- /dev/null +++ b/playwright-java/src/test/java/com/browserstack/PlaywrightLocalTest.java @@ -0,0 +1,53 @@ +package com.browserstack; + +import com.google.gson.JsonObject; +import com.microsoft.playwright.*; +import java.net.URLEncoder; + +public class PlaywrightLocalTest { + public static void main(String[] args) { + try (Playwright playwright = Playwright.create()) { + JsonObject capabilitiesObject = new JsonObject(); + capabilitiesObject.addProperty("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + capabilitiesObject.addProperty("browser_version", "latest"); + capabilitiesObject.addProperty("os", "osx"); + capabilitiesObject.addProperty("os_version", "catalina"); + capabilitiesObject.addProperty("name", "Playwright first local test"); + capabilitiesObject.addProperty("build", "playwright-java-3"); + capabilitiesObject.addProperty("browserstack.username", "BROWSERSTACK_USERNAME"); + capabilitiesObject.addProperty("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + capabilitiesObject.addProperty("browserstack.local", "true"); + + BrowserType chromium = playwright.chromium(); + String caps = URLEncoder.encode(capabilitiesObject.toString(), "utf-8"); + String ws_endpoint = "wss://cdp.browserstack.com/playwright?caps=" + caps; + Browser browser = chromium.connect(ws_endpoint); + Page page = browser.newPage(); + try { + page.navigate("https://www.google.co.in/"); + Locator locator = page.locator("[aria-label='Search']"); + locator.click(); + page.fill("[aria-label='Search']", "BrowserStack"); + page.locator("[aria-label='Google Search'] >> nth=0").click(); + String title = page.title(); + + if (title.equals("BrowserStack - Google Search")) { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + markTestStatus("passed", "Title matched", page); + } else { + markTestStatus("failed", "Title did not match", page); + } + } catch (Exception err) { + markTestStatus("failed", err.getMessage(), page); + } + browser.close(); + } catch (Exception err) { + System.out.println(err); + } + } + + public static void markTestStatus(String status, String reason, Page page) { + Object result; + result = page.evaluate("_ => {}", "browserstack_executor: { \"action\": \"setSessionStatus\", \"arguments\": { \"status\": \"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} diff --git a/playwright-java/src/test/java/com/browserstack/PlaywrightLocalUsingBindingsTest.java b/playwright-java/src/test/java/com/browserstack/PlaywrightLocalUsingBindingsTest.java new file mode 100644 index 0000000..4b313fc --- /dev/null +++ b/playwright-java/src/test/java/com/browserstack/PlaywrightLocalUsingBindingsTest.java @@ -0,0 +1,72 @@ +package com.browserstack; + +import com.google.gson.JsonObject; +import com.microsoft.playwright.*; +import java.net.URLEncoder; +import java.util.HashMap; + +import com.browserstack.local.Local; + +public class PlaywrightLocalUsingBindingsTest { + public static void main(String[] args) { + try (Playwright playwright = Playwright.create()) { + JsonObject capabilitiesObject = new JsonObject(); + capabilitiesObject.addProperty("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + capabilitiesObject.addProperty("browser_version", "latest"); + capabilitiesObject.addProperty("os", "osx"); + capabilitiesObject.addProperty("os_version", "catalina"); + capabilitiesObject.addProperty("name", "Playwright first local test"); + capabilitiesObject.addProperty("build", "playwright-java-3"); + capabilitiesObject.addProperty("browserstack.username", "BROWSERSTACK_USERNAME"); + capabilitiesObject.addProperty("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + capabilitiesObject.addProperty("browserstack.local", "true"); + + //Creates an instance of Local + Local bsLocal = new Local(); + + // You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY". + HashMap bsLocalArgs = new HashMap(); + bsLocalArgs.put("key", "BROWSERSTACK_ACCESS_KEY"); + + // Starts the Local instance with the required arguments + bsLocal.start(bsLocalArgs); + + // Check if BrowserStack local instance is running + System.out.println("BrowserStackLocal running: " + bsLocal.isRunning()); + + BrowserType chromium = playwright.chromium(); + String caps = URLEncoder.encode(capabilitiesObject.toString(), "utf-8"); + String ws_endpoint = "wss://cdp.browserstack.com/playwright?caps=" + caps; + Browser browser = chromium.connect(ws_endpoint); + Page page = browser.newPage(); + try { + page.navigate("https://www.google.co.in/"); + Locator locator = page.locator("[aria-label='Search']"); + locator.click(); + page.fill("[aria-label='Search']", "BrowserStack"); + page.locator("[aria-label='Google Search'] >> nth=0").click(); + String title = page.title(); + + if (title.equals("BrowserStack - Google Search")) { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + markTestStatus("passed", "Title matched", page); + } else { + markTestStatus("failed", "Title did not match", page); + } + } catch (Exception err) { + markTestStatus("failed", err.getMessage(), page); + } + browser.close(); + + //Stop the Local instance + bsLocal.stop(); + } catch (Exception err) { + System.out.println(err); + } + } + + public static void markTestStatus(String status, String reason, Page page) { + Object result; + result = page.evaluate("_ => {}", "browserstack_executor: { \"action\": \"setSessionStatus\", \"arguments\": { \"status\": \"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} diff --git a/playwright-java/src/test/java/com/browserstack/PlaywrightParallelTest.java b/playwright-java/src/test/java/com/browserstack/PlaywrightParallelTest.java new file mode 100644 index 0000000..6d42984 --- /dev/null +++ b/playwright-java/src/test/java/com/browserstack/PlaywrightParallelTest.java @@ -0,0 +1,117 @@ +package com.browserstack; + +import com.google.gson.JsonObject; +import com.microsoft.playwright.*; + +import java.net.URLEncoder; +import java.util.ArrayList; + +class RunSession implements Runnable { + private JsonObject caps; + + RunSession(JsonObject capabilities) { + this.caps = capabilities; + } + + public void run() { + try (Playwright playwright = Playwright.create()) { + BrowserType chromium = playwright.chromium(); + String caps = URLEncoder.encode(this.caps.toString(), "utf-8"); + String ws_endpoint = "wss://cdp.browserstack.com/playwright?caps=" + caps; + Browser browser = chromium.connect(ws_endpoint); + Page page = browser.newPage(); + try { + page.navigate("https://www.google.co.in/"); + Locator locator = page.locator("[aria-label='Search']"); + locator.click(); + page.fill("[aria-label='Search']", "BrowserStack"); + page.locator("[aria-label='Google Search'] >> nth=0").click(); + String title = page.title(); + + if (title.equals("BrowserStack - Google Search")) { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + markTestStatus("passed", "Title matched", page); + } else { + markTestStatus("failed", "Title did not match", page); + } + } catch (Exception err) { + markTestStatus("failed", err.getMessage(), page); + } + browser.close(); + } catch (Exception err) { + System.out.println(err); + } + } + public static void markTestStatus(String status, String reason, Page page) { + Object result; + result = page.evaluate("_ => {}", "browserstack_executor: { \"action\": \"setSessionStatus\", \"arguments\": { \"status\": \"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} + +public class PlaywrightParallelTest { + public static void main(String[] args) throws Exception { + ArrayList capabilitiesList = getCapabilitiesList(); + + ArrayList threadList = new ArrayList(); + + for (JsonObject capabilities: capabilitiesList) { + capabilities.addProperty("browserstack.username", "BROWSERSTACK_USERNAME"); + capabilities.addProperty("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + Thread sessionThread = new Thread(new RunSession(capabilities)); + threadList.add(sessionThread); + sessionThread.start(); + } + + for (Thread thread: threadList) { + thread.join(); + } + } + + public static ArrayList getCapabilitiesList() { + ArrayList capabilitiesList = new ArrayList(); + + JsonObject catalinaChromeCap = new JsonObject(); + catalinaChromeCap.addProperty("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaChromeCap.addProperty("browser_version", "latest"); + catalinaChromeCap.addProperty("os", "osx"); + catalinaChromeCap.addProperty("os_version", "catalina"); + catalinaChromeCap.addProperty("name", "Branded Google Chrome on Catalina"); + catalinaChromeCap.addProperty("build", "playwright-java-2"); + capabilitiesList.add(catalinaChromeCap); + + JsonObject catalinaEdgeCap = new JsonObject(); + catalinaEdgeCap.addProperty("browser", "edge"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaEdgeCap.addProperty("browser_version", "latest"); + catalinaEdgeCap.addProperty("os", "osx"); + catalinaEdgeCap.addProperty("os_version", "catalina"); + catalinaEdgeCap.addProperty("name", "Branded Microsoft Edge on Catalina"); + catalinaEdgeCap.addProperty("build", "playwright-java-2"); + capabilitiesList.add(catalinaEdgeCap); + + JsonObject catalinaFirefoxCap = new JsonObject(); + catalinaFirefoxCap.addProperty("browser", "playwright-firefox"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaFirefoxCap.addProperty("os", "osx"); + catalinaFirefoxCap.addProperty("os_version", "catalina"); + catalinaFirefoxCap.addProperty("name", "Playwright firefox on Catalina"); + catalinaFirefoxCap.addProperty("build", "playwright-java-2"); + capabilitiesList.add(catalinaFirefoxCap); + + JsonObject catalinaWebkitCap = new JsonObject(); + catalinaWebkitCap.addProperty("browser", "playwright-webkit"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaWebkitCap.addProperty("os", "osx"); + catalinaWebkitCap.addProperty("os_version", "catalina"); + catalinaWebkitCap.addProperty("name", "Playwright webkit on Catalina"); + catalinaWebkitCap.addProperty("build", "playwright-java-2"); + capabilitiesList.add(catalinaWebkitCap); + + JsonObject catalinaChromiumCap = new JsonObject(); + catalinaChromiumCap.addProperty("browser", "playwright-chromium"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + catalinaChromiumCap.addProperty("os", "osx"); + catalinaChromiumCap.addProperty("os_version", "catalina"); + catalinaChromiumCap.addProperty("name", "Playwright webkit on Catalina"); + catalinaChromiumCap.addProperty("build", "playwright-java-2"); + capabilitiesList.add(catalinaChromiumCap); + + return capabilitiesList; + } +} diff --git a/playwright-java/src/test/java/com/browserstack/PlaywrightTest.java b/playwright-java/src/test/java/com/browserstack/PlaywrightTest.java new file mode 100644 index 0000000..be01cda --- /dev/null +++ b/playwright-java/src/test/java/com/browserstack/PlaywrightTest.java @@ -0,0 +1,53 @@ +package com.browserstack; + +import com.google.gson.JsonObject; +import com.microsoft.playwright.*; +import java.net.URLEncoder; + +public class PlaywrightTest { + public static void main(String[] args) { + try (Playwright playwright = Playwright.create()) { + JsonObject capabilitiesObject = new JsonObject(); + capabilitiesObject.addProperty("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + capabilitiesObject.addProperty("browser_version", "latest"); + capabilitiesObject.addProperty("os", "osx"); + capabilitiesObject.addProperty("os_version", "catalina"); + capabilitiesObject.addProperty("name", "Playwright first single test"); + capabilitiesObject.addProperty("build", "playwright-java-1"); + capabilitiesObject.addProperty("browserstack.username", "BROWSERSTACK_USERNAME"); + capabilitiesObject.addProperty("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY"); + + BrowserType chromium = playwright.chromium(); + String caps = URLEncoder.encode(capabilitiesObject.toString(), "utf-8"); + String ws_endpoint = "wss://cdp.browserstack.com/playwright?caps=" + caps; + Browser browser = chromium.connect(ws_endpoint); + Page page = browser.newPage(); + try { + page.navigate("https://www.google.co.in/"); + Locator locator = page.locator("[aria-label='Search']"); + locator.click(); + page.fill("[aria-label='Search']", "BrowserStack"); + page.locator("[aria-label='Google Search'] >> nth=0").click(); + String title = page.title(); + + if (title.equals("BrowserStack - Google Search")) { + // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + markTestStatus("passed", "Title matched", page); + } else { + markTestStatus("failed", "Title did not match", page); + } + + } catch (Exception err) { + markTestStatus("failed", err.getMessage(), page); + } + browser.close(); + } catch (Exception err) { + System.out.println(err); + } + } + + public static void markTestStatus(String status, String reason, Page page) { + Object result; + result = page.evaluate("_ => {}", "browserstack_executor: { \"action\": \"setSessionStatus\", \"arguments\": { \"status\": \"" + status + "\", \"reason\": \"" + reason + "\"}}"); + } +} diff --git a/playwright-python/README.md b/playwright-python/README.md new file mode 100644 index 0000000..6337517 --- /dev/null +++ b/playwright-python/README.md @@ -0,0 +1,49 @@ +# Testing with playwright-browserstack in Python + +[Playwright](https://playwright.dev/python/) Integration with BrowserStack. + +![BrowserStack Logo](https://d98b8t1nnulk5.cloudfront.net/production/images/layout/logo-header.png?1469004780) + +## Setup + +* Clone the repo and run `cd playwright-python` +* Make sure you have Python 3 (version < 3.9.0) installed on your system +* Install Playwright + ``` + pip install --upgrade pip + pip install playwright + playwright install + ``` + +## Running your tests + +- To run a single test, run `python single-playwright-test.py` +- To run parallel tests, run `python parallel-playwright-test.py` + + ### Run sample test on privately hosted websites + **Using Language Bindings** + 1. Follow the steps below: + ``` + pip install browserstack-local + python local-using-bindings-playwright-test.py + ``` + + **Using Command-line Interface** + + 1. You have to download the BrowserStack Local binary from the links below (depending on your environment): + * [OS X (10.7 and above)](https://www.browserstack.com/browserstack-local/BrowserStackLocal-darwin-x64.zip) + * [Linux 32-bit](https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-ia32.zip) + * [Linux 64-bit](https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-x64.zip) + * [Windows (XP and above)](https://www.browserstack.com/browserstack-local/BrowserStackLocal-win32.zip) + 2. Once you have downloaded and unzipped the file, you can initiate the binary by running the command: `./BrowserStackLocal --key YOUR_ACCESS_KEY` + 3. Once you see the terminal say "[SUCCESS]" You can now access your local server(s) in our remote browser”, your local testing connection is considered established. + 4. You can then run the sample Local test using `python local-playwright-test.py` + +Understand how many parallel sessions you need by using our [Parallel Test Calculator](https://www.browserstack.com/automate/parallel-calculator?ref=github) + + +## Notes +* You can view your test results on the [BrowserStack Automate dashboard](https://www.browserstack.com/automate) + +## Additional Resources +* [Documentation for writing Automate test scripts with BrowserStack](https://www.browserstack.com/docs/automate/playwright) diff --git a/playwright-python/local-playwright-test.py b/playwright-python/local-playwright-test.py new file mode 100644 index 0000000..5f8c66f --- /dev/null +++ b/playwright-python/local-playwright-test.py @@ -0,0 +1,47 @@ +import json +import urllib +import subprocess +from playwright.sync_api import sync_playwright + +desired_cap = { + 'browser': 'chrome', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'browser_version': 'latest', # this capability is valid only for branded `chrome` and `edge` browsers and you can specify any browser version like `latest`, `latest-beta`, `latest-1` and so on. + 'os': 'osx', + 'os_version': 'catalina', + 'name': 'Branded Google Chrome on Catalina', + 'build': 'playwright-python-3', + 'browserstack.local': 'true', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +} + +def run_local_session(): + clientPlaywrightVersion = str(subprocess.getoutput('playwright --version')).strip().split(" ")[1] + desired_cap['client.playwrightVersion'] = clientPlaywrightVersion + + cdpUrl = 'wss://cdp.browserstack.com/playwright?caps=' + urllib.parse.quote(json.dumps(desired_cap)) + browser = playwright.chromium.connect(cdpUrl) + page = browser.new_page() + try: + page.goto("https://www.google.co.in/") + page.fill("[aria-label='Search']", 'Browserstack') + locator = page.locator("[aria-label='Google Search'] >> nth=0") + locator.click() + title = page.title() + + if title == "Browserstack - Google Search": + # following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + mark_test_status("passed", "Title matched", page) + else: + mark_test_status("failed", "Title did not match", page) + + except Exception as err: + mark_test_status("failed", str(err), page) + + browser.close() + +def mark_test_status(status, reason, page): + page.evaluate("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+ status + "\", \"reason\": \"" + reason + "\"}}"); + +with sync_playwright() as playwright: + run_local_session(playwright) diff --git a/playwright-python/local-using-bindings-playwright-test.py b/playwright-python/local-using-bindings-playwright-test.py new file mode 100644 index 0000000..edb7119 --- /dev/null +++ b/playwright-python/local-using-bindings-playwright-test.py @@ -0,0 +1,62 @@ +import json +import urllib +import subprocess +from playwright.sync_api import sync_playwright +from browserstack.local import Local + +desired_cap = { + 'browser': 'chrome', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'browser_version': 'latest', # this capability is valid only for branded `chrome` and `edge` browsers and you can specify any browser version like `latest`, `latest-beta`, `latest-1` and so on. + 'os': 'osx', + 'os_version': 'catalina', + 'name': 'Branded Google Chrome on Catalina', + 'build': 'playwright-python-3', + 'browserstack.local': 'true', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +} + +def run_local_session(playwright): + # Creates an instance of Local + bs_local = Local() + + # You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY". + bs_local_args = { "key": "BROWSERSTACK_ACCESS_KEY" } + + # Starts the Local instance with the required arguments + bs_local.start(**bs_local_args) + + # Check if BrowserStack local instance is running + print("BrowserStackLocal running: " + bs_local.isRunning()) + + clientPlaywrightVersion = str(subprocess.getoutput('playwright --version')).strip().split(" ")[1] + desired_cap['client.playwrightVersion'] = clientPlaywrightVersion + + cdpUrl = 'wss://cdp.browserstack.com/playwright?caps=' + urllib.parse.quote(json.dumps(desired_cap)) + browser = playwright.chromium.connect(cdpUrl) + page = browser.new_page() + try: + page.goto("https://www.google.co.in/") + page.fill("[aria-label='Search']", 'Browserstack') + locator = page.locator("[aria-label='Google Search'] >> nth=0") + locator.click() + title = page.title() + + if title == "Browserstack - Google Search": + # following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + mark_test_status("passed", "Title matched", page) + else: + mark_test_status("failed", "Title did not match", page) + except Exception as err: + mark_test_status("failed", str(err), page) + + browser.close() + + # Stop the Local instance + bs_local.stop() + +def mark_test_status(status, reason, page): + page.evaluate("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+ status + "\", \"reason\": \"" + reason + "\"}}"); + +with sync_playwright() as playwright: + run_local_session(playwright) diff --git a/playwright-python/parallel-playwright-test.py b/playwright-python/parallel-playwright-test.py new file mode 100644 index 0000000..1532182 --- /dev/null +++ b/playwright-python/parallel-playwright-test.py @@ -0,0 +1,94 @@ +import json +import subprocess +import urllib +from threading import Thread +from playwright.sync_api import sync_playwright + +desired_cap = [ +{ + 'browser': 'chrome', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'browser_version': 'latest', # this capability is valid only for branded `chrome` and `edge` browsers and you can specify any browser version like `latest`, `latest-beta`, `latest-1` and so on. + 'os': 'osx', + 'os_version': 'catalina', + 'name': 'Branded Google Chrome on Catalina', + 'build': 'playwright-python-2', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +}, +{ + 'browser': 'edge', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'browser_version': 'latest', # this capability is valid only for branded `chrome` and `edge` browsers and you can specify any browser version like `latest`, `latest-beta`, `latest-1` and so on. + 'os': 'osx', + 'os_version': 'catalina', + 'name': 'Branded Microsoft Edge on Catalina', + 'build': 'playwright-python-2', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +}, +{ + 'browser': 'playwright-firefox', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'os': 'osx', + 'os_version': 'catalina', + 'name': 'Playwright firefox on Catalina', + 'build': 'playwright-python-2', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +}, +{ + 'browser': 'playwright-webkit', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'os': 'osx', + 'os_version': 'catalina', + 'name': 'Playwright webkit on Catalina', + 'build': 'playwright-python-2', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +}, +{ + 'browser': 'playwright-chromium', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'os': 'osx', + 'os_version': 'Catalina', + 'name': 'Chrome on Win10', + 'build': 'playwright-python-2', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +}] + +def run_parallel_session(desired_cap): + with sync_playwright() as playwright: + clientPlaywrightVersion = str(subprocess.getoutput('playwright --version')).strip().split(" ")[1] + desired_cap['client.playwrightVersion'] = clientPlaywrightVersion + + cdpUrl = 'wss://cdp.browserstack.com/playwright?caps=' + urllib.parse.quote(json.dumps(desired_cap)) + browser = playwright.chromium.connect(cdpUrl) + page = browser.new_page() + try: + page.goto("https://www.google.co.in/") + page.fill("[aria-label='Search']", 'Browserstack') + locator = page.locator("[aria-label='Google Search'] >> nth=0") + locator.click() + title = page.title() + + if title == "Browserstack - Google Search": + # following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + mark_test_status("passed", "Title matched", page) + else: + mark_test_status("failed", "Title did not match", page) + + except Exception as err: + mark_test_status("failed", str(err), page) + + browser.close() + +def mark_test_status(status, reason, page): + page.evaluate("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+ status + "\", \"reason\": \"" + reason + "\"}}"); + +threads = [] +for cap in desired_cap: + combination_thread = Thread(target=run_parallel_session, args=(cap,)) + threads.append(combination_thread) + combination_thread.start() + +for thread in threads: + thread.join() + + diff --git a/playwright-python/playwright-test-on-iphone.py b/playwright-python/playwright-test-on-iphone.py new file mode 100644 index 0000000..44c6d82 --- /dev/null +++ b/playwright-python/playwright-test-on-iphone.py @@ -0,0 +1,46 @@ +import json +import urllib +import subprocess +from playwright.sync_api import sync_playwright + +desired_cap = { + 'browser': 'playwright-chromium', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'browser_version': 'latest', # this capability is valid only for branded `chrome` and `edge` browsers and you can specify any browser version like `latest`, `latest-beta`, `latest-1` and so on. + 'name': 'Test on Playwright emulated iPhone 11 Pro', + 'build': 'playwright-python-4', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +} + +def run_session(playwright): + clientPlaywrightVersion = str(subprocess.getoutput('playwright --version')).strip().split(" ")[1] + desired_cap['client.playwrightVersion'] = clientPlaywrightVersion + + cdpUrl = 'wss://cdp.browserstack.com/playwright?caps=' + urllib.parse.quote(json.dumps(desired_cap)) + iphone = playwright.devices["iPhone 11 Pro"] # Complete list of devices - https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json + browser = playwright.chromium.connect(cdpUrl) + context = browser.new_context(**iphone) + page = context.new_page() + try: + page.goto("https://www.google.co.in/") + page.fill("[aria-label='Search']", 'Browserstack') + page.keyboard.press('Enter') + page.wait_for_timeout(1000) + title = page.title() + + if title == "Browserstack - Google Search": + # following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + mark_test_status("passed", "Title matched", page) + else: + mark_test_status("failed", "Title did not match", page) + except Exception as err: + mark_test_status("failed", str(err), page) + + browser.close() + +def mark_test_status(status, reason, page): + page.evaluate("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+ status + "\", \"reason\": \"" + reason + "\"}}"); + +with sync_playwright() as playwright: + run_session(playwright) + diff --git a/playwright-python/playwright-test-on-pixel.py b/playwright-python/playwright-test-on-pixel.py new file mode 100644 index 0000000..ce115df --- /dev/null +++ b/playwright-python/playwright-test-on-pixel.py @@ -0,0 +1,46 @@ +import json +import urllib +import subprocess +from playwright.sync_api import sync_playwright + +desired_cap = { + 'browser': 'playwright-chromium', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'browser_version': 'latest', # this capability is valid only for branded `chrome` and `edge` browsers and you can specify any browser version like `latest`, `latest-beta`, `latest-1` and so on. + 'name': 'Test on Playwright emulated Pixel 5', + 'build': 'playwright-python-4', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +} + +def run_session(playwright): + clientPlaywrightVersion = str(subprocess.getoutput('playwright --version')).strip().split(" ")[1] + desired_cap['client.playwrightVersion'] = clientPlaywrightVersion + + cdpUrl = 'wss://cdp.browserstack.com/playwright?caps=' + urllib.parse.quote(json.dumps(desired_cap)) + pixel = playwright.devices["Pixel 5"] # // Complete list of devices - https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json + browser = playwright.chromium.connect(cdpUrl) + context = browser.new_context(**pixel) + page = context.new_page() + try: + page.goto("https://www.google.co.in/") + page.fill("[aria-label='Search']", 'Browserstack') + page.keyboard.press('Enter') + page.wait_for_timeout(1000) + title = page.title() + + if title == "Browserstack - Google Search": + # following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + mark_test_status("passed", "Title matched", page) + else: + mark_test_status("failed", "Title did not match", page) + except Exception as err: + mark_test_status("failed", str(err), page) + + browser.close() + +def mark_test_status(status, reason, page): + page.evaluate("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+ status + "\", \"reason\": \"" + reason + "\"}}"); + +with sync_playwright() as playwright: + run_session(playwright) + diff --git a/playwright-python/playwright-test.py b/playwright-python/playwright-test.py new file mode 100644 index 0000000..a203139 --- /dev/null +++ b/playwright-python/playwright-test.py @@ -0,0 +1,45 @@ +import json +import urllib +import subprocess +from playwright.sync_api import sync_playwright + +desired_cap = { + 'browser': 'chrome', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit` + 'browser_version': 'latest', # this capability is valid only for branded `chrome` and `edge` browsers and you can specify any browser version like `latest`, `latest-beta`, `latest-1` and so on. + 'os': 'osx', + 'os_version': 'catalina', + 'name': 'Branded Google Chrome on Catalina', + 'build': 'playwright-python-1', + 'browserstack.username': 'BROWSERSTACK_USERNAME', + 'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY' +} + +def run_session(playwright): + clientPlaywrightVersion = str(subprocess.getoutput('playwright --version')).strip().split(" ")[1] + desired_cap['client.playwrightVersion'] = clientPlaywrightVersion + + cdpUrl = 'wss://cdp.browserstack.com/playwright?caps=' + urllib.parse.quote(json.dumps(desired_cap)) + browser = playwright.chromium.connect(cdpUrl) + page = browser.new_page() + try: + page.goto("https://www.google.co.in/") + page.fill("[aria-label='Search']", 'Browserstack') + locator = page.locator("[aria-label='Google Search'] >> nth=0") + locator.click() + title = page.title() + + if title == "Browserstack - Google Search": + # following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test + mark_test_status("passed", "Title matched", page) + else: + mark_test_status("failed", "Title did not match", page) + except Exception as err: + mark_test_status("failed", str(err), page) + + browser.close() + +def mark_test_status(status, reason, page): + page.evaluate("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+ status + "\", \"reason\": \"" + reason + "\"}}"); + +with sync_playwright() as playwright: + run_session(playwright)