Skip to content

Commit 9aa2024

Browse files
authored
Merge pull request #7 from himanshu-02/now-optimisations-ps-proxy
PR for proxy checker & code review suggestions
2 parents 9d3a223 + d97a918 commit 9aa2024

File tree

2 files changed

+182
-62
lines changed

2 files changed

+182
-62
lines changed

win/proxy-check.ps1

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
#requires -version 5.0
2+
<#
3+
BrowserStack Proxy Detection and Validation
4+
- Detects proxy from environment variables
5+
- Tests BrowserStack API connectivity through proxy
6+
- Exports PROXY_HOST and PROXY_PORT if successful
7+
#>
8+
9+
param(
10+
[string]$BrowserStackUsername,
11+
[string]$BrowserStackAccessKey
12+
)
13+
14+
$ErrorActionPreference = 'Continue'
15+
16+
# Test URL for connectivity check
17+
$TEST_URL = "https://www.browserstack.com/automate/browsers.json"
18+
19+
# Function to parse proxy URL
20+
function Parse-ProxyUrl {
21+
param([string]$ProxyUrl)
22+
23+
if ([string]::IsNullOrWhiteSpace($ProxyUrl)) {
24+
return $null
25+
}
26+
27+
# Remove protocol (http:// or https://)
28+
$cleaned = $ProxyUrl -replace '^https?://', ''
29+
30+
# Remove credentials if present (user:pass@)
31+
if ($cleaned -match '@') {
32+
$cleaned = $cleaned.Substring($cleaned.IndexOf('@') + 1)
33+
}
34+
35+
# Extract host and port
36+
if ($cleaned -match '^([^:]+):(\d+)') {
37+
return @{
38+
Host = $matches[1]
39+
Port = $matches[2]
40+
}
41+
} elseif ($cleaned -match '^([^:]+)') {
42+
# No port specified, use default
43+
return @{
44+
Host = $matches[1]
45+
Port = "8080" # default proxy port
46+
}
47+
}
48+
49+
return $null
50+
}
51+
52+
# Detect proxy from environment variables (case-insensitive)
53+
$PROXY = $env:http_proxy
54+
if ([string]::IsNullOrWhiteSpace($PROXY)) { $PROXY = $env:HTTP_PROXY }
55+
if ([string]::IsNullOrWhiteSpace($PROXY)) { $PROXY = $env:https_proxy }
56+
if ([string]::IsNullOrWhiteSpace($PROXY)) { $PROXY = $env:HTTPS_PROXY }
57+
58+
# Reset output variables
59+
$env:PROXY_HOST = ""
60+
$env:PROXY_PORT = ""
61+
62+
# If no proxy configured, exit early
63+
if ([string]::IsNullOrWhiteSpace($PROXY)) {
64+
Write-Host "No proxy found in environment. Clearing proxy host and port variables."
65+
$env:PROXY_HOST = ""
66+
$env:PROXY_PORT = ""
67+
exit 0
68+
}
69+
70+
Write-Host "Proxy detected: $PROXY"
71+
72+
# Parse proxy URL
73+
$proxyInfo = Parse-ProxyUrl -ProxyUrl $PROXY
74+
if (-not $proxyInfo) {
75+
Write-Host "❌ Failed to parse proxy URL: $PROXY"
76+
$env:PROXY_HOST = ""
77+
$env:PROXY_PORT = ""
78+
exit 1
79+
}
80+
81+
Write-Host "Testing reachability via proxy..."
82+
Write-Host " Proxy Host: $($proxyInfo.Host)"
83+
Write-Host " Proxy Port: $($proxyInfo.Port)"
84+
85+
# Encode BrowserStack credentials in Base64
86+
$base64Creds = ""
87+
if (-not [string]::IsNullOrWhiteSpace($BrowserStackUsername) -and
88+
-not [string]::IsNullOrWhiteSpace($BrowserStackAccessKey)) {
89+
$pair = "${BrowserStackUsername}:${BrowserStackAccessKey}"
90+
$bytes = [System.Text.Encoding]::UTF8.GetBytes($pair)
91+
$base64Creds = [System.Convert]::ToBase64String($bytes)
92+
}
93+
94+
# Test connectivity through proxy
95+
try {
96+
$proxyUri = "http://$($proxyInfo.Host):$($proxyInfo.Port)"
97+
98+
# Create web request with proxy
99+
$webProxy = New-Object System.Net.WebProxy($proxyUri)
100+
$webClient = New-Object System.Net.WebClient
101+
$webClient.Proxy = $webProxy
102+
103+
# Add authorization header if credentials provided
104+
if (-not [string]::IsNullOrWhiteSpace($base64Creds)) {
105+
$webClient.Headers.Add("Authorization", "Basic $base64Creds")
106+
}
107+
108+
# Attempt to download (with timeout)
109+
$null = $webClient.DownloadString($TEST_URL)
110+
111+
# If we reach here, the request succeeded
112+
Write-Host "✅ Reachable. HTTP 200"
113+
Write-Host "Exporting PROXY_HOST=$($proxyInfo.Host)"
114+
Write-Host "Exporting PROXY_PORT=$($proxyInfo.Port)"
115+
116+
$env:PROXY_HOST = $proxyInfo.Host
117+
$env:PROXY_PORT = $proxyInfo.Port
118+
119+
exit 0
120+
121+
} catch {
122+
$statusCode = "Unknown"
123+
if ($_.Exception.InnerException -and $_.Exception.InnerException.Response) {
124+
$statusCode = [int]$_.Exception.InnerException.Response.StatusCode
125+
}
126+
127+
Write-Host "❌ Not reachable (HTTP $statusCode). Clearing variables."
128+
Write-Host " Error: $($_.Exception.Message)"
129+
130+
$env:PROXY_HOST = ""
131+
$env:PROXY_PORT = ""
132+
133+
exit 0 # Exit successfully even if proxy check fails
134+
}
135+

