Skip to content

Instantly share code, notes, and snippets.

@jaredcnance
Created October 17, 2017 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredcnance/864f0b7ef2b2564904433536c29be359 to your computer and use it in GitHub Desktop.
Save jaredcnance/864f0b7ef2b2564904433536c29be359 to your computer and use it in GitHub Desktop.
internal class FunctionRunner
{
private static readonly string FuncExePath = GetPath(Environment.SpecialFolder.ApplicationData, "npm\\node_modules\\azure-functions-core-tools\\bin\\func.exe");
private readonly string _functionDirectory;
private readonly int _timeouteSeconds;
public FunctionRunner(
string relativeFunctionDirectory,
int timeoutSeconds = 15)
{
_functionDirectory = GetPath(Environment.SpecialFolder.UserProfile, relativeFunctionDirectory);
_timeouteSeconds = timeoutSeconds;
}
public void ExecuteFunction()
{
var process = new Process
{
StartInfo =
{
FileName = FuncExePath,
Arguments = "run . --no-interactive",
WorkingDirectory = _functionDirectory
}
};
process.Start();
Thread.Sleep(_timeouteSeconds * 1000);
KillProcessTree(process);
}
private void KillProcessTree(Process parentProcess)
{
var processesToCleanup = GetChildProcesses(parentProcess.Id);
processesToCleanup.Add(parentProcess);
foreach (var artifactProc in processesToCleanup)
{
if (artifactProc.HasExited)
continue;
// need to kill the process so we can start it in subsequent tests
artifactProc.Kill();
}
Thread.Sleep(2000);
}
public List<Process> GetChildProcesses(int pid)
{
var children = new List<Process>();
var searcher = new ManagementObjectSearcher($"Select * From Win32_Process Where ParentProcessID={pid}");
foreach (var mo in searcher.Get())
children.Add(Process.GetProcessById(Convert.ToInt32(mo["ProcessID"])));
return children;
}
private static string GetPath(Environment.SpecialFolder folder, string remainder)
=> System.IO.Path.Combine(Environment.GetFolderPath(folder), remainder);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment