GuOrg / Gu.Wpf.UiAutomation

MIT License
96 stars 17 forks source link

Application.TryAttach can throw uncaught exceptions #184

Open jv42 opened 6 months ago

jv42 commented 6 months ago

I'm using the SetUp method in a very similar way to the example in README.md:

[SetUp]
public void SetUp()
{
    if (Application.TryAttach(ExeFileName, out var app))
    {
        using (app)
        {
            app.MainWindow.FindButton("Reset").Invoke();
        }
    }
}

Basically, I've only removed the argument that I'm not using.

Locally, this works just fine, but on a build machine, I got an exception in TryAttach()

System.InvalidOperationException : Process was not started by this object, so requested information cannot be determined.
          at System.Diagnostics.Process.get_StartInfo()
           at Gu.Wpf.UiAutomation.Application.<>c__DisplayClass33_0.<TryAttach>b__0(Process x)
           at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Func`2 predicate, Boolean& found)
           at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
           at Gu.Wpf.UiAutomation.Application.TryAttach(ProcessStartInfo processStartInfo, OnDispose onDispose, Application& result)
           at Gu.Wpf.UiAutomation.Application.TryAttach(String exeFileName, Application& result)
           at *MyTestApp.MyTestClass*.Setup() in *MyTestClass file* 
           at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
           at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)

It matches this line https://github.com/GuOrg/Gu.Wpf.UiAutomation/blob/d62e2e57e619162476bc77bd4fa4ba83def545aa/Gu.Wpf.UiAutomation/Application.cs#L209

Accessing the StartInfo property is not allowed for all processes [depends on privileges] and should probably be wrapped in a try/catch in that case, if it fails, we can skip it because it's not a valid process to attach to anyway.