Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement dynamic port selection for all platforms #2527

Draft
wants to merge 17 commits into
base: master
Choose a base branch
from
Draft
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
3 changes: 1 addition & 2 deletions packages/patrol/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ android {

defaultConfig {
minSdk 21
buildConfigField("String", "PATROL_APP_PORT", project.hasProperty('app-server-port') ? '"' + project.getProperty('app-server-port') + '"' : '""')
buildConfigField("String", "PATROL_TEST_PORT", project.hasProperty('test-server-port') ? '"' + project.getProperty('test-server-port') + '"' : '""')
buildConfigField("String", "PATROL_TEST_SERVER_PORT", project.hasProperty('test-server-port') ? '"' + project.getProperty('test-server-port') + '"' : '""')
}

buildFeatures {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package pl.leancode.patrol;


public class AndroidServerPortProvider {
private static int serverPort;

public static void setPort(int newValue) {
serverPort = newValue;
}

public static int getPort() {
return serverPort;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package pl.leancode.patrol

import pl.leancode.patrol.contracts.Contracts
import pl.leancode.patrol.contracts.Contracts.MarkAppAppServiceReadyRequest
import pl.leancode.patrol.contracts.Contracts.TapAtRequest
import pl.leancode.patrol.contracts.Contracts.OpenUrlRequest
import pl.leancode.patrol.contracts.Contracts.ConfigureRequest
import pl.leancode.patrol.contracts.Contracts.DarkModeRequest
import pl.leancode.patrol.contracts.Contracts.EnterTextRequest
Expand Down Expand Up @@ -70,7 +72,7 @@ class AutomatorServer(private val automation: Automator) : NativeAutomatorServer
automation.openQuickSettings()
}

override fun openUrl(request: Contracts.OpenUrlRequest) {
override fun openUrl(request: OpenUrlRequest) {
automation.openUrl(request.url)
}

Expand Down Expand Up @@ -216,7 +218,7 @@ class AutomatorServer(private val automation: Automator) : NativeAutomatorServer
}
}

override fun tapAt(request: Contracts.TapAtRequest) {
override fun tapAt(request: TapAtRequest) {
automation.tapAt(
x = request.x.toFloat(),
y = request.y.toFloat()
Expand Down Expand Up @@ -328,7 +330,8 @@ class AutomatorServer(private val automation: Automator) : NativeAutomatorServer
}
}

override fun markPatrolAppServiceReady() {
override fun markPatrolAppServiceReady(request: MarkAppAppServiceReadyRequest) {
PatrolServer.appServerPort = request.port?.toInt()
PatrolServer.appReady.open()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@

public class BrowserstackPatrolJUnitRunner extends PatrolJUnitRunner {
@Override
public PatrolAppServiceClient createAppServiceClient() {
public PatrolAppServiceClient createAppServiceClient(Integer port) {
// Create client with a default constructor (localhost:8082) by default.
PatrolAppServiceClient client = new PatrolAppServiceClient();
PatrolAppServiceClient client = new PatrolAppServiceClient(port);
waitForPatrolAppService();

try {
Expand All @@ -25,7 +25,7 @@ public PatrolAppServiceClient createAppServiceClient() {
// If the client on localhost:8082 fails, let's apply the wokraround
Logger.INSTANCE.i("PatrolAppServiceClientException in createAppServiceClient " + ex.getMessage());
Logger.INSTANCE.i("LOOPBACK: " + getLoopback());
client = new PatrolAppServiceClient(getLoopback());
client = new PatrolAppServiceClient(getLoopback(), port);
}

return client;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,12 @@ class PatrolAppServiceClient {
private val timeout = 2L
private val timeUnit = TimeUnit.HOURS

private val defaultPort = 8082
val port: Int
get() {
val portStr = BuildConfig.PATROL_APP_PORT
if (portStr == null) {
Logger.i("PATROL_APP_PORT is null, falling back to default ($defaultPort)")
return defaultPort
}
return portStr.toIntOrNull() ?: run {
Logger.i("PATROL_APP_PORT is not a valid integer, falling back to default ($defaultPort)")
defaultPort
}
}

constructor() {
constructor(port: Int) {
client = Client(address = "localhost", port = port, timeout = timeout, timeUnit = timeUnit)
Logger.i("Created PatrolAppServiceClient: ${client.serverUrl}")
}

constructor(address: String) {
constructor(address: String, port: Int) {
client = Client(address = address, port = port, timeout = timeout, timeUnit = timeUnit)
Logger.i("Created PatrolAppServiceClient: ${client.serverUrl}")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,24 @@ public void setUp(Class<?> activityClass) {
// It's simpler because we don't have the need for that much synchronization.
// Currently, the only synchronization point we're interested in is when the app under test returns the list of tests.
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();


PatrolServer patrolServer = new PatrolServer();
patrolServer.start(); // Gets killed when the instrumentation process dies. We're okay with this.
Integer port = patrolServer.getPort();


Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName(instrumentation.getTargetContext(), activityClass.getCanonicalName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("patrol_server_port", port);
instrumentation.getTargetContext().startActivity(intent);

PatrolServer patrolServer = new PatrolServer();
patrolServer.start(); // Gets killed when the instrumentation process dies. We're okay with this.

patrolAppServiceClient = createAppServiceClient();
}

public PatrolAppServiceClient createAppServiceClient() {
return new PatrolAppServiceClient();
public PatrolAppServiceClient createAppServiceClient(Integer port) {
patrolAppServiceClient = new PatrolAppServiceClient(port);
return patrolAppServiceClient;
}

/**
Expand All @@ -102,6 +107,7 @@ public void waitForPatrolAppService() {
final String TAG = "PatrolJUnitRunner.setUp(): ";

Logger.INSTANCE.i(TAG + "Waiting for PatrolAppService to report its readiness...");
PatrolServer.Companion.setAppServerPort(null);
PatrolServer.Companion.getAppReady().block();

Logger.INSTANCE.i(TAG + "PatrolAppService is ready to report Dart tests");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package pl.leancode.patrol

import android.content.Intent
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

class PatrolPlugin : FlutterPlugin, MethodCallHandler {
class PatrolPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
private lateinit var channel: MethodChannel

override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
Expand All @@ -21,4 +24,16 @@ class PatrolPlugin : FlutterPlugin, MethodCallHandler {
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}

override fun onAttachedToActivity(binding: ActivityPluginBinding) {
val intent: Intent = binding.activity.intent
val serverPort = intent.getIntExtra("patrol_server_port", 0)
AndroidServerPortProvider.setPort(serverPort)
}

override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
onAttachedToActivity(binding)
}
override fun onDetachedFromActivityForConfigChanges() {}
override fun onDetachedFromActivity() {}
}
Original file line number Diff line number Diff line change
@@ -1,40 +1,31 @@
package pl.leancode.patrol

import android.os.ConditionVariable
import io.ktor.server.engine.ApplicationEngineEnvironment
import org.http4k.core.ContentType
import org.http4k.filter.ServerFilters
import org.http4k.server.Http4kServer
import org.http4k.server.KtorCIO
import org.http4k.server.asServer
import java.net.ServerSocket

class PatrolServer {
private val defaultPort = 8081

private var server: Http4kServer? = null
private var automatorServer: AutomatorServer? = null

val port: Int
get() {
val portStr = BuildConfig.PATROL_TEST_PORT
if (portStr == null) {
Logger.i("PATROL_TEST_PORT is null, falling back to default ($defaultPort)")
return defaultPort
}
return portStr.toIntOrNull() ?: run {
Logger.i("PATROL_TEST_PORT is not a valid integer, falling back to default ($defaultPort)")
defaultPort
}
}
var port: Int? = null

fun start() {
Logger.i("Starting server...")

port = BuildConfig.PATROL_TEST_SERVER_PORT.toIntOrNull() ?: getFreePort()

automatorServer = AutomatorServer(Automator.instance)

server = automatorServer!!.router
.withFilter(catcher)
.withFilter(printer)
.withFilter(ServerFilters.SetContentType(ContentType.TEXT_PLAIN))
.asServer(KtorCIO(port))
.asServer(KtorCIO(port!!))
.start()

Logger.i("Created and started PatrolServer, port: $port")
Expand All @@ -50,7 +41,11 @@ class PatrolServer {

companion object {
val appReady: ConditionVariable = ConditionVariable()
var appServerPort: Int? = null
}

private fun getFreePort() = ServerSocket(0).use { it.localPort }

}

typealias DartTestResults = Map<String, String>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
final class AutomatorServer: NativeAutomatorServer {
private let automator: Automator

private let onAppReady: (Bool) -> Void
private let onAppReady: (Bool, Int) -> Void

init(automator: Automator, onAppReady: @escaping (Bool) -> Void) {
init(automator: Automator, onAppReady: @escaping (Bool, Int) -> Void) {
self.automator = automator
self.onAppReady = onAppReady
}
Expand Down Expand Up @@ -411,8 +411,8 @@
}
}

func markPatrolAppServiceReady() throws {
onAppReady(true)
func markPatrolAppServiceReady(request: MarkAppAppServiceReadyRequest) throws {
onAppReady(true, request.port!)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -382,3 +382,7 @@ public struct SetLocationAccuracyRequest: Codable {
public var locationAccuracy: SetLocationAccuracyRequestLocationAccuracy
}

public struct MarkAppAppServiceReadyRequest: Codable {
public var port: Int?
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Foundation

var globalPort: Int32 = 0

@_cdecl("getGlobalPort")
public func getGlobalPort() -> Int32 {
return globalPort
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ protocol NativeAutomatorServer {
func handlePermissionDialog(request: HandlePermissionRequest) throws
func setLocationAccuracy(request: SetLocationAccuracyRequest) throws
func debug() throws
func markPatrolAppServiceReady() throws
func markPatrolAppServiceReady(request: MarkAppAppServiceReadyRequest) throws
}

extension NativeAutomatorServer {
Expand Down Expand Up @@ -274,7 +274,8 @@ extension NativeAutomatorServer {
}

private func markPatrolAppServiceReadyHandler(request: HTTPRequest) throws -> HTTPResponse {
try markPatrolAppServiceReady()
let requestArg = try JSONDecoder().decode(MarkAppAppServiceReadyRequest.self, from: request.body)
try markPatrolAppServiceReady(request: requestArg)
return HTTPResponse(.ok)
}
}
Expand Down
Loading
Loading