Skip to content

Commit f57156a

Browse files
kamal-kaur04francisf
authored andcommitted
added get session details sample scripts
1 parent 4c7d631 commit f57156a

File tree

7 files changed

+200
-0
lines changed

7 files changed

+200
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
using Microsoft.Playwright;
2+
using System.Threading.Tasks;
3+
using System;
4+
using System.Collections.Generic;
5+
using Newtonsoft.Json;
6+
using Newtonsoft.Json.Linq;
7+
8+
9+
class PlaywrightSessionDetailsTest
10+
{
11+
public static async Task main(string[] args)
12+
{
13+
using var playwright = await Playwright.CreateAsync();
14+
15+
Dictionary<string, string> browserstackOptions = new Dictionary<string, string>();
16+
browserstackOptions.Add("name", "Playwright first sample test");
17+
browserstackOptions.Add("build", "playwright-dotnet-5");
18+
browserstackOptions.Add("os", "osx");
19+
browserstackOptions.Add("os_version", "catalina");
20+
browserstackOptions.Add("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`
21+
browserstackOptions.Add("browserstack.username", "BROWSERSTACK_USERNAME");
22+
browserstackOptions.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY");
23+
string capsJson = JsonConvert.SerializeObject(browserstackOptions);
24+
string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capsJson);
25+
26+
await using var browser = await playwright.Chromium.ConnectAsync(cdpUrl);
27+
var page = await browser.NewPageAsync();
28+
try {
29+
await page.GotoAsync("https://www.google.co.in/");
30+
await page.Locator("[aria-label='Search']").ClickAsync();
31+
await page.FillAsync("[aria-label='Search']", "BrowserStack");
32+
await page.Locator("[aria-label='Google Search'] >> nth=0").ClickAsync();
33+
var title = await page.TitleAsync();
34+
35+
if (title == "BrowserStack - Google Search")
36+
{
37+
// 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
38+
await MarkTestStatus("passed", "Title matched", page);
39+
} else
40+
{
41+
await MarkTestStatus("failed", "Title did not match", page);
42+
}
43+
}
44+
catch (Exception err) {
45+
await MarkTestStatus("failed", err.Message, page);
46+
}
47+
Object sessionObject = await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\":\"getSessionDetails\"}");
48+
Console.WriteLine(sessionObject);
49+
50+
// convert Object to String for parsing
51+
string? json_resp = Convert.ToString(sessionObject);
52+
53+
// parse the data
54+
if (json_resp != null)
55+
{
56+
var session_details = JObject.Parse(json_resp);
57+
58+
// print the session ID on IDE's console
59+
Console.WriteLine(session_details["hashed_id"]);
60+
}
61+
62+
await browser.CloseAsync();
63+
}
64+
65+
public static async Task MarkTestStatus(string status, string reason, IPage page) {
66+
await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}");
67+
}
68+
}

playwright-dotnet/Program.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ public static async Task Main(string[] args)
2929
Console.WriteLine("Running Pixel Test");
3030
await PlaywrightPixelTest.main(args);
3131
break;
32+
case "sessiondetails":
33+
Console.WriteLine("Getting Session Details Test");
34+
await PlaywrightSessionDetailsTest.main(args);
35+
break;
3236
default:
3337
Console.WriteLine("Running Single Test by default");
3438
await PlaywrightTest.main(args);

playwright-dotnet/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@
1313

1414
- To run a single test, run `dotnet run single`
1515
- To run a parallel test, run command `dotnet run parallel`
16+
- To run sessions on emulated devices,
17+
`dotnet run iphonetest` or `dotnet run pixeltest`
18+
You can specify any device name from thr below list:
19+
https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json
20+
- Run `dotnet run sessiondetails` to check how to get session details.
1621

1722
### Run sample test on privately hosted websites
1823

playwright-java/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
- To run parallel tests, run
1717
`mvn -Dexec.mainClass="com.browserstack.PlaywrightParallelTest" -Dexec.classpathScope=test test-compile exec:java
1818
`
19+
- Run `mvn -Dexec.mainClass="com.browserstack.PlaywrightSessionDetailsTest" -Dexec.classpathScope=test test-compile exec:java` to check how to get session details.
1920

2021
### Run sample test on privately hosted websites
2122

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.browserstack;
2+
3+
import com.google.gson.JsonObject;
4+
import com.microsoft.playwright.*;
5+
import com.google.gson.JsonParser;
6+
7+
import java.net.URLEncoder;
8+
9+
public class PlaywrightSessionDetailsTest {
10+
public static void main(String[] args) {
11+
try (Playwright playwright = Playwright.create()) {
12+
JsonObject capabilitiesObject = new JsonObject();
13+
capabilitiesObject.addProperty("browser", "chrome"); // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`
14+
capabilitiesObject.addProperty("browser_version", "latest");
15+
capabilitiesObject.addProperty("os", "osx");
16+
capabilitiesObject.addProperty("os_version", "catalina");
17+
capabilitiesObject.addProperty("name", "Playwright first single test");
18+
capabilitiesObject.addProperty("build", "playwright-java-5");
19+
capabilitiesObject.addProperty("browserstack.username", "BROWSERSTACK_USERNAME");
20+
capabilitiesObject.addProperty("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY");
21+
22+
BrowserType chromium = playwright.chromium();
23+
String caps = URLEncoder.encode(capabilitiesObject.toString(), "utf-8");
24+
String ws_endpoint = "wss://cdp.browserstack.com/playwright?caps=" + caps;
25+
Browser browser = chromium.connect(ws_endpoint);
26+
Page page = browser.newPage();
27+
try {
28+
page.navigate("https://www.google.co.in/");
29+
Locator locator = page.locator("[aria-label='Search']");
30+
locator.click();
31+
page.fill("[aria-label='Search']", "BrowserStack");
32+
page.locator("[aria-label='Google Search'] >> nth=0").click();
33+
String title = page.title();
34+
35+
if (title.equals("BrowserStack - Google Search")) {
36+
// 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
37+
markTestStatus("passed", "Title matched", page);
38+
} else {
39+
markTestStatus("failed", "Title did not match", page);
40+
}
41+
42+
// store the JSON response in the Object class
43+
Object response = page.evaluate("_ => {}", "browserstack_executor: {\"action\": \"getSessionDetails\"}");
44+
System.out.println(response);
45+
46+
// parse the JSON response
47+
JsonObject json = JsonParser.parseString((String) response).getAsJsonObject();
48+
49+
// store session ID in a variable
50+
String sessionID = String.valueOf(json.get("hashed_id"));
51+
52+
// print session ID in your IDE's console
53+
System.out.println(sessionID);
54+
} catch (Exception err) {
55+
markTestStatus("failed", err.getMessage(), page);
56+
}
57+
browser.close();
58+
} catch (Exception err) {
59+
System.out.println(err);
60+
}
61+
}
62+
public static void markTestStatus(String status, String reason, Page page) {
63+
Object result;
64+
result = page.evaluate("_ => {}", "browserstack_executor: { \"action\": \"setSessionStatus\", \"arguments\": { \"status\": \"" + status + "\", \"reason\": \"" + reason + "\"}}");
65+
}
66+
}

playwright-python/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@
1919

2020
- To run a single test, run `python single-playwright-test.py`
2121
- To run parallel tests, run `python parallel-playwright-test.py`
22+
- To run sessions on emulated devices,
23+
`python playwright-test-on-iphone.py` or `python playwright-test-on-pixel.py`
24+
You can specify any device name from thr below list:
25+
https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json
26+
- Run `python session-details-playwright-test.py` to check how to get session details.
2227

2328
### Run sample test on privately hosted websites
2429
**Using Language Bindings**
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import json
2+
import urllib
3+
from playwright.sync_api import sync_playwright
4+
5+
desired_cap = {
6+
'browser': 'chrome', # allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`
7+
'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.
8+
'os': 'osx',
9+
'os_version': 'catalina',
10+
'name': 'Branded Google Chrome on Catalina',
11+
'build': 'playwright-python-5',
12+
'browserstack.username': 'BROWSERSTACK_USERNAME',
13+
'browserstack.accessKey': 'BROWSERSTACK_ACCESS_KEY'
14+
}
15+
16+
def run_session(playwright):
17+
cdpUrl = 'wss://cdp.browserstack.com/playwright?caps=' + urllib.parse.quote(json.dumps(desired_cap))
18+
browser = playwright.chromium.connect(cdpUrl)
19+
page = browser.new_page()
20+
try:
21+
page.goto("https://www.google.co.in/")
22+
page.fill("[aria-label='Search']", 'Browserstack')
23+
locator = page.locator("[aria-label='Google Search'] >> nth=0")
24+
locator.click()
25+
title = page.title()
26+
27+
if title == "Browserstack - Google Search":
28+
# 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
29+
mark_test_status("passed", "Title matched", page)
30+
else:
31+
mark_test_status("failed", "Title did not match", page)
32+
except Exception as err:
33+
mark_test_status("failed", str(err), page)
34+
35+
# get details of the session
36+
response = page.evaluate("_=> {}", 'browserstack_executor: {"action": "getSessionDetails"}')
37+
print(response)
38+
39+
jsonResponse = json.loads(response)
40+
41+
# print the session ID in the IDE's console
42+
print(jsonResponse["hashed_id"])
43+
44+
browser.close()
45+
46+
def mark_test_status(status, reason, page):
47+
page.evaluate("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+ status + "\", \"reason\": \"" + reason + "\"}}");
48+
49+
with sync_playwright() as playwright:
50+
run_session(playwright)
51+

0 commit comments

Comments
 (0)