Skip to content

Commit

Permalink
Add dynamic port generator
Browse files Browse the repository at this point in the history
  • Loading branch information
liliankasem committed Oct 4, 2024
1 parent a88b2c4 commit ba418b2
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 56 deletions.
39 changes: 36 additions & 3 deletions test/Azure.Functions.Cli.Tests/E2E/Helpers/ProcessHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.RegularExpressions;
Expand All @@ -14,9 +16,9 @@ internal class ProcessHelper
private static readonly Regex pidRegex = new Regex(@"LISTENING\s+(\d+)\s*$");
private static string FunctionsHostUrl = "http://localhost";

public static async Task WaitForFunctionHostToStart(Process funcProcess, string port)
public static async Task WaitForFunctionHostToStart(Process funcProcess, int port)
{
var url = $"{FunctionsHostUrl}:{port}";
var url = $"{FunctionsHostUrl}:{port.ToString()}";
using var httpClient = new HttpClient();

await RetryHelper.RetryAsync(async () =>
Expand All @@ -41,7 +43,7 @@ await RetryHelper.RetryAsync(async () =>
});
}

public static void TryKillProcessForPort(string port)
public static void TryKillProcessForPort(int port)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Expand Down Expand Up @@ -76,6 +78,37 @@ public static void TryKillProcessForPort(string port)
}
}

public static int GetAvailablePort(int minPort = 7000, int maxPort = 8000)
{
for (int port = minPort; port <= maxPort; port++)
{
if (IsPortAvailable(port))
{
return port;
}
}

throw new InvalidOperationException("No available ports found in the specified range.");
}

private static bool IsPortAvailable(int port)
{
bool isAvailable = true;

try
{
TcpListener listener = new TcpListener(IPAddress.Any, port);
listener.Start();
listener.Stop();
}
catch (SocketException)
{
isAvailable = false;
}

return isAvailable;
}

private static string ExecuteCommand(string command)
{
using (Process p = new Process())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class RunConfiguration
public Func<string, Process, StringBuilder, Task> Test { get; set; }
public TimeSpan CommandTimeout { get; set; } = TimeSpan.FromSeconds(40);
public string CommandsStr => $"{string.Join(", ", Commands)}";
public bool WaitForRunningHostState = false;
public string HostProcessPort = "7071";
public bool WaitForRunningHostState { get; set; } = false;
public int HostProcessPort { get; set; } = 7071;
}
}
Loading

0 comments on commit ba418b2

Please sign in to comment.