win/run.ps1

Lines changed: 47 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,8 @@ $WEB_PLATFORM_TEMPLATES = @(
6464
"Windows|11|Edge",
6565
"Windows|11|Chrome",
6666
"Windows|8|Chrome",
67-
#"OS X|Monterey|Safari",
6867
"OS X|Monterey|Chrome",
6968
"OS X|Ventura|Chrome",
70-
#"OS X|Big Sur|Safari",
7169
"OS X|Catalina|Firefox"
7270
)
7371

@@ -1076,17 +1074,6 @@ function Setup-Web-Java {
10761074

10771075
Push-Location $TARGET
10781076
try {
1079-
# Update Base URL
1080-
$files = Get-ChildItem -Path $TARGET -Recurse -Filter *.* -File | Where-Object { $_.Extension -match '\.(java|xml|properties)$' }
1081-
foreach ($file in $files) {
1082-
$content = Get-Content $file.FullName -Raw -ErrorAction SilentlyContinue
1083-
if ($content -and $content -match "https://www\.bstackdemo\.com") {
1084-
$content = $content -replace "https://www\.bstackdemo\.com", $CX_TEST_URL
1085-
Set-ContentNoBom -Path $file.FullName -Value $content
1086-
Log-Line "🌐 Updated base URL in $($file.Name)" $GLOBAL_LOG
1087-
}
1088-
}
1089-
10901077
# Check if domain is private
10911078
if (Test-DomainPrivate) {
10921079
$UseLocal = $true
@@ -1197,16 +1184,6 @@ parallelsPerPlatform: $ParallelsPerPlatform
11971184

11981185
Log-Line "✅ Updated root-level browserstack.yml with platforms and credentials" $GLOBAL_LOG
11991186

1200-
# Update base URL in test file
1201-
$testFile = "tests\bstack-sample-test.py"
1202-
$testFileFull = Join-Path $TARGET $testFile
1203-
if (Test-Path $testFileFull) {
1204-
$c = [System.IO.File]::ReadAllText($testFileFull)
1205-
$c = $c.Replace("https://bstackdemo.com", $CX_TEST_URL)
1206-
Set-ContentNoBom -Path $testFileFull -Value $c
1207-
Log-Line "🌐 Updated base URL in tests/bstack-sample-test.py to: $CX_TEST_URL" $GLOBAL_LOG
1208-
}
1209-
12101187
$sdk = Join-Path $venv "Scripts\browserstack-sdk.exe"
12111188
Log-Line "🚀 Running 'browserstack-sdk pytest -s tests/bstack-sample-test.py'. This could take a few minutes. Follow the Automation build here: https://automation.browserstack.com/" $GLOBAL_LOG
12121189
[void](Invoke-External -Exe $sdk -Arguments @('pytest','-s','tests/bstack-sample-test.py') -LogFile $LogFile -WorkingDirectory $TARGET)
@@ -1259,7 +1236,9 @@ function Setup-Web-NodeJS {
12591236

12601237
$env:BROWSERSTACK_USERNAME = $BROWSERSTACK_USERNAME
12611238
$env:BROWSERSTACK_ACCESS_KEY = $BROWSERSTACK_ACCESS_KEY
1262-
$env:BROWSERSTACK_LOCAL = if ($UseLocal) { "true" } else { "false" }
1239+
$localFlagStr = if ($UseLocal) { "true" } else { "false" }
1240+
$env:BROWSERSTACK_LOCAL = $localFlagStr
1241+
$env:BSTACK_PARALLELS = $ParallelsPerPlatform
12631242

12641243
Log-Line "🚀 Running 'npm run test'" $GLOBAL_LOG
12651244
[void](Invoke-External -Exe "cmd.exe" -Arguments @("/c","npm","run","test") -LogFile $LogFile -WorkingDirectory $TARGET)
@@ -1422,7 +1401,7 @@ class TestUniversalAppCheck:
14221401
function Setup-Mobile-Java {
14231402
param([bool]$UseLocal, [int]$ParallelsPerPlatform, [string]$LogFile)
14241403

1425-
$REPO = "browserstack-examples-appium-testng"
1404+
$REPO = "now-testng-appium-app-browserstack"
14261405
$TARGET = Join-Path $GLOBAL_DIR $REPO
14271406

14281407
New-Item -ItemType Directory -Path $GLOBAL_DIR -Force | Out-Null
@@ -1433,47 +1412,30 @@ function Setup-Mobile-Java {
14331412
Invoke-GitClone -Url "https://github.com/BrowserStackCE/$REPO.git" -Target $TARGET -LogFile $MOBILE_LOG
14341413
Log-Line "✅ Cloned repository: $REPO into $TARGET" $GLOBAL_LOG
14351414

1436-
# Update pom.xml sdk version to LATEST (matches mac script)
1437-
$pom = Join-Path $TARGET "pom.xml"
1438-
if (Test-Path $pom) {
1439-
$pomContent = Get-Content $pom -Raw
1440-
$pomContent = $pomContent -replace '(?s)(<artifactId>browserstack-java-sdk</artifactId>.*?<version>)(.*?)(</version>)', '$1LATEST$3'
1441-
$pomContent | Set-Content $pom
1442-
Log-Line "🔧 Updated browserstack-java-sdk version to LATEST in pom.xml" $GLOBAL_LOG
1443-
}
1444-
14451415
Push-Location $TARGET
14461416
try {
1417+
# Navigate to platform-specific directory
1418+
if ($APP_PLATFORM -eq "all" -or $APP_PLATFORM -eq "android") {
1419+
Set-Location "android\testng-examples"
1420+
} else {
1421+
Set-Location "ios\testng-examples"
1422+
}
1423+
14471424
$env:BROWSERSTACK_USERNAME = $BROWSERSTACK_USERNAME
14481425
$env:BROWSERSTACK_ACCESS_KEY = $BROWSERSTACK_ACCESS_KEY
14491426

1450-
# Update driver init to AndroidDriver (parity with bash)
1451-
$testBase = Get-ChildItem -Path "src" -Recurse -Filter "TestBase.java" -ErrorAction SilentlyContinue | Select-Object -First 1
1452-
if ($testBase) {
1453-
(Get-Content $testBase.FullName -Raw) -replace 'new AppiumDriver\(', 'new AndroidDriver(' | Set-Content $testBase.FullName
1454-
Log-Line "🔧 Updated driver initialization in $($testBase.FullName) to use AndroidDriver" $GLOBAL_LOG
1455-
}
1456-
1457-
$env:BROWSERSTACK_CONFIG_FILE = "src/test/resources/conf/capabilities/browserstack-parallel.yml"
1427+
# YAML config path
1428+
$env:BROWSERSTACK_CONFIG_FILE = ".\browserstack.yml"
14581429
$platforms = Generate-Mobile-Platforms-Yaml -MaxTotalParallels $TEAM_PARALLELS_MAX_ALLOWED_MOBILE
14591430
$localFlag = if ($UseLocal) { "true" } else { "false" }
14601431

1461-
@"
1462-
userName: $BROWSERSTACK_USERNAME
1463-
accessKey: $BROWSERSTACK_ACCESS_KEY
1464-
framework: testng
1465-
browserstackLocal: $localFlag
1466-
buildName: browserstack-build-mobile
1467-
projectName: NOW-Mobile-Test
1468-
parallelsPerPlatform: $ParallelsPerPlatform
1469-
accessibility: true
1470-
percy: true
1432+
# Append to existing YAML (repo has base config)
1433+
$yamlAppend = @"
14711434
app: $APP_URL
14721435
platforms:
14731436
$platforms
1474-
"@ | Set-Content $env:BROWSERSTACK_CONFIG_FILE
1475-
1476-
Log-Line "✅ Updated $env:BROWSERSTACK_CONFIG_FILE with platforms and credentials" $GLOBAL_LOG
1437+
"@
1438+
Add-Content -Path $env:BROWSERSTACK_CONFIG_FILE -Value $yamlAppend
14771439

14781440
# Check if domain is private
14791441
if (Test-DomainPrivate) {
@@ -1487,12 +1449,16 @@ $platforms
14871449
Log-Line "✅ BrowserStack Local is DISABLED for this run." $GLOBAL_LOG
14881450
}
14891451

1490-
$mvn = Get-MavenCommand -RepoDir $TARGET
1491-
Log-Line "⚙️ Running '$mvn install -DskipTests'" $GLOBAL_LOG
1492-
[void](Invoke-External -Exe $mvn -Arguments @("install","-DskipTests") -LogFile $LogFile -WorkingDirectory $TARGET)
1452+
$mvn = Get-MavenCommand -RepoDir (Get-Location).Path
1453+
Log-Line "⚙️ Running '$mvn clean'" $GLOBAL_LOG
1454+
$cleanExit = Invoke-External -Exe $mvn -Arguments @("clean") -LogFile $LogFile -WorkingDirectory (Get-Location).Path
1455+
if ($cleanExit -ne 0) {
1456+
Log-Line "❌ 'mvn clean' FAILED. See $LogFile for details." $GLOBAL_LOG
1457+
throw "Maven clean failed"
1458+
}
14931459

1494-
Log-Line "🚀 Running '$mvn clean test -P bstack-parallel -Dtest=OrderTest'" $GLOBAL_LOG
1495-
[void](Invoke-External -Exe $mvn -Arguments @("clean","test","-P","bstack-parallel","-Dtest=OrderTest") -LogFile $LogFile -WorkingDirectory $TARGET)
1460+
Log-Line "🚀 Running '$mvn test -P sample-test'. This could take a few minutes. Follow the Automation build here: https://automation.browserstack.com/" $GLOBAL_LOG
1461+
[void](Invoke-External -Exe $mvn -Arguments @("test","-P","sample-test") -LogFile $LogFile -WorkingDirectory (Get-Location).Path)
14961462

14971463
} finally {
14981464
Pop-Location
@@ -1514,7 +1480,7 @@ function Setup-Mobile-NodeJS {
15141480
Remove-Item -Path $TARGET -Recurse -Force
15151481
}
15161482

1517-
Invoke-GitClone -Url "https://github.com/BrowserStackCE/$REPO.git" -Branch "sdk" -Target $TARGET -LogFile $MOBILE_LOG
1483+
Invoke-GitClone -Url "https://github.com/BrowserStackCE/$REPO.git" -Target $TARGET -LogFile $MOBILE_LOG
15181484

15191485
$testDir = Join-Path $TARGET "test"
15201486
Push-Location $testDir
@@ -1744,7 +1710,7 @@ function Run-Setup {
17441710
}
17451711
Log-Line "========================================" $GLOBAL_LOG
17461712
Log-Line "🎉 All requested tests have been executed!" $GLOBAL_LOG
1747-
Log-Line "🔗 View results: https://automate.browserstack.com/ (Web) | https://app-automate.browserstack.com/ (Mobile)" $GLOBAL_LOG
1713+
Log-Line "🔗 View results: https://automation.browserstack.com/" $GLOBAL_LOG
17481714
Log-Line "========================================" $GLOBAL_LOG
17491715
}
17501716

@@ -1758,6 +1724,25 @@ try {
17581724
Fetch-Plan-Details
17591725

17601726
Log-Line "Plan summary: WEB_PLAN_FETCHED=$WEB_PLAN_FETCHED (team max=$TEAM_PARALLELS_MAX_ALLOWED_WEB), MOBILE_PLAN_FETCHED=$MOBILE_PLAN_FETCHED (team max=$TEAM_PARALLELS_MAX_ALLOWED_MOBILE)" $GLOBAL_LOG
1727+
1728+
# Check for proxy configuration
1729+
Log-Line "ℹ️ Checking proxy in environment" $GLOBAL_LOG
1730+
$proxyCheckScript = Join-Path $PSScriptRoot "proxy-check.ps1"
1731+
if (Test-Path $proxyCheckScript) {
1732+
try {
1733+
& $proxyCheckScript -BrowserStackUsername $BROWSERSTACK_USERNAME -BrowserStackAccessKey $BROWSERSTACK_ACCESS_KEY
1734+
if ($env:PROXY_HOST -and $env:PROXY_PORT) {
1735+
Log-Line "✅ Proxy configured: $env:PROXY_HOST:$env:PROXY_PORT" $GLOBAL_LOG
1736+
} else {
1737+
Log-Line "ℹ️ No proxy configured or proxy check failed" $GLOBAL_LOG
1738+
}
1739+
} catch {
1740+
Log-Line "⚠️ Proxy check script failed: $($_.Exception.Message)" $GLOBAL_LOG
1741+
}
1742+
} else {
1743+
Log-Line "⚠️ Proxy check script not found at: $proxyCheckScript" $GLOBAL_LOG
1744+
}
1745+
17611746
Run-Setup
17621747
} catch {
17631748
Log-Line " " $GLOBAL_LOG

0 commit comments

Comments
 (0)