diff --git a/Solutions/VS15_amd64/Microsoft.Management.Infrastructure.Tests/Microsoft.Management.Infrastructure.Tests.csproj b/Solutions/VS15_amd64/Microsoft.Management.Infrastructure.Tests/Microsoft.Management.Infrastructure.Tests.csproj index 29b7f57..4226a8e 100644 --- a/Solutions/VS15_amd64/Microsoft.Management.Infrastructure.Tests/Microsoft.Management.Infrastructure.Tests.csproj +++ b/Solutions/VS15_amd64/Microsoft.Management.Infrastructure.Tests/Microsoft.Management.Infrastructure.Tests.csproj @@ -36,6 +36,7 @@ + @@ -158,6 +159,12 @@ UnitTests\CimSessionTest.cs + + UnitTests\CimSessionOptionsTest.cs + + + UnitTests\CimOperationOptionsTest.cs + diff --git a/Solutions/VS15_amd64/Microsoft.Management.Infrastructure/Microsoft.Management.Infrastructure.csproj b/Solutions/VS15_amd64/Microsoft.Management.Infrastructure/Microsoft.Management.Infrastructure.csproj index f9563f8..9043654 100644 --- a/Solutions/VS15_amd64/Microsoft.Management.Infrastructure/Microsoft.Management.Infrastructure.csproj +++ b/Solutions/VS15_amd64/Microsoft.Management.Infrastructure/Microsoft.Management.Infrastructure.csproj @@ -508,11 +508,20 @@ Serialization\MofDeserializerSchemaValidationOption.cs - - Strings.Designer.cs + + True + True + Strings.resx + Resources\Strings.Designer.cs - + + + ResXFileCodeGenerator + Strings.Designer.cs + Resources\Strings.resx + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Operation is not valid during the process of unloading the AppDomain + + + CIM array cannot contain null elements. + + + {0}:{1} + + + CimInstance doesn&apos;t have an associated namespace + + + {0}: {2} ({1}) + + + {0} ({1}) + + + {0}: {1} + + + {0} = {1} + + + CimSession: {0} + + + Could not infer CimType from the provided .NET object. + + + Unknown error. + + + CimSessionOptions instance is invalid: unsupported protocol or unrecognized custom option. Verify parameter passed to the CimSessionOptions(string) constructor and/or parameters passed to the CimSessionOptions.SetCustomOption(string, string) or CimSessionOptions.SetCustomOption(string, int) method. + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure/Serialization/CimDeserializer.cs b/src/Microsoft.Management.Infrastructure/Serialization/CimDeserializer.cs index 6de4bbb..48b4ad1 100644 --- a/src/Microsoft.Management.Infrastructure/Serialization/CimDeserializer.cs +++ b/src/Microsoft.Management.Infrastructure/Serialization/CimDeserializer.cs @@ -28,8 +28,7 @@ private CimDeserializer(string format, uint flags) Debug.Assert(!string.IsNullOrEmpty(format), "Caller should verify that format != null"); MI_Deserializer tmpHandle; - // TODO: Fix MI_SerializerFlags in next line to come from "flags" - MI_Result result = CimApplication.Handle.NewDeserializer(MI_SerializerFlags.None, format, out tmpHandle); + MI_Result result = CimApplication.Handle.NewDeserializer((MI_SerializerFlags)flags, format, out tmpHandle); if (result == MI_Result.MI_RESULT_INVALID_PARAMETER) { throw new ArgumentOutOfRangeException("format"); diff --git a/src/Microsoft.Management.Infrastructure/Serialization/CimMofDeserializer.cs b/src/Microsoft.Management.Infrastructure/Serialization/CimMofDeserializer.cs index 4182e7b..0a4e9a6 100644 --- a/src/Microsoft.Management.Infrastructure/Serialization/CimMofDeserializer.cs +++ b/src/Microsoft.Management.Infrastructure/Serialization/CimMofDeserializer.cs @@ -443,8 +443,7 @@ private void Dispose(bool disposing) if (disposing) { - // TODO: When MI API supports Delete/Dispose, uncomment - //this._myHandle.Dispose(); + this._myHandle.Dispose(); } _disposed = true; diff --git a/src/Microsoft.Management.Infrastructure/Serialization/CimMofSerializer.cs b/src/Microsoft.Management.Infrastructure/Serialization/CimMofSerializer.cs index 23f5606..5296510 100644 --- a/src/Microsoft.Management.Infrastructure/Serialization/CimMofSerializer.cs +++ b/src/Microsoft.Management.Infrastructure/Serialization/CimMofSerializer.cs @@ -22,8 +22,7 @@ private static CimSerializer CreateCimMofSerializer(string format, uint flags) Debug.Assert(!string.IsNullOrEmpty(format), "Caller should verify that format != null"); MI_Serializer tmpHandle; - // TODO: Fix MI_SerializerFlags in next line to come from "flags" - MI_Result result = CimApplication.Handle.NewSerializer(MI_SerializerFlags.None, + MI_Result result = CimApplication.Handle.NewSerializer((MI_SerializerFlags)flags, format, out tmpHandle); if (result == MI_Result.MI_RESULT_INVALID_PARAMETER) diff --git a/src/Microsoft.Management.Infrastructure/Serialization/CimSerializer.cs b/src/Microsoft.Management.Infrastructure/Serialization/CimSerializer.cs index 5948691..f7974da 100644 --- a/src/Microsoft.Management.Infrastructure/Serialization/CimSerializer.cs +++ b/src/Microsoft.Management.Infrastructure/Serialization/CimSerializer.cs @@ -342,8 +342,7 @@ private void Dispose(bool disposing) if (disposing) { - // TODO: Uncomment once this function is implemented - //this._myHandle.Delete(); + this._myHandle.Dispose(); } _disposed = true; diff --git a/test/Microsoft.Management.Infrastructure.Tests/Helpers/Helpers.cs b/test/Microsoft.Management.Infrastructure.Tests/Helpers/Helpers.cs index f99c4e1..a8b7dac 100644 --- a/test/Microsoft.Management.Infrastructure.Tests/Helpers/Helpers.cs +++ b/test/Microsoft.Management.Infrastructure.Tests/Helpers/Helpers.cs @@ -1,14 +1,176 @@ using System; +using System.Collections.Generic; +using System.Diagnostics; +#if !_CORECLR +using System.DirectoryServices; +using System.Runtime.Remoting.Messaging; +#else +#endif using System.IO; +using System.Linq; +using System.Security.Principal; using System.Text; +using System.Threading; +using Microsoft.Management.Infrastructure.Generic; namespace MMI.Tests { using System.Reflection; - using System.Runtime.InteropServices; public static class Helpers { + private const string testUser_userName = "miDotNetTstUsr"; + private const string testUser_password = "test123.#"; + + private class ObservableToListObserver : IObserver + { + private readonly object myLock = new object(); + private readonly List> results = new List>(); + private readonly ManualResetEventSlim completeEvent = new ManualResetEventSlim(false); + private readonly int maxNumberOfResults; + private int numberOfSimultatenousCallbacks; + private bool completed; + + internal ObservableToListObserver(int maxNumberOfResults) + { + this.maxNumberOfResults = maxNumberOfResults; + } + + public bool IsSubscription = false; + private readonly ManualResetEventSlim singleInstanceEvent = new ManualResetEventSlim(false); + + public void OnCompleted() + { + try + { + Assert.Equal( + Interlocked.Increment(ref this.numberOfSimultatenousCallbacks), 1, + "Callbacks should be serialized (i.e. only 1 callback at a time)"); + + lock (this.myLock) + { + Assert.False(this.completed, "Shouldn't get any OnCompleted callbacks after being in complete state"); + + this.completed = true; + this.results.Add(new AsyncItem()); + this.completeEvent.Set(); + this.singleInstanceEvent.Set(); + } + } + catch + { + Debug.Assert(false, "No exception should be thrown by the test helper"); + throw; + } + finally + { + Interlocked.Decrement(ref this.numberOfSimultatenousCallbacks); + } + } + + public void OnError(Exception error) + { + try + { + Assert.Equal( + Interlocked.Increment(ref this.numberOfSimultatenousCallbacks), 1, + "Callbacks should be serialized (i.e. only 1 callback at a time)"); + + lock (this.myLock) + { + Assert.NotNull(error, "error argument of IObserver.OnError should never be null"); + Assert.False(this.completed, "Shouldn't get any OnError callbacks after being in complete state"); + + this.completed = true; + this.results.Add(new AsyncItem(error)); + this.completeEvent.Set(); + this.singleInstanceEvent.Set(); + } + } + catch + { + Debug.Assert(false, "No exception should be thrown by the test helper"); + throw; + } + finally + { + Interlocked.Decrement(ref this.numberOfSimultatenousCallbacks); + } + } + + public void OnNext(T value) + { + try + { + Assert.Equal( + Interlocked.Increment(ref this.numberOfSimultatenousCallbacks), 1, + "Callbacks should be serialized (i.e. only 1 callback at a time)"); + + lock (this.myLock) + { + Assert.False(this.completed, "Shouldn't get any OnNext callbacks after being in complete state"); + + this.results.Add(new AsyncItem(value)); + Assert.True(this.results.Count <= this.maxNumberOfResults); + if (IsSubscription) + { + this.singleInstanceEvent.Set(); + } + } + } + catch + { + Debug.Assert(false, "No exception should be thrown by the test helper"); + throw; + } + finally + { + Interlocked.Decrement(ref this.numberOfSimultatenousCallbacks); + } + } + + public List> GetResults() + { + this.completeEvent.Wait(); + lock (this.myLock) + { + return new List>(this.results); + } + } + + public AsyncItem GetSingleResult() + { + this.singleInstanceEvent.Wait(); + lock (this.myLock) + { + List> availableResults = this.GetAvailableResults(); + if (availableResults.Count > 0) + { + return availableResults[0]; + } + return null; + } + } + + private List> GetAvailableResults() + { + lock (this.myLock) + { + return new List>(this.results); + } + } + + public void StopProcessingResults() + { + lock (this.myLock) + { + this.completeEvent.Set(); + this.singleInstanceEvent.Set(); + } + } + } + + private readonly static BindingFlags PrivateBindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; public static Y GetPrivateProperty(this X self, string name) @@ -53,5 +215,220 @@ public static byte[] GetBytesFromFile(string filePath) System.Text.UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(s); } + + public static void AssertException(Action exceptionCausingAction, Action exceptionVerificationAction = null) where T : Exception + { + try + { + exceptionCausingAction(); + Assert.True(false, "Expected " + typeof(T).Name + " exception"); + } + catch (T exception) + { + if (exceptionVerificationAction != null) + { + exceptionVerificationAction(exception); + } + } + } +#if !_CORECLR + public static void AssertRunningAsNonTestUser(string message) + { + string testUser_userName = "miDotNetTstUsr"; + Assert.NotEqual(WindowsIdentity.GetCurrent().Name, Environment.MachineName + "\\" + testUser_userName, "Asserting that we are not running as impersonated user (windows identity): " + message); + object logicalContextData = CallContext.LogicalGetData("ImpersonationTest"); + Assert.Null(logicalContextData, "Asserting that we are not running as impersonated user (logicalcallcontext-null): " + message); + } + + public static void AssertRunningAsTestUser(string message) + { + string testUser_userName = "miDotNetTstUsr"; + Assert.Equal(WindowsIdentity.GetCurrent().Name, Environment.MachineName + "\\" + testUser_userName, "Asserting that we are running as impersonated user (windowsidentity): " + message); + object logicalContextData = CallContext.LogicalGetData("ImpersonationTest"); + Assert.NotNull(logicalContextData, "Asserting that we are running as impersonated user (logicalcallcontext-notnull): " + message); + Assert.Equal(logicalContextData.ToString(), Process.GetCurrentProcess().Id.ToString(), "Asserting that we are running as impersonated user (logicalcallcontext-datacontent): " + message); + } + + private static void AddTestUser() + { + DirectoryEntry computer = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); + if (computer.Children.Cast().Any(entry => entry.Name.Equals(testUser_userName, StringComparison.OrdinalIgnoreCase))) + { + return; + } + DirectoryEntry user = computer.Children.Add(testUser_userName, "user"); + user.Invoke("SetPassword", new object[] { testUser_password }); + user.Invoke("Put", new object[] { "Description", "Test user for MI Client .NET API DRTs" }); + user.CommitChanges(); + + SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); + string name = sid.Translate(typeof(NTAccount)).ToString(); + string administratorsGroupName = name.Split('\\')[1]; + + DirectoryEntry group = computer.Children.Find(administratorsGroupName, "group"); + group.Invoke("Add", new object[] { user.Path.ToString() }); + } + + private class MyImpersonationRestorationDisposable : IDisposable + { + public MyImpersonationRestorationDisposable(WindowsImpersonationContext impersonationContext) + { + this._impersonationContext = impersonationContext; + } + + private WindowsImpersonationContext _impersonationContext; + + public void Dispose() + { + this._impersonationContext.Undo(); + CallContext.FreeNamedDataSlot("ImpersonationTest"); + } + } + + public static List> ObservableToList(IObservable observable) + { + return ObservableToList(observable, null); + } + + public static AsyncItem ObservableToSingleItem(IObservable observable) + { + Assert.NotNull(observable, "API should never return a null observable"); + + int maxNumberOfResults = int.MaxValue; + if (observable.GetType().IsGenericType && observable.GetType().GetGenericTypeDefinition().Equals(typeof(CimAsyncResult<>))) + { + maxNumberOfResults = 1; + } + + var observer = new ObservableToListObserver(maxNumberOfResults); + observer.IsSubscription = true; + + IDisposable cancellationDisposable = null; + try + { + cancellationDisposable = observable.Subscribe(observer); + } + catch + { + Assert.True(false, "Subscribe should not throw any exceptions"); + } + Assert.NotNull( + cancellationDisposable, + "Wes Dyer says that Subscribe should never return null (even for non-cancellable operations) - this results in better composability"); + + Thread.Sleep(3000); + StartDummyProcess(); + return observer.GetSingleResult(); + } + + public static List> ObservableToList(IObservable observable, TimeSpan? cancellationDelay) + { + Assert.NotNull(observable, "API should never return a null observable"); + + int maxNumberOfResults = int.MaxValue; + if (observable.GetType().IsGenericType && observable.GetType().GetGenericTypeDefinition().Equals(typeof(CimAsyncResult<>))) + { + maxNumberOfResults = 1; + } + + var observer = new ObservableToListObserver(maxNumberOfResults); + + IDisposable cancellationDisposable = null; + try + { + cancellationDisposable = observable.Subscribe(observer); + } + catch + { + Assert.True(false, "Subscribe should not throw any exceptions"); + } + Assert.NotNull( + cancellationDisposable, + "Wes Dyer says that Subscribe should never return null (even for non-cancellable operations) - this results in better composability"); + + if (cancellationDelay.HasValue) + { + Assert.NotNull(cancellationDisposable, "IObservable.Subscribe should always return non-null"); + if (cancellationDelay != TimeSpan.MaxValue) + { + Thread.Sleep((int)(cancellationDelay.Value.TotalMilliseconds)); + cancellationDisposable.Dispose(); + Thread.Sleep(TimeSpan.FromSeconds(3)); + Thread.Sleep((int)(cancellationDelay.Value.TotalMilliseconds)); + observer.StopProcessingResults(); + } + } + + List> results = observer.GetResults(); + + if (cancellationDelay.HasValue) + { + if (cancellationDelay == TimeSpan.MaxValue) + { + cancellationDisposable.Dispose(); + } + } + + return results; + } +#else +#endif + #region Fake + internal static int StartDummyProcess() + { + System.Diagnostics.ProcessStartInfo processInfo = new System.Diagnostics.ProcessStartInfo(); + processInfo.FileName = "ttest.exe"; + + processInfo.UseShellExecute = false; + processInfo.RedirectStandardOutput = true; + processInfo.RedirectStandardError = true; + processInfo.CreateNoWindow = true; + System.Diagnostics.Process proc = System.Diagnostics.Process.Start(processInfo); + + StreamReader outputReader = proc.StandardOutput; + StreamReader errorReader = proc.StandardError; + + string sOutput = outputReader.ReadToEnd(); + + sOutput = errorReader.ReadToEnd(); + proc.WaitForExit(); + return proc.ExitCode; + } + #endregion Fake + } + + public enum AsyncItemKind + { + Item, + Exception, + Completion + } + + public class AsyncItem + { + public AsyncItem(T item) + { + this.Kind = AsyncItemKind.Item; + this.Item = item; + this.Timestamp = DateTime.Now; + } + + public AsyncItem(Exception ex) + { + this.Kind = AsyncItemKind.Exception; + this.Exception = ex; + this.Timestamp = DateTime.Now; + } + + public AsyncItem() + { + this.Kind = AsyncItemKind.Completion; + this.Timestamp = DateTime.Now; + } + + public AsyncItemKind Kind { get; private set; } + public T Item { get; private set; } + public Exception Exception { get; private set; } + public DateTime Timestamp { get; private set; } } } diff --git a/test/Microsoft.Management.Infrastructure.Tests/NativeTests/SessionTests.cs b/test/Microsoft.Management.Infrastructure.Tests/NativeTests/SessionTests.cs index d74ae83..f613206 100644 --- a/test/Microsoft.Management.Infrastructure.Tests/NativeTests/SessionTests.cs +++ b/test/Microsoft.Management.Infrastructure.Tests/NativeTests/SessionTests.cs @@ -6,6 +6,8 @@ using Microsoft.Management.Infrastructure.Native; using MMI.Tests; using Xunit; +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; namespace MMI.Tests.Native { @@ -200,5 +202,57 @@ public void SimpleGetClass() Assert.Equal(TestGetClassParameterType, parameterType, "Expect parameter type to be the documented type"); Assert.Equal(TestGetClassParameterIndex, parameterIndex, "Expect the power state to be the first parameter"); } + + [WindowsFact] + public void ClassHashCode_Sanity() + { + MI_Operation cimClassOperation1; + MMI.Tests.Native.StaticFixtures.Session.GetClass(MI_OperationFlags.Default, null, TestGetClassNamespace, TestGetClassClassName, null, out cimClassOperation1); + MI_Class cimClass1; + bool moreResults1; + MI_Result operationRes1; + MI_Instance completionDetails1; + string errorMessage1; + var res1 = cimClassOperation1.GetClass(out cimClass1, out moreResults1, out operationRes1, out errorMessage1, out completionDetails1); + MIAssert.Succeeded(res1); + MIAssert.Succeeded(operationRes1); + Assert.False(moreResults1, "Expect no more results after getting named class"); + + MI_Operation cimClassOperation2; + MMI.Tests.Native.StaticFixtures.Session.GetClass(MI_OperationFlags.Default, null, TestGetClassNamespace, TestGetClassClassName, null, out cimClassOperation2); + MI_Class cimClass2; + bool moreResults2; + MI_Result operationRes2; + MI_Instance completionDetails2; + string errorMessage2; + var res2 = cimClassOperation2.GetClass(out cimClass2, out moreResults2, out operationRes2, out errorMessage2, out completionDetails2); + MIAssert.Succeeded(res2); + MIAssert.Succeeded(operationRes2); + Assert.False(moreResults2, "Expect no more results after getting named class"); + + int hash1 = cimClass1.GetClassHashCode(); + int hash2 = cimClass2.GetClassHashCode(); + + Assert.Equal(hash1, hash2, "MI_Class HashCodes are not identical for two objects of the same class."); + + cimClassOperation1.Close(); + cimClassOperation2.Close(); + } + + [WindowsFact] + public void CredentialTest() + { + string testpassword = "mypassword"; + System.Security.SecureString testSS = new System.Security.SecureString(); + foreach (char ch in testpassword) + testSS.AppendChar(ch); + + CimCredential c = new CimCredential(PasswordAuthenticationMechanism.Default, "myhost", "johnkord", testSS); + CimSessionOptions csOpts = new CimSessionOptions(); + csOpts.AddDestinationCredentials(c); + CimSession s = CimSession.Create("localhost", csOpts); + + + } } } diff --git a/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimClassTest.cs b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimClassTest.cs deleted file mode 100644 index be1c7cf..0000000 --- a/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimClassTest.cs +++ /dev/null @@ -1,21 +0,0 @@ -/*============================================================================ -* Copyright (C) Microsoft Corporation, All rights reserved. -*============================================================================= -*/ - -namespace Microsoft.Management.Infrastructure.UnitTests -{ - using Microsoft.Management.Infrastructure; - using Microsoft.Management.Infrastructure.Native; - using System; - using MMI.Tests; - using Xunit; - - public class CimClassTest - { - [TDDFact] - public void TODO() - { - } - } -} diff --git a/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimOperationOptionsTest.cs b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimOperationOptionsTest.cs new file mode 100644 index 0000000..c74584c --- /dev/null +++ b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimOperationOptionsTest.cs @@ -0,0 +1,432 @@ +/*============================================================================ +* Copyright (C) Microsoft Corporation, All rights reserved. +*============================================================================= +*/ + +using System; +using System.Globalization; +using System.Security; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Security.Cryptography.X509Certificates; +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; +using Xunit; + +namespace MMI.Tests.UnitTests +{ + public class CimOperationOptionsTest + { + [TDDFact] + public void BaseOptions_Empty() + { + using (var operationOptions = new CimOperationOptions(mustUnderstand: true)) + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [TDDFact] + public void BaseOptions_Timeout_Medium() + { + var operationOptions = new CimOperationOptions(mustUnderstand: true); + operationOptions.Timeout = TimeSpan.FromSeconds(123); + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [TDDFact] + public void BaseOptions_Timeout_Small() + { + var operationOptions = new CimOperationOptions(mustUnderstand: true); + operationOptions.Timeout = TimeSpan.FromMilliseconds(1); + Assert.Throws(() => + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + enumeratedInstances.Count(); + } + return null; + }); + } + + [TDDFact] + public void BaseOptions_Timeout_Infinity() + { + var operationOptions = new CimOperationOptions(mustUnderstand: true); + operationOptions.Timeout = TimeSpan.MaxValue; + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [TDDFact] + public void BaseOptions_UseMachineId_True() + { + var operationOptions = new CimOperationOptions(mustUnderstand: true); + operationOptions.UseMachineId = true; + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [TDDFact] + public void BaseOptions_UseMachineId_False() + { + var operationOptions = new CimOperationOptions(mustUnderstand: true); + operationOptions.UseMachineId = false; + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [TDDFact] + public void BaseOptions_ResourceUriPrefix() + { + var operationOptions = new CimOperationOptions(mustUnderstand: true); + operationOptions.ResourceUriPrefix = new Uri("http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2"); + + var sessionOptions = new WSManSessionOptions(); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [Fact] + public void BaseOptions_ResourceUriPrefix_Null() + { + var operationOptions = new CimOperationOptions(mustUnderstand: true); + Assert.Throws(() => + { + return operationOptions.ResourceUriPrefix = null; + }); + + } + + [TDDFact] + public void BaseOptions_CustomOptionString_MustUnderstandFalse() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + operationOptions.SetCustomOption("MyOptionName", "MyOptionValue", false); + + var sessionOptions = new WSManSessionOptions(); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [TDDFact] + public void BaseOptions_CustomOptionString_MustUnderstandTrue() + { + var operationOptions = new CimOperationOptions(mustUnderstand: true); + operationOptions.SetCustomOption("MyOptionName", "MyOptionValue", false); + + var sessionOptions = new WSManSessionOptions(); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [Fact] + public void BaseOptions_CustomOptionString_OptionName_Null() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + Assert.Throws(() => + { + operationOptions.SetCustomOption(null, "MyOptionValue", false); + return null; + }); + } + + [Fact] + public void BaseOptions_CustomOption_MismatchedValueAndType() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + Assert.Throws(() => + { + operationOptions.SetCustomOption("MyOptionName", "abc", CimType.DateTime, false); + return null; + }); + } + + [TDDFact] + public void BaseOptions_CustomOption_UnsupportedType() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + Assert.Throws(() => + { + var cimInstance = new CimInstance("MyClassName"); + operationOptions.SetCustomOption("MyOptionName", cimInstance, CimType.Instance, false); + return null; + }); + } + + [TDDFact] + public void BaseOptions_CustomOption_RoundtripString() + { + using (var cimSession = CimSession.Create(null)) + { + var cimInstance = cimSession.EnumerateInstances("this.TestNamespace", "TestClass_AllDMTFTypes").First(); + Assert.NotNull(cimInstance, "Sanity check - got an instance to act on"); + + var operationOptions = new CimOperationOptions(mustUnderstand: false); + operationOptions.SetCustomOption("MyOptionName", "MyOptionValue", CimType.String, mustComply: false); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create("optionName", "MyOptionName", CimType.String, CimFlags.None)); + CimMethodResult result = cimSession.InvokeMethod("this.TestNamespace", cimInstance, "GetStringCustomOption", methodParameters, operationOptions); + Assert.NotNull(result, "CimSession.InvokeMethod returned non-null"); + + Assert.Equal(result.ReturnValue.CimType, CimType.UInt32, "Got the right type of return value"); + object returnValue = result.ReturnValue.Value; + Assert.Equal((UInt32)returnValue, (uint)0, "Got the right return value"); + + CimMethodParameter optionValueParameter = result.OutParameters["optionValue"]; + Assert.NotNull(optionValueParameter, "Got the out parameter"); + Assert.Equal(optionValueParameter.CimType, CimType.String, "Got the right CIM type of out parameter"); + Assert.True(optionValueParameter.Value is string, "Got the right .NET type of out parameter"); + Assert.Equal((string)(optionValueParameter.Value), "MyOptionValue", "Got the right value of out parameter"); + } + } + + [Fact] + public void BaseOptions_CustomOption_OptionName_Null() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + Assert.Throws(() => + { + operationOptions.SetCustomOption(null, 123, CimType.UInt8, false); + return null; + }); + } + + [Fact] + public void BaseOptions_RawOptionString() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + operationOptions.SetOption("MyOptionName", "MyOptionValue"); + } + + [Fact] + public void BaseOptions_RawOptionUInt32() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + operationOptions.SetOption("MyOptionName", 123); + } + + [Fact] + public void BaseOptions_RawOptionString_OptionName_Null() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + Assert.Throws(() => + { + operationOptions.SetOption(null, "MyOptionValue"); + return null; + }); + } + + [Fact] + public void BaseOptions_RawOptionUInt32_OptionName_Null() + { + var operationOptions = new CimOperationOptions(mustUnderstand: false); + Assert.Throws(() => + { + operationOptions.SetOption(null, 123); + return null; + }); + } + + [TDDFact] + public void BaseOptions_KeysOnly_True() + { + var operationOptions = new CimOperationOptions { KeysOnly = true }; + Assert.Equal(operationOptions.KeysOnly, true, "KeysOnly round-trips properly"); + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + + CimInstance cimInstance = enumeratedInstances.ToList().First(); + Assert.NotNull(cimInstance, "cimSession.EnumerateInstances returned results other than null"); + List allProperties = cimInstance.CimInstanceProperties.ToList(); + + Assert.Equal(allProperties.Where(p => p.Value != null).Count(), 1, "Only key properties should get values"); + Assert.True(allProperties.Where(p => p.Value != null).All(p => CimFlags.Key == (p.Flags & CimFlags.Key)), "keyProperty.Flags includes CimFlags.Key"); + Assert.True(allProperties.Where(p => p.Value != null).All(p => p.Name.Equals("Handle", StringComparison.OrdinalIgnoreCase)), "keyProperty.Name equals 'Handle' for Win32_Process"); + } + } + + [TDDFact] + public void BaseOptions_KeysOnly_False() + { + var operationOptions = new CimOperationOptions { KeysOnly = false }; + Assert.Equal(operationOptions.KeysOnly, false, "KeysOnly round-trips properly"); + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + + CimInstance cimInstance = enumeratedInstances.ToList().First(); + Assert.NotNull(cimInstance, "cimSession.EnumerateInstances returned results other than null"); + List allProperties = cimInstance.CimInstanceProperties.ToList(); + + Assert.True(allProperties.Count > 1, "More than 1 property of Win32_Process is returned"); + Assert.True(allProperties.Any(property => CimFlags.Key != (property.Flags & CimFlags.Key)), "Some of the returned properties are non-key"); + Assert.True(allProperties.Any(property => CimFlags.Key == (property.Flags & CimFlags.Key)), "Some of the returned properties are key"); + } + } + + [TDDFact] + public void BaseOptions_ShortenLifetimeOfResults_Sync() + { + var operationOptions = new CimOperationOptions { ShortenLifetimeOfResults = true }; + + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + + CimInstance cimInstance = enumeratedInstances.ToList().First(); + Assert.NotNull(cimInstance, "cimSession.EnumerateInstances returned results other than null"); + + Assert.Throws(() => { return cimInstance.CimSystemProperties.ClassName; }); + } + } + /* + [Fact] + public void BaseOptions_ShortenLifetimeOfResults_Async_EnumInstances() + { + var operationOptions = new CimOperationOptions { ShortenLifetimeOfResults = true }; + + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable enumeratedInstances = cimSession.EnumerateInstancesAsync(@"root\cimv2", "Win32_Process", operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + + List> serializedResults = Helpers.ObservableToList(enumeratedInstances); + Assert.NotNull(serializedResults, "cimSession.EnumerateInstances returned results other than null"); + Assert.True(serializedResults.Count >= 2, "cimSession.EnumerateInstances returned some results"); + Assert.Equal(serializedResults[0].Kind, AsyncItemKind.Item, "cimSession.EnumerateInstances returned an actual CimInstance"); + Assert.Throws(() => + { + for (int i = 0; i < 10; i++) + { + var className = serializedResults[0].Item.CimSystemProperties.ClassName; + Thread.Sleep(200); + } + return null; + }); + } + } + + [Fact] + public void BaseOptions_ShortenLifetimeOfResults_Async_MethodRegular() + { + using (var cimSession = CimSession.Create(null)) + { + var operationOptions = new CimOperationOptions { ShortenLifetimeOfResults = true, EnableMethodResultStreaming = false }; + + var methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create("count", 3, CimType.UInt32, CimFlags.None)); + IObservable observable = cimSession.InvokeMethodAsync("this.TestNamespace", "TestClass_Streaming", "StreamNumbers", methodParameters, operationOptions); + Assert.NotNull(observable, "CimSession.InvokeMethod returned non-null"); + + List> result = Helpers.ObservableToList(observable); + Assert.True(result.Count > 0, "Got some callbacks"); + Assert.Equal(result[result.Count - 1].Kind, AsyncItemKind.Completion, "Got completion callback"); + + Assert.True(result.Count > 1, "Got more than 1 callback"); + Assert.Equal(result[result.Count - 2].Kind, AsyncItemKind.Item, "Got non-streamed result (presence)"); + Assert.True(result[result.Count - 2].Item.GetType().Equals(typeof(CimMethodResult)), "Got non-streamed result (type)"); + + CimMethodResult methodResult = (CimMethodResult)result[result.Count - 2].Item; + Assert.Throws(() => + { + for (int i = 0; i < 10; i++) + { + var tmp = methodResult.OutParameters.Count; // expecting ObjectDisposedException here + Thread.Sleep(200); + } + return null; + }); + } + } + + [Fact] + public void BaseOptions_ShortenLifetimeOfResults_Async_MethodStreaming() + { + using (var cimSession = CimSession.Create(null)) + { + var operationOptions = new CimOperationOptions { ShortenLifetimeOfResults = true, EnableMethodResultStreaming = true }; + + var methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create("count", 3, CimType.UInt32, CimFlags.None)); + IObservable observable = cimSession.InvokeMethodAsync("this.TestNamespace", "TestClass_Streaming", "StreamNumbers", methodParameters, operationOptions); + Assert.NotNull(observable, "CimSession.InvokeMethod returned non-null"); + + List> result = Helpers.ObservableToList(observable); + Assert.True(result.Count > 0, "Got some callbacks"); + Assert.Equal(result[result.Count - 1].Kind, AsyncItemKind.Completion, "Got completion callback"); + + Assert.True(result.Count > 1, "Got more than 1 callback"); + + Assert.True(result[0].Item.GetType().Equals(typeof(CimMethodStreamedResult)), "Got streamed result"); + CimMethodStreamedResult streamedResult = ((CimMethodStreamedResult)(result[0].Item)); + + Assert.True(streamedResult.ItemValue is CimInstance, "Got streamed instance back"); + CimInstance cimInstance = (CimInstance)streamedResult.ItemValue; + Assert.Throws(() => + { + for (int i = 0; i < 10; i++) + { + var tmp = cimInstance.CimSystemProperties.ClassName; // expecting ObjectDisposedException here + Thread.Sleep(200); + } + return null; + }); + } + } + */ + } +} diff --git a/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimSessionOptionsTest.cs b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimSessionOptionsTest.cs new file mode 100644 index 0000000..3e7249b --- /dev/null +++ b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimSessionOptionsTest.cs @@ -0,0 +1,564 @@ +/*============================================================================ +* Copyright (C) Microsoft Corporation, All rights reserved. +*============================================================================= +*/ + +using System; +using System.Globalization; +using System.Security; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; +using Xunit; + +namespace MMI.Tests.UnitTests +{ + + public class CimSessionOptionsTest + { + [Fact] + public void BaseOptions_Empty() + { + var sessionOptions = new CimSessionOptions(); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void BaseOptions_Timeout() + { + var sessionOptions = new CimSessionOptions(); + sessionOptions.Timeout = TimeSpan.FromSeconds(123); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void BaseOptions_AddDestinationCredential1() + { + var sessionOptions = new CimSessionOptions(); + CimCredential cred = new CimCredential(ImpersonatedAuthenticationMechanism.None); + sessionOptions.AddDestinationCredentials(cred); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void BaseOptions_AddDestinationCredential2() + { + var sessionOptions = new CimSessionOptions(); + SecureString str = new SecureString(); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + CimCredential cred = new CimCredential(PasswordAuthenticationMechanism.Default, "ddddddd", "ddddddd", str); + sessionOptions.AddDestinationCredentials(cred); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void BaseOptions_AddDestinationCredential3() + { + string thumbprint = null; + X509Store store = new X509Store("My", StoreLocation.LocalMachine); + store.Open(OpenFlags.ReadOnly); + foreach (var cert in store.Certificates) + { + thumbprint = cert.Thumbprint; + break; + } + + var sessionOptions = new WSManSessionOptions(); + CimCredential cred = new CimCredential(CertificateAuthenticationMechanism.Default, thumbprint); + sessionOptions.AddDestinationCredentials(cred); + sessionOptions.UseSsl = true; + using (CimSession cimSession = CimSession.Create(Environment.MachineName, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void BaseOptions_AddDestinationCredential4_NullUserName() + { + var sessionOptions = new CimSessionOptions(); + SecureString str = new SecureString(); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + CimCredential cred = new CimCredential(PasswordAuthenticationMechanism.Default, "ddddddd", null, str); + sessionOptions.AddDestinationCredentials(cred); + Assert.Throws(() => { return CimSession.Create(null, sessionOptions); }); + } + + [TDDFact] + public void BaseOptions_AddDestinationCredential5_WrongMechamism() + { + var sessionOptions = new CimSessionOptions(); + SecureString str = new SecureString(); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + str.AppendChar('d'); + CimCredential cred = new CimCredential((PasswordAuthenticationMechanism)100, "ddddddd", "ddddddd", str); + sessionOptions.AddDestinationCredentials(cred); + Assert.Throws(() => { return CimSession.Create(null, sessionOptions); }); + } + + [TDDFact] + public void BaseOptions_Timeout_Infinity() + { + var sessionOptions = new CimSessionOptions(); + sessionOptions.Timeout = TimeSpan.MaxValue; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + /* + [Fact] + public void BaseOptions_Culture() + { + var sessionOptions = new CimSessionOptions(); + sessionOptions.Culture = CultureInfo.GetCultures(CultureTypes.AllCultures).First(); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + */ + [Fact] + public void BaseOptions_Culture_Null() + { + var sessionOptions = new CimSessionOptions(); + Assert.Throws(() => { return sessionOptions.Culture = null; }); + } + /* + [Fact] + public void BaseOptions_UICulture() + { + var sessionOptions = new CimSessionOptions(); + sessionOptions.UICulture = CultureInfo.GetCultures(CultureTypes.AllCultures).First(); + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + */ + [TDDFact] + public void BaseOptions_UICulture_Null() + { + var sessionOptions = new CimSessionOptions(); + Assert.Throws(() => { return sessionOptions.UICulture = null; }); + } + + [TDDFact] + public void DComOptions_Empty() + { + using (var sessionOptions = new DComSessionOptions()) + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_PacketIntegrity_True() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.PacketIntegrity = true; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_PacketIntegrity_False() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.PacketIntegrity = false; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_PacketPrivacy_True() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.PacketPrivacy = true; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_PacketPrivacy_False() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.PacketPrivacy = false; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_Impersonation_None() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.Impersonation = ImpersonationType.None; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_Impersonation_Default() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.Impersonation = ImpersonationType.Default; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_Impersonation_Delegate() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.Impersonation = ImpersonationType.Delegate; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_Impersonation_Identify() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.Impersonation = ImpersonationType.Identify; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void DComOptions_Impersonation_Impersonate() + { + var sessionOptions = new DComSessionOptions(); + sessionOptions.Impersonation = ImpersonationType.Impersonate; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_Empty() + { + using (var sessionOptions = new WSManSessionOptions()) + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetDestinationPort() + { + // TODO/FIXME - add unit test for corner cases (0, > 65535) + + var sessionOptions = new WSManSessionOptions(); + sessionOptions.DestinationPort = 8080; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetProxyCredential() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.DestinationPort = 8080; + CimCredential cred = new CimCredential(ImpersonatedAuthenticationMechanism.None); //wsman accepts only username/password + sessionOptions.AddProxyCredentials(cred); + //Exception is thrown after creating the session as WSMAN doesn'[TDDFact] allow proxy without username/password. + Assert.Throws(() => { return CimSession.Create(null, sessionOptions); }); + } + + [TDDFact] + public void WSManOptions_SetMaxEnvelopeSize() + { + // TODO/FIXME - add unit test for corner cases (0, maxvalue) + var sessionOptions = new WSManSessionOptions(); + sessionOptions.MaxEnvelopeSize = 8080; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetCertCACheck_True() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.CertCACheck = true; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetCertCACheck_False() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.CertCACheck = false; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetCertCNCheck_True() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.CertCNCheck = true; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetCertCNCheck_False() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.CertCNCheck = false; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetCertRevocationCheck_True() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.CertRevocationCheck = true; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetCertRevocationCheck_False() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.CertRevocationCheck = false; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetUseSsl_True() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.UseSsl = true; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetUseSsl_False() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.UseSsl = false; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_ProxyType_None() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.ProxyType = ProxyType.None; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_ProxyType_Invalid() + { + var sessionOptions = new WSManSessionOptions(); + Assert.Throws(() => { return sessionOptions.ProxyType = (ProxyType)123; }); + } + + [TDDFact] + public void WSManOptions_PacketEncoding_Default() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.PacketEncoding = PacketEncoding.Default; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_PacketEncoding_UTF8() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.PacketEncoding = PacketEncoding.Utf8; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_PacketEncoding_UTF16() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.PacketEncoding = PacketEncoding.Utf16; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_PacketEncoding_Invalid() + { + var sessionOptions = new WSManSessionOptions(); + Assert.Throws(() => { return sessionOptions.PacketEncoding = (PacketEncoding)123; }); + } + + [TDDFact] + public void WSManOptions_SetEncodePortInSPN_True() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.EncodePortInServicePrincipalName = true; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_SetEncodePortInSPN_False() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.EncodePortInServicePrincipalName = false; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + private void WSManOptions_SetHttpUrlPrefix_Core(Uri orig) + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.HttpUrlPrefix = orig; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + Uri roundTrip = sessionOptions.HttpUrlPrefix; + Assert.Equal(roundTrip.ToString(), orig.ToString(), "HttpUrlPrefix should stay the same on round-trip"); + } + + [TDDFact] + public void WSManOptions_SetHttpUrlPrefix_Relative() + { + WSManOptions_SetHttpUrlPrefix_Core(new Uri("myPrefix", UriKind.Relative)); + } + + [TDDFact] + public void WSManOptions_SetHttpUrlPrefix_Absolute() + { + WSManOptions_SetHttpUrlPrefix_Core(new Uri("http://www.microsoft.com", UriKind.Absolute)); + } + + [TDDFact] + public void WSManOptions_SetHttpUrlPrefix_Null() + { + var sessionOptions = new WSManSessionOptions(); + Assert.Throws(() => { return sessionOptions.HttpUrlPrefix = null; }); + } + + private class TestCustomOptions : CimSessionOptions + { + internal TestCustomOptions(string protocolName) + : base(protocolName) + { + } + } + + [TDDFact] + public void WSManOptions_NoEncryption_True() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.NoEncryption = true; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void WSManOptions_NoEncryption_False() + { + var sessionOptions = new WSManSessionOptions(); + sessionOptions.NoEncryption = false; + using (CimSession cimSession = CimSession.Create(null, sessionOptions)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + } + } + + [TDDFact] + public void CustomOptions_UnrecognizedProtocol() + { + var sessionOptions = new TestCustomOptions("unrecognizedProtocolName"); + Assert.Throws(() => { return CimSession.Create(null, sessionOptions); }); + } + } +} diff --git a/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimSessionTest.cs b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimSessionTest.cs index 7f16ba4..430cd9c 100644 --- a/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimSessionTest.cs +++ b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/CimSessionTest.cs @@ -2,18 +2,26 @@ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================= */ + using Microsoft.Management.Infrastructure; +using Microsoft.Management.Infrastructure.Options; +using Microsoft.Management.Infrastructure.Generic; +using System; +using System.IO; +using System.Collections; +using System.Linq; +using System.Collections.Generic; +using System.Threading; +using System.Globalization; +using System.Diagnostics; +using System.Text.RegularExpressions; using Xunit; namespace MMI.Tests.UnitTests { - - - public class CimSessionTest { - #region Test create - [TDDFact] + [Fact] public void Create_ComputerName_Null() { using (CimSession cimSession = CimSession.Create(null)) @@ -33,7 +41,2250 @@ public void Create_ComputerName_Localhost() Assert.True(cimSession.ToString().Contains("localhost"), "cimSession.ToString should contain computer name"); } } - // Todo: will add more test cases - #endregion Test create + + [TDDFact] + public void Create_ComputerName_Nonexistant_DCOM() + { + using (CimSession cimSession = CimSession.Create("nonexistantcomputer", new DComSessionOptions())) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Helpers.AssertException( + () => cimSession.EnumerateInstances(@"root\cimv2", "CIM_OSProcess").Count(), + delegate (CimException exception) + { + Assert.Equal(NativeErrorCode.Failed, exception.NativeErrorCode, "Got the right NativeErrorCode"); + Assert.Equal("MSFT_WmiError", exception.ErrorData.CimSystemProperties.ClassName, "Got the right kind of ErrorData"); + Assert.Equal((uint)1, exception.StatusCode, "Got the right StatusCode"); + }); + } + } + /* + [Fact] + public void Create_ComputerName_Nonexistant_WSMan() + { + using (CimSession cimSession = CimSession.Create("nonexistantcomputer", new WSManSessionOptions())) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Helpers.AssertException( + () => cimSession.EnumerateInstances(@"root\cimv2", "CIM_OSProcess"), + delegate (CimException exception) + { + Assert.Equal(NativeErrorCode.Failed, exception.NativeErrorCode, "Got the right NativeErrorCode"); + Assert.Equal("MSFT_WmiError", exception.ErrorData.CimSystemProperties.ClassName, "Got the right kind of ErrorData"); + Assert.Equal((uint)1, exception.StatusCode, "Got the right StatusCode"); + if (Thread.CurrentThread.CurrentUICulture.DisplayName.Equals("en-US", StringComparison.OrdinalIgnoreCase)) + { + Assert.True(exception.Message.Contains("winrm"), "Got the right Message (1)"); + Assert.True(exception.Message.Contains("cannot find"), "Got the right Message (2)"); + Assert.True(exception.Message.Contains("computer"), "Got the right Message (3)"); + Assert.True(exception.Message.Contains("nonexistantcomputer"), "Got the right Message (4)"); + } + }); + } + } + */ + [TDDFact] + public void Create_ComputerName_EnvironmentMachineName() + { + string machineName = Environment.MachineName; + using (CimSession cimSession = CimSession.Create(machineName)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Equal(machineName, cimSession.ComputerName, "cimSession.ComputerName should not be the same as the value passed to Create method"); + } + } + + [Fact] + public void Close() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + cimSession.Close(); + } + } + + [Fact] + public void AlreadyDisposed_Close_Then_Close() + { + CimSession cimSession = CimSession.Create(null); + Assert.NotNull(cimSession, "cimSession should not be null"); + cimSession.Close(); + cimSession.Close(); // expecting no exception - Close/CloseAsync/Dispose should be idempotent + } + + [Fact] + public void AlreadyDisposed_Dispose_Then_Close() + { + CimSession cimSession = CimSession.Create(null); + Assert.NotNull(cimSession, "cimSession should not be null"); + cimSession.Dispose(); + cimSession.Close(); // expecting no exception - Close/CloseAsync/Dispose should be idempotent + } + + [TDDFact] + public void EnumerateInstances_ClassName_NotFound() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Helpers.AssertException( + () => cimSession.EnumerateInstances(@"root\cimv2", "nonExistantClassHere").Count(), + delegate (CimException exception) + { + Assert.Equal(exception.NativeErrorCode, NativeErrorCode.InvalidClass, "Got the right NativeErrorCode"); + Assert.Equal(exception.Message, "Invalid_Class", "Got the right message (1)"); + Assert.Equal(exception.Message, "InvalidClass", "Got the right message (2)"); + Assert.True(exception.Message.IndexOf(' ') != (-1), "Got the right message (3)"); + }); + } + } + + [Fact] + public void EnumerateInstances_ClassName_NotFound_EnumerationIsLazy() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + cimSession.EnumerateInstances(@"root\cimv2", "NotExistantClass"); + } + } + + [TDDFact] + public void EnumerateInstances() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedInstances.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + } + } + + [TDDFact] + public void EnumerateInstances_SessionComputerName() + { + using (CimSession cimSession = CimSession.Create(Environment.MachineName, new WSManSessionOptions())) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimInstance topInstance = cimSession.EnumerateInstances(@"root\cimv2", "CIM_ProcessExecutable").FirstOrDefault(); + Assert.NotNull(topInstance, "topInstance should not be null"); + Assert.Equal(topInstance.GetCimSessionComputerName(), Environment.MachineName, "Verifying topInstance.GetCimSessionComputerName"); + + CimInstance embeddedInstance = (CimInstance)topInstance.CimInstanceProperties["Antecedent"].Value; + Assert.Equal(embeddedInstance.GetCimSessionComputerName(), Environment.MachineName, "Verifying embeddedInstance.GetCimSessionComputerName"); + + Assert.Equal(embeddedInstance.GetCimSessionInstanceId(), topInstance.GetCimSessionInstanceId(), "Verifying GetCimSessionInstanceId"); + } + } + + public CimSession EnumerateInstances_AbandonedEnumerator_Helper() + { + CimSession cimSession = CimSession.Create(null, new WSManSessionOptions()); + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + IEnumerator enumerator = enumeratedInstances.GetEnumerator(); + enumerator.MoveNext(); + return cimSession; + } + + [TDDFact] + public void EnumerateInstances_AbandonedEnumerator() + { + CimSession cimSession = EnumerateInstances_AbandonedEnumerator_Helper(); + + Thread.Sleep(1000); + GC.Collect(); + GC.WaitForPendingFinalizers(); + Thread.Sleep(1000); + GC.Collect(); + GC.WaitForPendingFinalizers(); + Thread.Sleep(1000); + GC.Collect(); + GC.WaitForPendingFinalizers(); + + // this will hang if garbage collection has not drained the sync operation + cimSession.Close(); + } + + [TDDFact] + public void EnumerateInstances_IsValueModified() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + CimInstance cimInstance = enumeratedInstances.FirstOrDefault(); + Assert.NotNull(cimInstance, "cimSession.EnumerateInstances returned some instances"); + + foreach (CimProperty property in cimInstance.CimInstanceProperties) + { + Assert.True(!property.IsValueModified, "No property should be modified at this point / " + property.Name); + } + + CimProperty testProperty = cimInstance.CimInstanceProperties["Name"]; + testProperty.Value = "foo"; + Assert.True(testProperty.IsValueModified, "Test property should be marked as modified (test point #10)"); + testProperty.IsValueModified = false; + Assert.True(!testProperty.IsValueModified, "Test property should be marked as not modified (test point #12)"); + testProperty.IsValueModified = true; + Assert.True(testProperty.IsValueModified, "Test property should be marked as modified (test point #14)"); + } + } + + [TDDFact] + public void EnumerateInstances_IsValueModified_ValueEquality() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + CimInstance cimInstance = enumeratedInstances.FirstOrDefault(); + Assert.NotNull(cimInstance, "cimSession.EnumerateInstances returned some instances"); + + foreach (CimProperty property in cimInstance.CimInstanceProperties) + { + Assert.True(!property.IsValueModified, "No property should be modified at this point / " + property.Name); + } + + CimProperty testProperty = cimInstance.CimInstanceProperties["InstallDate"]; + object origValue = testProperty.Value; + Assert.Null(origValue, "Sanity check - test assumes that InstallDate of first/idle/system process is null"); + + testProperty.IsValueModified = false; + Assert.True(!testProperty.IsValueModified, "Test property should be marked as not modified (test point #12)"); + Assert.Null(testProperty.Value, "Orig null value should be retained (test point #12)"); + + testProperty.IsValueModified = true; + Assert.True(testProperty.IsValueModified, "Test property should be marked as modified (test point #14)"); + Assert.Null(testProperty.Value, "Orig null value should be retained (test point #14)"); + } + } + + [TDDFact] + public void GetClass_Property_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + CimClass enumeratedClass = cimSession.GetClass(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_OSProcess", "CimClass.CimSystemProperties.ClassName returneded null"); + Assert.Throws(() => { + CimPropertyDeclaration prop = enumeratedClass.CimClassProperties[null]; + return prop; + }); + } + } + + [TDDFact] + public void GetClass_Method_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + CimClass enumeratedClass = cimSession.GetClass(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_OSProcess", "CimClass.CimSystemProperties.ClassName returneded null"); + Assert.Throws(() => { + CimMethodDeclaration method = enumeratedClass.CimClassMethods[null]; + return method; + }); + } + } + + [TDDFact] + public void GetClass_MethodParameter_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + CimClass enumeratedClass = cimSession.GetClass(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_OSProcess", "CimClass.CimSystemProperties.ClassName returneded null"); + CimMethodDeclaration method = enumeratedClass.CimClassMethods["Create"]; + Assert.Throws(() => + { + CimMethodParameterDeclaration param = method.Parameters[null]; + return param; + }); + } + } + + [TDDFact] + public void GetClass_MethodParameterQualifier_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + CimClass enumeratedClass = cimSession.GetClass(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_OSProcess", "CimClass.CimSystemProperties.ClassName returneded null"); + Assert.Throws(() => + { + CimMethodDeclaration method = enumeratedClass.CimClassMethods["Create"]; + CimMethodParameterDeclaration param = method.Parameters["CommandLine"]; + CimQualifier qualifier = param.Qualifiers[null]; + return qualifier; + }); + } + } + + [TDDFact] + public void GetClass_PropertyQualifier_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + CimClass enumeratedClass = cimSession.GetClass(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_OSProcess", "CimClass.CimSystemProperties.ClassName returneded null"); + Assert.Throws(() => + { + CimPropertyDeclaration prop = enumeratedClass.CimClassProperties["CommandLine"]; + CimQualifier qualifier = prop.Qualifiers[null]; + return qualifier; + }); + } + } + + [TDDFact] + public void GetClassMethod() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimClass enumeratedClass = cimSession.GetClass(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_OSProcess", "CimClass.CimSystemProperties.ClassName returneded null"); + Assert.NotNull(enumeratedClass.CimClassMethods, "CimClass.CimClassMethods returneded null"); + Assert.NotNull(enumeratedClass.CimClassMethods["Create"], @"CimClass.CimClassMethods[Create] returneded null"); + //method qualifier + Assert.NotNull(enumeratedClass.CimClassMethods["Create"].Qualifiers, @"CimClass.CimClassMethods[Create].CimClassQualifiers returneded null"); + Assert.NotNull(enumeratedClass.CimClassMethods["Create"].Qualifiers["static"], @"CimClass.CimClassMethods[Create].CimClassQualifiers[static] returneded null"); + Assert.Equal((Boolean)enumeratedClass.CimClassMethods["Create"].Qualifiers["static"].Value, true, @"CimClass.CimClassMethods[Create].CimClassQualifiers[static].Value is not true"); + //method parameter + Assert.NotNull(enumeratedClass.CimClassMethods["Create"].Parameters, @"CimClass.CimClassMethods[Create].Parameters returneded null"); + Assert.NotNull(enumeratedClass.CimClassMethods["Create"].Parameters["CommandLine"], @"CimClass.CimClassMethods[Create].Parameters[CommandLine] returneded null"); + Assert.Equal(enumeratedClass.CimClassMethods["Create"].Parameters["CommandLine"].Name, "CommandLine", @"CimClass.CimClassMethods[Create].Parameters[CommandLine].Name returneded null"); + //Method parameter qualifier + Assert.NotNull(enumeratedClass.CimClassMethods["Create"].Parameters["CommandLine"].Qualifiers, @"CimClass.CimClassMethods[Create].Parameters[CommandLine].CimClassQualifiers returneded null"); + Assert.NotNull(enumeratedClass.CimClassMethods["Create"].Parameters["CommandLine"].Qualifiers["ID"], @"CimClass.CimClassMethods[Create].Parameters[CommandLine].CimClassQualifiers[ID returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassMethods["Create"].Parameters["CommandLine"].Qualifiers["ID"].CimType, CimType.SInt32, @"CimClass.CimClassMethods[Create].Parameters[CommandLine].CimClassQualifiers[ID returneded null"); + } + } + + [TDDFact] + public void GetClassSync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimClass enumeratedClass = cimSession.GetClass(@"root\cimv2", "CIM_Process"); + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_Process", "CimClass.CimSystemProperties.ClassName returneded null"); + Assert.Equal((string)enumeratedClass.CimSuperClassName, "CIM_LogicalElement", "CimClass.CimSuperClassName returneded null"); + //Assert.NotNull(enumeratedClass.CimSuperClass, "CimClass.CimSuperClassName returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.Namespace, @"root/cimv2", "CimClass.CimSystemProperties.Namespace returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties, "CimClass.CimClassProperties returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties["Handle"], @"CimClass.CimClassProperties[Handle] returneded null"); + + Assert.Equal((string)enumeratedClass.CimClassProperties["Handle"].Name, "Handle", @"CimClass.CimClassProperties[Handle].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["Handle"].CimType, CimType.String, @"CimClass.CimClassProperties[Handle].type returneded null"); + // Assert.Equal(enumeratedClass.CimClassProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, @"CimClass.CimClassProperties[Handle].Flags returneded null"); + + Assert.NotNull(enumeratedClass.CimClassProperties["Handle"].Qualifiers, @"CimClass.CimClassProperties[Handle].Qualifiers returneded null"); + Assert.Equal((string)enumeratedClass.CimClassProperties["Handle"].Qualifiers["read"].Name, "read", @"CimClass.CimClassProperties[Handle].Qualifiers[Cim_Key].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["Handle"].Qualifiers["read"].CimType, CimType.Boolean, @"CimClass.CimClassProperties[Handle].Qualifiers[read].Type returneded null"); + //Assert.Equal(enumeratedClass.CimClassProperties["Handle"].CimClassQualifiers["read"].Flags & CimFlags.DisableOverride, CimFlags.DisableOverride, @"CimClass.CimClassProperties[Handle].CimClassQualifiers[read].Flags returneded null"); + //Assert.Equal((bool)enumeratedClass.CimClassProperties["Handle"].CimClassQualifiers["read"].Value, true, @"CimClass.CimClassProperties[Handle].CimClassQualifiers[Cim_Key].Value returneded null"); + + //Check class qualifiers + Assert.NotNull(enumeratedClass.CimClassQualifiers, "CimClass.CimClassQualifiers returneded null"); + Assert.NotNull(enumeratedClass.CimClassQualifiers["Abstract"], "CimClass.CimClassQualifiers[Abstract] returneded null"); + Assert.Equal(enumeratedClass.CimClassQualifiers["Abstract"].Name, "Abstract", "CimClass.CimClassQualifiers[Abstract] returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassQualifiers["Abstract"].CimType, CimType.Boolean, @"enumeratedClass.CimClassQualifiers[Abstract].Type returneded null"); + //Assert.Equal(enumeratedClass.CimClassQualifiers["Abstract"].Flags & CimFlags.DisableOverride, CimFlags.DisableOverride, @"enumeratedClass.CimClassQualifiers[Abstract].Flags returneded null"); + + //Check System properties + //System properties Environment.MachineName + Assert.Equal(enumeratedClass.CimSystemProperties.Namespace, "root/cimv2", "cimInstance.CimSystemProperties.Namespace is not correct"); + Assert.Equal(enumeratedClass.CimSystemProperties.ClassName, "CIM_Process", "cimInstance.CimSystemProperties.ClassName is not correct"); + Assert.Equal(enumeratedClass.CimSystemProperties.ServerName, Environment.MachineName, "cimInstance.CimSystemProperties.ServerName is not correct"); + Assert.Null(enumeratedClass.CimSystemProperties.Path); + /*Assert.Equal(enumeratedClass.CimSystemProperties.Path, + "//" + Environment.MachineName + "/root/cimv2:CIM_Process", + "cimInstance.CimSystemProperties.Path is not correct " + enumeratedClass.CimSystemProperties.Path); + */ + } + } + /* + [Fact] + public void GetClassASync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable asyncInstance = cimSession.GetClassAsync(@"root\cimv2", "CIM_Process"); + List> asyncList = Helpers.ObservableToList(asyncInstance); + + Assert.Equal(asyncList.Count, 2, "Got 2 async callbacks"); + Assert.Equal(asyncList[0].Kind, AsyncItemKind.Item, "First callback for item"); + Assert.Equal(asyncList[1].Kind, AsyncItemKind.Completion, "Second callback for completion"); + CimClass enumeratedClass = asyncList[0].Item; + + + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.NotNull(enumeratedClass.CimSuperClass, "cimSession.CimSuperClass is null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_Process", "CimClass.CimSystemProperties.ClassName returneded null"); + Assert.Equal((string)enumeratedClass.CimSuperClassName, "CIM_LogicalElement", "CimClass.CimSuperClassName returneded null"); + Assert.Equal((string)enumeratedClass.CimSuperClassName, "CIM_LogicalElement", "CimClass.CimSuperClassName returneded null"); + //Assert.NotNull(enumeratedClass.CimSuperClass, "CimClass.CimSuperClassName returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.Namespace, @"root/cimv2", "CimClass.CimSystemProperties.Namespace returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties, "CimClass.CimClassProperties returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties["Handle"], @"CimClass.CimClassProperties[Handle] returneded null"); + Assert.Equal((string)enumeratedClass.CimClassProperties["Handle"].Name, "Handle", @"CimClass.CimClassProperties[Handle].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["Handle"].CimType, CimType.String, @"CimClass.CimClassProperties[Handle].type returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties["Handle"].Qualifiers, @"CimClass.CimClassProperties[Handle].Qualifiers returneded null"); + Assert.Equal((string)enumeratedClass.CimClassProperties["Handle"].Qualifiers["read"].Name, "read", @"CimClass.CimClassProperties[Handle].Qualifiers[Cim_Key].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["Handle"].Qualifiers["read"].CimType, CimType.Boolean, @"CimClass.CimClassProperties[Handle].Qualifiers[read].Type returneded null"); + + + Assert.NotNull(enumeratedClass.CimClassProperties, "CimClass.CimClassProperties returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties["Handle"], @"CimClass.CimClassProperties[Handle] returneded null"); + Assert.Equal((string)enumeratedClass.CimClassProperties["Handle"].Name, "Handle", @"CimClass.CimClassProperties[Handle].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["Handle"].CimType, CimType.String, @"CimClass.CimClassProperties[Handle].type returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties["Handle"].Qualifiers, @"CimClass.CimClassProperties[Handle].Qualifiers returneded null"); + Assert.Equal((string)enumeratedClass.CimClassProperties["Handle"].Qualifiers["read"].Name, "read", @"CimClass.CimClassProperties[Handle].Qualifiers[Cim_Key].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["Handle"].Qualifiers["read"].CimType, CimType.Boolean, @"CimClass.CimClassProperties[Handle].Qualifiers[read].Type returneded null"); + + + + // Assert.Equal(enumeratedClass.CimClassProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, @"CimClass.CimClassProperties[Handle].Flags returneded null"); + + //Assert.Equal(enumeratedClass.CimClassProperties["Handle"].CimClassQualifiers["read"].Flags & CimFlags.DisableOverride, CimFlags.DisableOverride, @"CimClass.CimClassProperties[Handle].CimClassQualifiers[read].Flags returneded null"); + //Assert.Equal((bool)enumeratedClass.CimClassProperties["Handle"].CimClassQualifiers["read"].Value, true, @"CimClass.CimClassProperties[Handle].CimClassQualifiers[Cim_Key].Value returneded null"); + + //Check class qualifiers + Assert.NotNull(enumeratedClass.CimClassQualifiers, "CimClass.CimClassQualifiers returneded null"); + Assert.NotNull(enumeratedClass.CimClassQualifiers["Abstract"], "CimClass.CimClassQualifiers[Abstract] returneded null"); + Assert.Equal(enumeratedClass.CimClassQualifiers["Abstract"].Name, "Abstract", "CimClass.CimClassQualifiers[Abstract] returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassQualifiers["Abstract"].CimType, CimType.Boolean, @"enumeratedClass.CimClassQualifiers[Abstract].Type returneded null"); + + //Check class qualifiers + Assert.NotNull(enumeratedClass.CimClassQualifiers, "CimClass.CimClassQualifiers returneded null"); + Assert.NotNull(enumeratedClass.CimClassQualifiers["Abstract"], "CimClass.CimClassQualifiers[Abstract] returneded null"); + Assert.Equal(enumeratedClass.CimClassQualifiers["Abstract"].Name, "Abstract", "CimClass.CimClassQualifiers[Abstract] returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassQualifiers["Abstract"].CimType, CimType.Boolean, @"enumeratedClass.CimClassQualifiers[Abstract].Type returneded null"); + + //Assert.Equal(enumeratedClass.CimClassQualifiers["Abstract"].Flags & CimFlags.DisableOverride, CimFlags.DisableOverride, @"enumeratedClass.CimClassQualifiers[Abstract].Flags returneded null"); + + Assert.Equal(asyncList.Last().Kind, AsyncItemKind.Completion, "Got OnCompleted callback"); + + } + } + */ + [TDDFact] + public void EnumerateClassesSync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedClassList = cimSession.EnumerateClasses(@"root\cimv2", "CIM_LogicalElement"); + Assert.NotNull(enumeratedClassList, "cimSession.EnumerateInstances returned something other than null"); + Assert.True(enumeratedClassList.Count() > 0, "Got some results back from CimSession.EnumerateInstances"); + + IEnumerator enumerator = enumeratedClassList.GetEnumerator(); + CimClass enumeratedClass = null; + while (enumerator.MoveNext()) + { + if (string.Compare(((CimClass)enumerator.Current).CimSystemProperties.ClassName, "CIM_OSProcess", StringComparison.OrdinalIgnoreCase) == 0) + { + enumeratedClass = (CimClass)enumerator.Current; + } + } + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_OSProcess", "CimClass.CimSystemProperties.ClassName returneded null"); + //Assert.Equal((string)enumeratedClass.CimSuperClassName, "CIM_OSProcess", "CimClass.CimSuperClassName returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.Namespace, @"root/cimv2", "CimClass.CimSystemProperties.Namespace returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties, "CimClass.CimClassProperties returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties["HandleCount"], @"CimClass.CimClassProperties[Handle] returneded null"); + + Assert.Equal((string)enumeratedClass.CimClassProperties["HandleCount"].Name, "HandleCount", @"CimClass.CimClassProperties[Handle].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["HandleCount"].CimType, CimType.UInt32, @"CimClass.CimClassProperties[HandleCount].type returneded null"); + // Assert.Equal(enumeratedClass.CimClassProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, @"CimClass.CimClassProperties[Handle].Flags returneded null"); + + Assert.NotNull(enumeratedClass.CimClassProperties["HandleCount"].Qualifiers, @"CimClass.CimClassProperties[HandleCount].Qualifiers returneded null"); + Assert.Equal((string)enumeratedClass.CimClassProperties["HandleCount"].Qualifiers["read"].Name, "read", @"CimClass.CimClassProperties[HandleCount].Qualifiers[Cim_Key].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["HandleCount"].Qualifiers["read"].CimType, CimType.Boolean, @"CimClass.CimClassProperties[HandleCount].Qualifiers[read].Type returneded null"); + // Assert.Equal(enumeratedClass.CimClassProperties["Handle"].CimClassQualifiers["read"].Flags & CimFlags.DisableOverride, CimFlags.DisableOverride, @"CimClass.CimClassProperties[Handle].CimClassQualifiers[read].Flags returneded null"); + //Assert.Equal((bool)enumeratedClass.CimClassProperties["Handle"].CimClassQualifiers["read"].Value, true, @"CimClass.CimClassProperties[Handle].CimClassQualifiers[Cim_Key].Value returneded null"); + + //Check class qualifiers + Assert.NotNull(enumeratedClass.CimClassQualifiers, "CimClass.CimClassQualifiers returneded null"); + Assert.NotNull(enumeratedClass.CimClassQualifiers["dynamic"], "CimClass.CimClassQualifiers[dynamic] returneded null"); + Assert.Equal(enumeratedClass.CimClassQualifiers["dynamic"].Name, "dynamic", "CimClass.CimClassQualifiers[dynamic] returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassQualifiers["dynamic"].CimType, CimType.Boolean, @"enumeratedClass.CimClassQualifiers[dynamic].Type returneded null"); + //Assert.Equal(enumeratedClass.CimClassQualifiers["Abstract"].Flags & CimFlags.DisableOverride, CimFlags.DisableOverride, @"enumeratedClass.CimClassQualifiers[Abstract].Flags returneded null"); + + } + } + /* + [Fact] + public void EnumerateClassesASync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable asyncInstance = cimSession.EnumerateClassesAsync(@"root\cimv2", "CIM_LogicalElement"); + List> asyncList = Helpers.ObservableToList(asyncInstance); + + Assert.True(asyncList.Count > 50, "Got less than 50 async callbacks"); + Assert.Equal(asyncList[0].Kind, AsyncItemKind.Item, "First callback for item"); + CimClass enumeratedClass = null; + foreach (AsyncItem item in asyncList) + { + if (item.Kind == AsyncItemKind.Item) + { + if (string.Compare(item.Item.CimSystemProperties.ClassName, "CIM_OSProcess", StringComparison.OrdinalIgnoreCase) == 0) + { + enumeratedClass = item.Item; + break; + } + } + } + + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.ClassName, "CIM_OSProcess", "CimClass.CimSystemProperties.ClassName returneded null"); + //Assert.Equal((string)enumeratedClass.CimSuperClassName, "CIM_OSProcess", "CimClass.CimSuperClassName returneded null"); + Assert.Equal((string)enumeratedClass.CimSystemProperties.Namespace, @"root/cimv2", "CimClass.CimSystemProperties.Namespace returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties, "CimClass.CimClassProperties returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties["HandleCount"], @"CimClass.CimClassProperties[Handle] returneded null"); + + Assert.Equal((string)enumeratedClass.CimClassProperties["HandleCount"].Name, "HandleCount", @"CimClass.CimClassProperties[Handle].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["HandleCount"].CimType, CimType.UInt32, @"CimClass.CimClassProperties[HandleCount].type returneded null"); + // Assert.Equal(enumeratedClass.CimClassProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, @"CimClass.CimClassProperties[Handle].Flags returneded null"); + + Assert.NotNull(enumeratedClass.CimClassProperties["HandleCount"].Qualifiers, @"CimClass.CimClassProperties[HandleCount].Qualifiers returneded null"); + Assert.Equal((string)enumeratedClass.CimClassProperties["HandleCount"].Qualifiers["read"].Name, "read", @"CimClass.CimClassProperties[HandleCount].Qualifiers[Cim_Key].Name returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassProperties["HandleCount"].Qualifiers["read"].CimType, CimType.Boolean, @"CimClass.CimClassProperties[HandleCount].Qualifiers[read].Type returneded null"); + // Assert.Equal(enumeratedClass.CimClassProperties["Handle"].CimClassQualifiers["read"].Flags & CimFlags.DisableOverride, CimFlags.DisableOverride, @"CimClass.CimClassProperties[Handle].CimClassQualifiers[read].Flags returneded null"); + //Assert.Equal((bool)enumeratedClass.CimClassProperties["Handle"].CimClassQualifiers["read"].Value, true, @"CimClass.CimClassProperties[Handle].CimClassQualifiers[Cim_Key].Value returneded null"); + + //Check class qualifiers + Assert.NotNull(enumeratedClass.CimClassQualifiers, "CimClass.CimClassQualifiers returneded null"); + Assert.NotNull(enumeratedClass.CimClassQualifiers["dynamic"], "CimClass.CimClassQualifiers[dynamic] returneded null"); + Assert.Equal(enumeratedClass.CimClassQualifiers["dynamic"].Name, "dynamic", "CimClass.CimClassQualifiers[dynamic] returneded null"); + Assert.Equal((CimType)enumeratedClass.CimClassQualifiers["dynamic"].CimType, CimType.Boolean, @"enumeratedClass.CimClassQualifiers[dynamic].Type returneded null"); + //Assert.Equal(enumeratedClass.CimClassQualifiers["Abstract"].Flags & CimFlags.DisableOverride, CimFlags.DisableOverride, @"enumeratedClass.CimClassQualifiers[Abstract].Flags returneded null"); + Assert.Equal(asyncList.Last().Kind, AsyncItemKind.Completion, "Got OnCompleted callback"); + + } + } + + [Fact] + public void TestConnectionSync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimInstance instance; + CimException exception; + bool bResult = cimSession.TestConnection(out instance, out exception); + Assert.Equal(bResult, true, "TestConnection Failed"); + Assert.Null(exception, "Unexpectidly for CIMException"); + } + } + + [Fact] + public void TestConnectionASync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable asyncInstance = cimSession.TestConnectionAsync(); + List> asyncList = Helpers.ObservableToList(asyncInstance); + + //COM doesn't return an instance + Assert.Equal(asyncList.Count, 1, "Got 2 async callbacks"); + Assert.Equal(asyncList[0].Kind, AsyncItemKind.Completion, "First callback for completion"); + } + } + */ + [TDDFact] + public void TestConnectionSyncRemote() + { + using (CimSession cimSession = CimSession.Create(@"ABCD")) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimInstance instance; + CimException exception; + bool bResult = cimSession.TestConnection(out instance, out exception); + Assert.Equal(bResult, false, "TestConnection Failed"); + Assert.NotNull(exception, "Unexpectidly for CIMException"); + } + } + /* + [Fact] + public void TestConnectionASyncRemote() + { + using (CimSession cimSession = CimSession.Create(@"ABCD")) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable asyncInstance = cimSession.TestConnectionAsync(); + List> asyncList = Helpers.ObservableToList(asyncInstance); + + //COM doesn't return an instance + Assert.Equal(asyncList.Count, 1, "Got 2 async callbacks"); + Assert.Equal(asyncList[0].Kind, AsyncItemKind.Exception, "Got OnError callback"); + Assert.True(asyncList[0].Exception.GetType().Equals(typeof(CimException)), "Got right type of exception back"); + } + } + */ + [TDDFact] + public void EnumerateInstances_ReturnedProperties() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + List enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "CIM_OSProcess").ToList(); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + + CimInstance currentProcess = enumeratedInstances.Single(x => (UInt32)(x.CimInstanceProperties["ProcessId"].Value) == Process.GetCurrentProcess().Id); + Assert.NotNull(currentProcess, "cimSession.EnumerateInstances(..., Win32_Process) found the current process"); + Assert.Equal(currentProcess.CimSystemProperties.ServerName, Environment.MachineName, "Got correct CimInstance.CimSystemProperties.ServerName"); + Assert.Equal(currentProcess.CimSystemProperties.ClassName, "Win32_Process", "Got correct CimInstance.CimSystemProperties.ClassName"); + Assert.True(Regex.IsMatch(currentProcess.CimSystemProperties.Namespace, "root.cimv2"), "Got correct CimInstance.CimSystemProperties.Namespace"); + + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Name, "Name", "currentProcess.CimInstanceProperties['Name'].Name is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].CimType, CimType.String, "currentProcess.CimInstanceProperties['Name'].CimType is correct"); + Assert.Equal((string)(currentProcess.CimInstanceProperties["Name"].Value), "ttest.exe", "currentProcess.CimInstanceProperties['Name'].Value is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Flags, CimFlags.Property | CimFlags.ReadOnly | CimFlags.NotModified, "currentProcess.CimInstanceProperties['Name'].Flags is correct"); + + Assert.Equal(currentProcess.CimInstanceProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, "currentProcess.CimInstanceProperties['Handle'].Flags includes CimFlags.Key"); + + Assert.True( + Regex.IsMatch(currentProcess.ToString(), "Win32_Process: ttest\\.exe \\(Handle = \"[0-9]*\"\\)", RegexOptions.IgnoreCase), + "currentProcess.ToString() returns expected value"); + } + } + /* + [Fact] + public void EnumerateInstances_CimClass() + { + using (CimSession cimSession = CimSession.Create(null)) + using (CimOperationOptions operationOptions = new CimOperationOptions()) + { + operationOptions.Flags = CimOperationFlags.FullTypeInformation; + Assert.NotNull(cimSession, "cimSession should not be null"); + List enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process", operationOptions).ToList(); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + + CimInstance currentProcess = enumeratedInstances.Single(x => (UInt32)(x.CimInstanceProperties["ProcessId"].Value) == Process.GetCurrentProcess().Id); + Assert.NotNull(currentProcess, "cimSession.EnumerateInstances(..., Win32_Process) found the current process"); + Assert.Equal(currentProcess.CimSystemProperties.ClassName, "Win32_Process", "Got correct CimInstance.CimSystemProperties.ClassName"); + + using (CimClass cimClass = currentProcess.CimClass) + { + Assert.NotNull(cimClass, "Got non-null cimClass"); + Assert.Equal(cimClass.CimSystemProperties.ClassName, "Win32_Process", "Got correct CimClass.CimSystemProperties.ClassName"); + Assert.NotNull(cimClass.CimSuperClass, "Got non-null parentClass"); + Assert.Equal(cimClass.CimSuperClass.CimSystemProperties.ClassName, "CIM_Process", "Got correct CimClass.CimSuperClass.CimSystemProperties.ClassName"); + Assert.Null(cimClass.CimClassQualifiers["nonExistantQualifier"], "Nonexistant qualifier returns null"); + Assert.Null(cimClass.CimClassProperties["nonExistantProperty"], "Nonexistant property returns null"); + Assert.Null(cimClass.CimClassMethods["nonExistantMethod"], "Nonexistant method returns null"); + } + } + } + */ + [TDDFact] + public void EnumerateInstances_SettingReceivedProperty() + { + using (CimSession cimSession = CimSession.Create(null)) + using (CimOperationOptions operationOptions = new CimOperationOptions()) + { + operationOptions.Flags = CimOperationFlags.FullTypeInformation; + Assert.NotNull(cimSession, "cimSession should not be null"); + List enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_DiskQuota", operationOptions).ToList(); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + + CimInstance diskQuota = enumeratedInstances.FirstOrDefault(); + Assert.NotNull(diskQuota, "cimSession.EnumerateInstances(..., Win32_DiskQuota) found a disk quota"); + Assert.Equal(diskQuota.CimSystemProperties.ClassName, "Win32_DiskQuota", "Got correct CimInstance.CimSystemProperties.ClassName"); + + // this used to fail because of bug #308968 + diskQuota.CimInstanceProperties["Limit"].Value = 123; + + Assert.Equal((UInt64)(diskQuota.CimInstanceProperties["Limit"].Value), (UInt64)123, "Win32_DiskQuota.Limit got changed locally"); + } + } + + [TDDFact] + public void EnumerateInstances_ResultsAreNotNull() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstances returned something other than null"); + + bool atLeastOneInstance = false; + foreach (CimInstance cimInstance in enumeratedInstances) + { + Assert.NotNull(cimInstance, "cimSession.EnumerateInstances returned something other than null"); + atLeastOneInstance = true; + } + Assert.True(atLeastOneInstance, "cimSession.EnumerateInstances returned some instances"); + } + } + + + private class EnumerateInstances_Cancellation_FromTwoThreads_Helper : IObserver + { + private IDisposable observableSubscription; + private ManualResetEventSlim onNextEvent = new ManualResetEventSlim(initialState: false); + private CancellationTokenSource cts; + + public EnumerateInstances_Cancellation_FromTwoThreads_Helper(CancellationTokenSource cts) + { + this.cts = cts; + } + + public void WaitForOnNext() + { + this.onNextEvent.Wait(); + } + + public void DisposeSubscription() + { + this.observableSubscription.Dispose(); + } + + public void Subscribe(IObservable observable) + { + observableSubscription = observable.Subscribe(this); + } + + public void OnNext(CimInstance value) + { + Thread.Sleep(TimeSpan.FromMilliseconds(500)); + this.onNextEvent.Set(); + Thread.Sleep(TimeSpan.FromMilliseconds(500)); + //this.DisposeSubscription(); + cts.Cancel(); + } + + public void OnError(Exception error) + { + } + + public void OnCompleted() + { + } + } + + [TDDFact] + public void EnumerateInstances_Cancellation_FromTwoThreads() + { + Console.WriteLine(); + using (CimSession cimSession = CimSession.Create(null)) + { + CancellationTokenSource cts = new CancellationTokenSource(); + CimOperationOptions oo = new CimOperationOptions() { CancellationToken = cts.Token }; + IObservable observable = cimSession.EnumerateInstancesAsync("root/cimv2", "Win32_Process", oo); + EnumerateInstances_Cancellation_FromTwoThreads_Helper observer = new EnumerateInstances_Cancellation_FromTwoThreads_Helper(cts); + observer.Subscribe(observable); + observer.WaitForOnNext(); + observer.DisposeSubscription(); + //cts.Cancel(); + } + } + + [TDDFact] + public void EnumerateInstances_SecondEnumeration() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IEnumerable enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process"); + + int count1 = enumeratedInstances.Count(); + Assert.True(count1 > 0, "count1 > 0"); + + int count2 = enumeratedInstances.Count(); + Assert.True(count2 > 0, "count2 > 0"); + + int floor = Math.Max(count1, count2) / 2; + Assert.True(count1 > floor, "count1 is reasonably close to count2"); + Assert.True(count2 > floor, "count2 is reasonably close to count1"); + } + } + /* + [Fact] + public void EnumerateInstancesAsync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable enumeratedInstances = cimSession.EnumerateInstancesAsync(@"root\cimv2", "Win32_Process"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstancesAsync returned something other than null"); + + List> listOfInstances = Helpers.ObservableToList(enumeratedInstances); + Assert.True(listOfInstances.Count > 0, "Got some results back from CimSession.EnumerateInstancesAsync"); + Assert.Equal(listOfInstances.Last().Kind, AsyncItemKind.Completion, "Got OnCompleted callback"); + } + } + + private static void EnumerateInstancesAsync_AnotherAppDomain_RunTest() + { + CimSession cimSession = CimSession.Create(null); + IObservable enumeratedInstances = cimSession.EnumerateInstancesAsync(@"root\cimv2", "Win32_Process"); + Helpers.ObservableToList(enumeratedInstances); + } + + [Fact] + public void EnumerateInstancesAsync_AnotherAppDomain() + { + AppDomainSetup domainSetup = new AppDomainSetup + { + ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, + ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, + ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName, + LoaderOptimization = LoaderOptimization.MultiDomainHost + }; + + // To workaround problems with loading test code into the other appdomain + // I am just copying the DRTs assembly to the base directory (the directory where TTest.exe is) + try + { + File.Copy( + typeof(CimSessionTest).Assembly.Location, + Path.Combine( + domainSetup.ApplicationBase, Path.GetFileName(typeof(CimSessionTest).Assembly.Location)), + overwrite: true); + } + catch (IOException) + { + } + + AppDomain anotherAppDomain = AppDomain.CreateDomain("MyOtherAppDomain " + Guid.NewGuid(), null, domainSetup); + try + { + anotherAppDomain.DoCallBack(EnumerateInstancesAsync_AnotherAppDomain_RunTest); + } + finally + { + AppDomain.Unload(anotherAppDomain); + } + } + + [Fact] + public void EnumerateInstancesAsync_ClassName_NotFound() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable enumeratedInstances = cimSession.EnumerateInstancesAsync(@"root\cimv2", "NotExistantClass"); + var serializedResult = Helpers.ObservableToList(enumeratedInstances); + Assert.True(serializedResult.Count == 1, "Got some results back from CimSession.EnumerateInstancesAsync"); + Assert.Equal(serializedResult[0].Kind, AsyncItemKind.Exception, "Got OnError callback"); + Assert.True(serializedResult[0].Exception.GetType().Equals(typeof(CimException)), "Got right type of exception back"); + Assert.True(!string.IsNullOrWhiteSpace(serializedResult[0].Exception.StackTrace), "Exception has the stack trace filled in"); + } + } + */ + [Fact] + public void EnumerateInstancesAsync_ClassName_NotFound_SubscriptionIsLazy() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + cimSession.EnumerateInstancesAsync(@"root\cimv2", "NotExistantClass"); + } + } + /* + public void EnumerateInstancesAsync_Cancellation_ViaCancellationToken_AfterOperationEnds() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CimOperationOptions operationOptions = new CimOperationOptions { CancellationToken = cancellationTokenSource.Token }; + IObservable enumeratedInstances = cimSession.EnumerateInstancesAsync("this.TestNamespace", "TestClass_AllDMTFTypes", operationOptions); + + var serializedResult = Helpers.ObservableToList(enumeratedInstances); + Assert.True(serializedResult.Count > 0, "Got some results back from CimSession.EnumerateInstancesAsync"); + Assert.Equal(serializedResult.Last().Kind, AsyncItemKind.Completion, "Got OnCompleted callback"); + + cancellationTokenSource.Cancel(); + } + } + + [Fact] + public void EnumerateInstancesAsync_ResultsAreNotNull() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable enumeratedInstances = cimSession.EnumerateInstancesAsync(@"root\cimv2", "Win32_Process"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstancesAsync returned something other than null"); + + List> listOfInstances = Helpers.ObservableToList(enumeratedInstances); + Assert.True(listOfInstances.Count > 0, "Got some results back from CimSession.EnumerateInstancesAsync"); + Assert.Equal(listOfInstances.Last().Kind, AsyncItemKind.Completion, "Got OnCompleted callback"); + + bool atLeastOneInstance = false; + foreach (CimInstance cimInstance in listOfInstances.Where(i => i.Kind == AsyncItemKind.Item).Select(i => i.Item)) + { + Assert.NotNull(cimInstance, "cimSession.EnumerateInstancesAsync returned something other than null"); + atLeastOneInstance = true; + } + Assert.True(atLeastOneInstance, "cimSession.EnumerateInstancesAsync returned some instances"); + } + } + + [Fact] + public void EnumerateInstancesAsync_ReturnedProperties() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + IObservable enumeratedInstances = cimSession.EnumerateInstancesAsync(@"root\cimv2", "Win32_Process"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstancesAsync returned something other than null"); + + List> listOfInstances = Helpers.ObservableToList(enumeratedInstances); + Assert.True(listOfInstances.Count > 0, "Got some results back from CimSession.EnumerateInstancesAsync"); + Assert.Equal(listOfInstances.Last().Kind, AsyncItemKind.Completion, "Got OnCompleted callback"); + + CimInstance currentProcess = listOfInstances + .Where(i => i.Kind == AsyncItemKind.Item) + .Select(i => i.Item) + .Single(x => (UInt32)(x.CimInstanceProperties["ProcessId"].Value) == Process.GetCurrentProcess().Id); + + Assert.NotNull(currentProcess, "cimSession.EnumerateInstances(..., Win32_Process) found the current process"); + + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Name, "Name", "currentProcess.CimInstanceProperties['Name'].Name is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].CimType, CimType.String, "currentProcess.CimInstanceProperties['Name'].CimType is correct"); + Assert.Equal((string)(currentProcess.CimInstanceProperties["Name"].Value), "ttest.exe", "currentProcess.CimInstanceProperties['Name'].Value is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Flags, CimFlags.ReadOnly | CimFlags.Property | CimFlags.NotModified, "currentProcess.CimInstanceProperties['Name'].Flags is correct"); + + Assert.Equal(currentProcess.CimInstanceProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, "currentProcess.CimInstanceProperties['Handle'].Flags includes CimFlags.Key"); + } + } + + [Fact] + public void EnumerateInstancesAsync_SecondSubscription() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + IObservable enumeratedInstances = cimSession.EnumerateInstancesAsync(@"root\cimv2", "Win32_Process"); + Assert.NotNull(enumeratedInstances, "cimSession.EnumerateInstancesAsync returned something other than null"); + + int count1 = Helpers.ObservableToList(enumeratedInstances).Count; + Assert.True(count1 > 0, "count1 > 0"); + + int count2 = Helpers.ObservableToList(enumeratedInstances).Count; + Assert.True(count2 > 0, "count2 > 0"); + + int floor = Math.Max(count1, count2) / 2; + Assert.True(count1 > floor, "count1 is reasonably close to count2"); + Assert.True(count2 > floor, "count2 is reasonably close to count1"); + } + } + + [Fact] + public void GetInstance() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("Win32_Process"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + + CimInstance currentProcess = cimSession.GetInstance(@"root\cimv2", instanceId); + Assert.NotNull(currentProcess, "cimSession.GetInstance returned something other than null"); + Assert.NotNull(currentProcess.CimClass, "cimSession.CimClass is null"); + + Assert.True(currentProcess.CimInstanceProperties.Count > 1, "Got more than 1 property back from CimSession.GetInstance"); + + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Name, "Name", "currentProcess.CimInstanceProperties['Name'].Name is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].CimType, CimType.String, "currentProcess.CimInstanceProperties['Name'].CimType is correct"); + Assert.Equal((string)(currentProcess.CimInstanceProperties["Name"].Value), "ttest.exe", "currentProcess.CimInstanceProperties['Name'].Value is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Flags, CimFlags.Property | CimFlags.ReadOnly | CimFlags.NotModified, "currentProcess.CimInstanceProperties['Name'].Flags is correct"); + + Assert.Equal(currentProcess.CimInstanceProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, "currentProcess.CimInstanceProperties['Handle'].Flags includes CimFlags.Key"); + + Assert.True(currentProcess.CimInstanceProperties.Count > 1, "Got more than 1 property back from CimSession.GetInstance"); + + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Name, "Name", "currentProcess.CimInstanceProperties['Name'].Name is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].CimType, CimType.String, "currentProcess.CimInstanceProperties['Name'].CimType is correct"); + Assert.Equal((string)(currentProcess.CimInstanceProperties["Name"].Value), "ttest.exe", "currentProcess.CimInstanceProperties['Name'].Value is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Flags, CimFlags.Property | CimFlags.ReadOnly | CimFlags.NotModified, "currentProcess.CimInstanceProperties['Name'].Flags is correct"); + + Assert.Equal(currentProcess.CimInstanceProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, "currentProcess.CimInstanceProperties['Handle'].Flags includes CimFlags.Key"); + + //System properties Environment.MachineName + Assert.Equal(currentProcess.CimSystemProperties.Namespace, "root/cimv2", "cimInstance.CimSystemProperties.Namespace is not correct"); + Assert.Equal(currentProcess.CimSystemProperties.ClassName, "Win32_Process", "cimInstance.CimSystemProperties.ClassName is not correct"); + Assert.Equal(currentProcess.CimSystemProperties.ServerName, Environment.MachineName, "cimInstance.CimSystemProperties.ServerName is not correct"); + Assert.Null(currentProcess.CimSystemProperties.Path); + + Assert.Equal(currentProcess.CimSystemProperties.Path, + "//" + Environment.MachineName + "/root/cimv2:Win32_Process.Handle=\"" + (currentProcess.CimInstanceProperties["Handle"].Value).ToString() + "\"", + "cimInstance.CimSystemProperties.Path is not correct " + currentProcess.CimSystemProperties.Path); + + } + } + + [Fact] + public void GetInstanceAsync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("Win32_Process"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + + IObservable asyncInstance = cimSession.GetInstanceAsync(@"root\cimv2", instanceId); + List> asyncList = Helpers.ObservableToList(asyncInstance); + Assert.Equal(asyncList.Count, 2, "Got 2 async callbacks"); + Assert.Equal(asyncList[0].Kind, AsyncItemKind.Item, "First callback for item"); + Assert.Equal(asyncList[1].Kind, AsyncItemKind.Completion, "Second callback for completion"); + + CimInstance currentProcess = asyncList[0].Item; + Assert.NotNull(currentProcess, "cimSession.GetInstance returned something other than null"); + + Assert.True(currentProcess.CimInstanceProperties.Count > 1, "Got more than 1 property back from CimSession.GetInstance"); + + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Name, "Name", "currentProcess.CimInstanceProperties['Name'].Name is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].CimType, CimType.String, "currentProcess.CimInstanceProperties['Name'].CimType is correct"); + Assert.Equal((string)(currentProcess.CimInstanceProperties["Name"].Value), "ttest.exe", "currentProcess.CimInstanceProperties['Name'].Value is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Flags, CimFlags.Property | CimFlags.ReadOnly | CimFlags.NotModified, "currentProcess.CimInstanceProperties['Name'].Flags is correct"); + + Assert.Equal(currentProcess.CimInstanceProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, "currentProcess.CimInstanceProperties['Handle'].Flags includes CimFlags.Key"); + } + } + */ + [TDDFact] + public void QueryInstances() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + string queryExpression = string.Format( + CultureInfo.InvariantCulture, + "SELECT * FROM Win32_Process WHERE ProcessId = {0}", + Process.GetCurrentProcess().Id); + + IEnumerable enumeratedInstances = cimSession.QueryInstances(@"root\cimv2", "WQL", queryExpression); + Assert.NotNull(enumeratedInstances, "cimSession.QueryInstances returned something other than null"); + + CimInstance currentProcess = enumeratedInstances.Single(); + + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Name, "Name", "currentProcess.CimInstanceProperties['Name'].Name is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].CimType, CimType.String, "currentProcess.CimInstanceProperties['Name'].CimType is correct"); + Assert.Equal((string)(currentProcess.CimInstanceProperties["Name"].Value), "ttest.exe", "currentProcess.CimInstanceProperties['Name'].Value is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Flags, CimFlags.Property | CimFlags.ReadOnly | CimFlags.NotModified, "currentProcess.CimInstanceProperties['Name'].Flags is correct"); + + Assert.Equal(currentProcess.CimInstanceProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, "currentProcess.CimInstanceProperties['Handle'].Flags includes CimFlags.Key"); + } + } + + + + [Fact] + public void QueryInstances_QueryDialect_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + string queryExpression = string.Format( + CultureInfo.InvariantCulture, + "SELECT * FROM Win32_Process WHERE ProcessId = {0}", + Process.GetCurrentProcess().Id); + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => { + return cimSession.QueryInstances(@"root\cimv2", null, queryExpression); + }); + } + } + + [Fact] + public void QueryInstances_QueryExpression_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.QueryInstances(@"root\cimv2", "WQL", null); + }); + } + } + + [TDDFact] + public void QueryInstances_CimClass() + { + using (CimSession cimSession = CimSession.Create(null)) + using (CimOperationOptions operationOptions = new CimOperationOptions()) + { + operationOptions.Flags = CimOperationFlags.FullTypeInformation; + string queryExpression = string.Format( + CultureInfo.InvariantCulture, + "SELECT * FROM Win32_Process WHERE ProcessId = {0}", + Process.GetCurrentProcess().Id); + + IEnumerable enumeratedInstances = cimSession.QueryInstances(@"root\cimv2", "WQL", queryExpression, operationOptions); + Assert.NotNull(enumeratedInstances, "cimSession.QueryInstances returned something other than null"); + + using (CimInstance currentProcess = enumeratedInstances.Single()) + { + using (CimClass cimClass = currentProcess.CimClass) + { + Assert.NotNull(cimClass, "Got non-null cimClass"); + Assert.Equal(cimClass.CimSystemProperties.ClassName, "Win32_Process", "Got correct CimClass.CimSystemProperties.ClassName"); + using (CimClass superClass = cimClass.CimSuperClass) + { + Assert.NotNull(superClass, "Got non-null parentClass"); + Assert.Equal(superClass.CimSystemProperties.ClassName, "CIM_Process", "Got correct CimClass.CimSuperClass.CimSystemProperties.ClassName"); + } + } + + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Name, "Name", "currentProcess.CimInstanceProperties['Name'].Name is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].CimType, CimType.String, "currentProcess.CimInstanceProperties['Name'].CimType is correct"); + Assert.Equal((string)(currentProcess.CimInstanceProperties["Name"].Value), "ttest.exe", "currentProcess.CimInstanceProperties['Name'].Value is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Flags, CimFlags.Property | CimFlags.ReadOnly | CimFlags.NotModified, "currentProcess.CimInstanceProperties['Name'].Flags is correct"); + } + } + } + /* + private class ImpersonationObserver : IObserver + { + public ImpersonationObserver(CimSession cimSession, string queryExpression, bool useThreadPool) + { + this.cimSession = cimSession; + this.queryExpression = queryExpression; + this.useThreadPool = useThreadPool; + } + + private readonly ManualResetEventSlim testCompleted = new ManualResetEventSlim(initialState: false); + private readonly CimSession cimSession; + private readonly string queryExpression; + private readonly bool useThreadPool; + private int countOfCompletedOperations = 0; + + public void OnNext(CimInstance value) + { + Helpers.AssertRunningAsTestUser("in IObserver.OnNext callback"); + } + + public void OnError(Exception error) + { + } + + public void OnCompleted() + { + Helpers.AssertRunningAsTestUser("in IObserver.OnCompleted callback"); + + countOfCompletedOperations++; + if (countOfCompletedOperations >= 3) + { + this.testCompleted.Set(); + } + else + { + if (useThreadPool) + { + ThreadPool.QueueUserWorkItem( + delegate + { + Helpers.AssertRunningAsTestUser("in ThreadPool thread spawned from IObserver.OnCompleted callback"); + this.cimSession.QueryInstancesAsync("root/cimv2", "WQL", this.queryExpression). + Subscribe(this); + }); + } + else + { + this.cimSession.QueryInstancesAsync("root/cimv2", "WQL", this.queryExpression).Subscribe(this); + } + } + } + + public void WaitForEndOfTest() + { + this.testCompleted.Wait(); + } + } + + [Fact] + public void QueryInstancesAsync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + string queryExpression = string.Format( + CultureInfo.InvariantCulture, + "SELECT * FROM Win32_Process WHERE ProcessId = {0}", + Process.GetCurrentProcess().Id); + + IObservable enumeratedInstances = cimSession.QueryInstancesAsync(@"root\cimv2", "WQL", queryExpression); + Assert.NotNull(enumeratedInstances, "cimSession.QueryInstancesAsync returned something other than null"); + + List> asyncList = Helpers.ObservableToList(enumeratedInstances); + Assert.Equal(asyncList.Count, 2, "Got 2 async callbacks"); + Assert.Equal(asyncList[0].Kind, AsyncItemKind.Item, "First callback for item"); + Assert.Equal(asyncList[1].Kind, AsyncItemKind.Completion, "Second callback for completion"); + + CimInstance currentProcess = asyncList[0].Item; + Assert.NotNull(currentProcess, "cimSession.GetInstance returned something other than null"); + + Assert.True(currentProcess.CimInstanceProperties.Count > 1, "Got more than 1 property back from CimSession.GetInstance"); + + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Name, "Name", "currentProcess.CimInstanceProperties['Name'].Name is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].CimType, CimType.String, "currentProcess.CimInstanceProperties['Name'].CimType is correct"); + Assert.Equal((string)(currentProcess.CimInstanceProperties["Name"].Value), "ttest.exe", "currentProcess.CimInstanceProperties['Name'].Value is correct"); + Assert.Equal(currentProcess.CimInstanceProperties["Name"].Flags, CimFlags.Property | CimFlags.ReadOnly | CimFlags.NotModified, "currentProcess.CimInstanceProperties['Name'].Flags is correct"); + + Assert.Equal(currentProcess.CimInstanceProperties["Handle"].Flags & CimFlags.Key, CimFlags.Key, "currentProcess.CimInstanceProperties['Handle'].Flags includes CimFlags.Key"); + } + } + */ + [Fact] + public void QueryInstancesAsync_QueryDialect_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + string queryExpression = string.Format( + CultureInfo.InvariantCulture, + "SELECT * FROM Win32_Process WHERE ProcessId = {0}", + Process.GetCurrentProcess().Id); + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.QueryInstancesAsync(@"root\cimv2", null, queryExpression); + }); + } + } + + [Fact] + public void QueryInstancesAsync_QueryExpression_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.QueryInstancesAsync(@"root\cimv2", "WQL", null); + }); + } + } + + [TDDFact] + public void EnumerateAssociatedInstances() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("Win32_Process"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + + IEnumerable enumeratedFiles = cimSession.EnumerateAssociatedInstances( + @"root\cimv2", + instanceId, + "CIM_ProcessExecutable", + "CIM_DataFile", + "Dependent", + "Antecedent"); + Assert.NotNull(enumeratedFiles, "cimSession.EnumerateInstances returned something other than null"); + + List associatedFiles = enumeratedFiles.ToList(); + Assert.True(associatedFiles.Count > 0, "Got some results back from CimSession.EnumerateAssociatedInstances"); + Assert.True(associatedFiles.All(f => f.CimInstanceProperties["Name"].CimType == CimType.String), "Got correct type of 'Name' property"); + Assert.True( + null != associatedFiles.Single(f => ((string)(f.CimInstanceProperties["Name"].Value)).EndsWith("mi.dll", StringComparison.OrdinalIgnoreCase)), + "Associated files includes the DRTs dll"); + } + } + /* + [Fact] + public void EnumerateAssociatedInstancesAsync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + + IObservable observableFiles = cimSession.EnumerateAssociatedInstancesAsync( + @"root\cimv2", + instanceId, + "CIM_ProcessExecutable", + "CIM_DataFile", + "Dependent", + "Antecedent"); + Assert.NotNull(observableFiles, "cimSession.EnumerateInstances returned something other than null"); + + List> unraveledObservable = Helpers.ObservableToList(observableFiles); + Assert.True(unraveledObservable.Count > 0, "Got some results back from CimSession.EnumerateInstancesAsync"); + Assert.Equal(unraveledObservable.Last().Kind, AsyncItemKind.Completion, "Got OnCompleted callback"); + + List associatedFiles = unraveledObservable.Where(a => a.Kind == AsyncItemKind.Item).Select(a => a.Item).ToList(); + + Assert.True(associatedFiles.Count > 0, "Got some results back from CimSession.EnumerateAssociatedInstances"); + Assert.True(associatedFiles.All(f => f.CimInstanceProperties["Name"].CimType == CimType.String), "Got correct type of 'Name' property"); + + Assert.True( + null != associatedFiles.Single(f => ((string)(f.CimInstanceProperties["Name"].Value)).EndsWith("mi.dll", StringComparison.OrdinalIgnoreCase)), + "Associated files includes the DRTs dll"); + } + } + */ + [Fact] + public void EnumerateAssociatedInstances_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.EnumerateAssociatedInstances( + @"root\cimv2", + null, + "CIM_ProcessExecutable", + "CIM_DataFile", + "Dependent", + "Antecedent"); + }); + } + } + + [Fact] + public void EnumerateAssociatedInstancesAsync_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.EnumerateAssociatedInstancesAsync( + @"root\cimv2", + null, + "CIM_ProcessExecutable", + "CIM_DataFile", + "Dependent", + "Antecedent"); + }); + } + } + + [TDDFact] + public void EnumerateReferencingInstances() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + + IEnumerable enumeratedAssociations = cimSession.EnumerateReferencingInstances( + @"root\cimv2", + instanceId, + "CIM_ProcessExecutable", + "Dependent"); + Assert.NotNull(enumeratedAssociations, "cimSession.EnumerateInstances returned something other than null"); + + List associations = enumeratedAssociations.ToList(); + Assert.True(associations.Count > 0, "Got some results back from CimSession.EnumerateReferencingInstances"); + + Assert.True( + associations.All(a => a.CimInstanceProperties["Antecedent"].CimType == CimType.Reference), + "association.Antecedent is of a correct CimType"); + + List associatedFiles = associations + .Select(a => a.CimInstanceProperties["Antecedent"].Value) + .OfType() + .ToList(); + + Assert.True(associatedFiles.Count > 0, "Got some results back from CimSession.EnumerateAssociatedInstances"); + Assert.True(associatedFiles.All(f => f.CimInstanceProperties["Name"].CimType == CimType.String), "Got correct type of 'Name' property"); + + Assert.True( + null != associatedFiles.Single(f => ((string)(f.CimInstanceProperties["Name"].Value)).EndsWith("mi.dll", StringComparison.OrdinalIgnoreCase)), + "Associated files includes the DRTs dll"); + + /* + foreach (var x in associatedFiles) + { + x.Dispose(); + } + */ + foreach (var x in associations) + { + x.Dispose(); + } + } + } + /* + [Fact] + public void EnumerateReferencingInstancesAsync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + + IObservable observableAssociations = cimSession.EnumerateReferencingInstancesAsync( + @"root\cimv2", + instanceId, + "CIM_ProcessExecutable", + "Dependent"); + Assert.NotNull(observableAssociations, "cimSession.EnumerateInstancesAsync returned something other than null"); + + List> unraveledObservable = Helpers.ObservableToList(observableAssociations); + Assert.True(unraveledObservable.Count > 0, "Got some results back from CimSession.EnumerateInstancesAsync"); + Assert.Equal(unraveledObservable.Last().Kind, AsyncItemKind.Completion, "Got OnCompleted callback"); + + List associations = unraveledObservable.Where(a => a.Kind == AsyncItemKind.Item).Select(a => a.Item).ToList(); + Assert.True(associations.Count > 0, "Got some results back from CimSession.EnumerateReferencingInstances"); + + Assert.True( + associations.All(a => a.CimInstanceProperties["Antecedent"].CimType == CimType.Reference), + "association.Antecedent is of a correct CimType"); + + List associatedFiles = associations + .Select(a => a.CimInstanceProperties["Antecedent"].Value) + .OfType() + .ToList(); + + Assert.True(associatedFiles.Count > 0, "Got some results back from CimSession.EnumerateAssociatedInstances"); + Assert.True(associatedFiles.All(f => f.CimInstanceProperties["Name"].CimType == CimType.String), "Got correct type of 'Name' property"); + + Assert.True( + null != associatedFiles.Single(f => ((string)(f.CimInstanceProperties["Name"].Value)).EndsWith("mi.dll", StringComparison.OrdinalIgnoreCase)), + "Associated files includes the DRTs dll"); + + } + } + */ + [Fact] + public void EnumerateReferencingInstances_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.EnumerateReferencingInstances( + @"root\cimv2", + null, + "CIM_ProcessExecutable", + "Dependent"); + }); + } + } + + [Fact] + public void EnumerateReferencingInstancesAsync_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.EnumerateReferencingInstancesAsync( + @"root\cimv2", + null, + "CIM_ProcessExecutable", + "Dependent"); + }); + } + } + + [Fact] + public void CreateInstance_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.CreateInstance(@"root\cimv2", null); + }); + } + } + + [Fact] + public void CreateInstanceAsync_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.CreateInstanceAsync(@"root\cimv2", null); + }); + } + } + + [Fact] + public void DeleteInstance_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + cimSession.DeleteInstance(@"root\cimv2", null); + return null; + }); + } + } + + [Fact] + public void DeleteInstance_Instance_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + Helpers.AssertException( + () => cimSession.DeleteInstance(null), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void DeleteInstanceAsync_Namespace_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + Assert.Null(instanceId.CimSystemProperties.Namespace, "Sanity check: instanceId.CimSystemProperties.Namespace == null"); + + Helpers.AssertException( + () => cimSession.DeleteInstanceAsync(instanceId), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void DeleteInstance_Namespace_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + Assert.Null(instanceId.CimSystemProperties.Namespace, "Sanity check: instanceId.CimSystemProperties.Namespace should be null"); + + Helpers.AssertException( + () => cimSession.DeleteInstance(instanceId), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void DeleteInstanceAsync_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.DeleteInstanceAsync(@"root\cimv2", null); + }); + } + } + + [Fact] + public void DeleteInstanceAsync_Instance_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + Helpers.AssertException( + () => cimSession.DeleteInstanceAsync(null), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void ModifyInstance_Namespace_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + Assert.Null(instanceId.CimSystemProperties.Namespace, "Sanity check: instanceId.CimSystemProperties.Namespace == null"); + + Helpers.AssertException( + () => cimSession.ModifyInstance(instanceId), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void ModifyInstance_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.ModifyInstance(@"root\cimv2", null); + }); + } + } + + [Fact] + public void ModifyInstance_Instance_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Helpers.AssertException( + () => cimSession.ModifyInstance(null), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void ModifyInstanceAsync_Namespace_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + Assert.Null(instanceId.CimSystemProperties.Namespace, "Sanity check: instanceId.CimSystemProperties.Namespace == null"); + Helpers.AssertException( + () => cimSession.ModifyInstanceAsync(instanceId), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void ModifyInstanceAsync_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.ModifyInstanceAsync(@"root\cimv2", null); + }); + } + } + + [Fact] + public void ModifyInstanceAsync_Instance_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Helpers.AssertException( + () => cimSession.ModifyInstanceAsync(null), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void InvokeInstanceMethod_Namespace_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + Assert.Null(instanceId.CimSystemProperties.Namespace, "Sanity check: instanceId.CimSystemProperties.Namespace == null"); + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Helpers.AssertException( + () => cimSession.InvokeMethod(instanceId, "MethodName", methodParameters), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [TDDFact] + public void InvokeInstanceMethod_SetSint32Value() + { + using (var cimSession = CimSession.Create(null)) + { + var cimInstance = new CimInstance("TestClass_AllDMTFTypes"); + cimInstance.CimInstanceProperties.Add(CimProperty.Create("v_Key", 123, CimType.UInt64, CimFlags.Key)); + cimInstance.CimInstanceProperties.Add(CimProperty.Create("v_sint32", 456, CimType.SInt32, CimFlags.None)); + + cimSession.CreateInstance("this.TestNamespace", cimInstance); + //this.AssertPresenceOfTestInstance(123, 456); + + CimMethodResult result; + using (var methodParameters = new CimMethodParametersCollection()) + { + Assert.Equal(methodParameters.Count, 0, "methodParameters.Count is correct"); + Assert.Equal(methodParameters.Count(), 0, "methodParameters.Count is correct"); + methodParameters.Add(CimMethodParameter.Create("Sint32Val", 789, CimType.SInt32, CimFlags.None)); + Assert.Equal(methodParameters.Count, 1, "methodParameters.Count is correct"); + Assert.Equal(methodParameters.Count(), 1, "methodParameters.Count is correct"); + result = cimSession.InvokeMethod("this.TestNamespace", cimInstance, "SetSint32Value", methodParameters); + } + Assert.NotNull(result, "CimSession.InvokeMethod returned non-null"); + Assert.Equal(result.ReturnValue.CimType, CimType.UInt32, "Got the right type of return value"); + object returnValue = result.ReturnValue.Value; + Assert.Equal((UInt32)returnValue, (uint)0, "Got the right return value"); + //this.AssertPresenceOfTestInstance(123, 789); + } + } + + [TDDFact] + public void InvokeStaticMethod_Add() + { + using (var cimSession = CimSession.Create(null)) + { + var methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create("Left", 123, CimType.SInt64, CimFlags.None)); + methodParameters.Add(CimMethodParameter.Create("Right", 456, CimType.SInt64, CimFlags.None)); + CimMethodResult result = cimSession.InvokeMethod("this.TestNamespace", "TestClass_MethodProvider_Calc", "Add", methodParameters); + + Assert.NotNull(result, "CimSession.InvokeMethod returned non-null"); + Assert.Equal(result.ReturnValue.CimType, CimType.UInt64, "Got the right type of return value"); + object returnValue = result.ReturnValue.Value; + Assert.Equal((UInt64)returnValue, (uint)0, "Got the right return value"); + + Assert.NotNull(result.OutParameters["sum"], "CimSession.InvokeMethod returned out parameter"); + Assert.Equal(result.OutParameters["sum"].CimType, CimType.SInt64, "CimSession.InvokeMethod returned right type of out parameter"); + object outParameterValue = result.OutParameters["sum"].Value; + Assert.Equal((Int64)outParameterValue, 123 + 456, "Got the right out parameter value"); + } + } + /* + [Fact] + public void InvokeStaticMethod_Add_InvalidParameterType() + { + using (var cimSession = CimSession.Create(null)) + { + var methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create("Left", 123, CimType.SInt64, CimFlags.None)); + methodParameters.Add(CimMethodParameter.Create("Right", "456", CimType.String, CimFlags.None)); + + Helpers.AssertException( + () => cimSession.InvokeMethod("this.TestNamespace", "TestClass_MethodProvider_Calc", "Add", methodParameters), + delegate (CimException cimException) + { + Assert.Equal(cimException.Message, "InvalidParameter", "Unlocalized enum value is not used as exception message"); + if (Thread.CurrentThread.CurrentCulture.DisplayName.Equals("en-US", StringComparison.OrdinalIgnoreCase)) + { + string lowerCaseMessage = cimException.Message.ToLowerInvariant(); + Assert.True(lowerCaseMessage.Contains("invalid"), "Message contains 'invalid' in English locale"); + Assert.True(lowerCaseMessage.Contains("parameter"), "Message contains 'parameter' in English locale"); + } + }); + } + } + */ + [TDDFact] + public void InvokeStreamingMethod_Sync() + { + using (var cimSession = CimSession.Create(null)) + { + var methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create("count", 3, CimType.UInt32, CimFlags.None)); + CimMethodResult result = cimSession.InvokeMethod("this.TestNamespace", "TestClass_Streaming", "StreamNumbers", methodParameters); + + Assert.NotNull(result, "CimSession.InvokeMethod returned non-null"); + Assert.Equal(result.ReturnValue.CimType, CimType.UInt32, "Got the right type of return value"); + object returnValue = result.ReturnValue.Value; + Assert.Equal((UInt32)returnValue, (uint)0, "Got the right return value"); + + Assert.NotNull(result.OutParameters["firstTen"], "CimSession.InvokeMethod returned out parameter"); + Assert.Equal(result.OutParameters["firstTen"].CimType, CimType.InstanceArray, "CimSession.InvokeMethod returned right type of out parameter"); + CimInstance[] outParameterValue = result.OutParameters["firstTen"].Value as CimInstance[]; + Assert.True(outParameterValue.All(v => v.CimSystemProperties.ClassName.Equals("Numbers", StringComparison.OrdinalIgnoreCase)), "Results have the right class name"); + Assert.True(outParameterValue.All(v => v.CimInstanceProperties["Numbers"] != null), "Results have 'Numbers' property"); + Assert.True(outParameterValue.All(v => v.CimInstanceProperties["Numbers"].CimType == CimType.SInt64Array), "Results have 'Numbers' property with correct type"); + + Assert.Equal(((long[])(outParameterValue[0].CimInstanceProperties["Numbers"].Value))[9], 10, "1st result is correct"); + Assert.Equal(((long[])(outParameterValue[1].CimInstanceProperties["Numbers"].Value))[9], 20, "2nd result is correct"); + Assert.Equal(((long[])(outParameterValue[2].CimInstanceProperties["Numbers"].Value))[9], 30, "3rd result is correct"); + } + } + /* + [Fact] + public void InvokeStreamingMethod_Async() + { + using (var cimSession = CimSession.Create(null)) + { + var operationOptions = new CimOperationOptions { EnableMethodResultStreaming = true }; + + var methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create("count", 3, CimType.UInt32, CimFlags.None)); + IObservable observable = cimSession.InvokeMethodAsync("this.TestNamespace", "TestClass_Streaming", "StreamNumbers", methodParameters, operationOptions); + Assert.NotNull(observable, "CimSession.InvokeMethod returned non-null"); + + List> result = Helpers.ObservableToList(observable); + Assert.True(result.Count > 0, "Got some callbacks"); + Assert.Equal(result[result.Count - 1].Kind, AsyncItemKind.Completion, "Got completion callback"); + + Assert.True(result.Count > 1, "Got more than 1 callback"); + Assert.Equal(result[result.Count - 2].Kind, AsyncItemKind.Item, "Got non-streamed result (presence)"); + Assert.True(result[result.Count - 2].Item.GetType().Equals(typeof(CimMethodResult)), "Got non-streamed result (type)"); + + Assert.True(result[0].Item.GetType().Equals(typeof(CimMethodStreamedResult)), "Got streamed result"); + Assert.Equal(((CimMethodStreamedResult)(result[0].Item)).ParameterName, "firstTen", "Streamed result has correct parameter name"); + Assert.Equal(((CimMethodStreamedResult)(result[0].Item)).ItemType, CimType.Instance, "Streamed result has correct type of item"); + + CimInstance item = (CimInstance)((CimMethodStreamedResult)(result[0].Item)).ItemValue; + Assert.NotNull(item.CimInstanceProperties["Numbers"], "Streamed result has 'Numbers' property (1)"); + Assert.Equal(item.CimInstanceProperties["Numbers"].CimType, CimType.SInt64Array, "Streamed result has 'Numbers' property of the correct type (1)"); + Assert.Equal(((long[])(item.CimInstanceProperties["Numbers"].Value))[9], 10, "Streamed result has 'Numbers' property with right value (1)"); + + item = (CimInstance)((CimMethodStreamedResult)(result[1].Item)).ItemValue; + Assert.NotNull(item.CimInstanceProperties["Numbers"], "Streamed result has 'Numbers' property (2)"); + Assert.Equal(item.CimInstanceProperties["Numbers"].CimType, CimType.SInt64Array, "Streamed result has 'Numbers' property of the correct type (2)"); + Assert.Equal(((long[])(item.CimInstanceProperties["Numbers"].Value))[9], 20, "Streamed result has 'Numbers' property with right value (2)"); + } + } + + [Fact] + public void InvokeStreamingMethod_Async_ServerSideStreamingOnly() + { + using (var cimSession = CimSession.Create(null)) + { + var methodParameters = new CimMethodParametersCollection(); + methodParameters.Add(CimMethodParameter.Create("count", 3, CimType.UInt32, CimFlags.None)); + IObservable observable = cimSession.InvokeMethodAsync("this.TestNamespace", "TestClass_Streaming", "StreamNumbers", methodParameters); + Assert.NotNull(observable, "CimSession.InvokeMethod returned non-null"); + + List> asyncResult = Helpers.ObservableToList(observable); + Assert.True(asyncResult.Count > 0, "Got some callbacks"); + Assert.Equal(asyncResult[asyncResult.Count - 1].Kind, AsyncItemKind.Completion, "Got completion callback"); + + Assert.True(asyncResult.Count == 2, "Got exactly one asyncResult"); + Assert.Equal(asyncResult[asyncResult.Count - 2].Kind, AsyncItemKind.Item, "Got non-streamed asyncResult (presence)"); + Assert.True(asyncResult[asyncResult.Count - 2].Item.GetType().Equals(typeof(CimMethodResult)), "Got non-streamed asyncResult (type)"); + + CimMethodResult result = asyncResult[asyncResult.Count - 2].Item; + + Assert.NotNull(result, "CimSession.InvokeMethod returned non-null"); + Assert.Equal(result.ReturnValue.CimType, CimType.UInt32, "Got the right type of return value"); + object returnValue = result.ReturnValue.Value; + Assert.Equal((UInt32)returnValue, (uint)0, "Got the right return value"); + + Assert.NotNull(result.OutParameters["firstTen"], "CimSession.InvokeMethod returned out parameter"); + Assert.Equal(result.OutParameters["firstTen"].CimType, CimType.InstanceArray, "CimSession.InvokeMethod returned right type of out parameter"); + CimInstance[] outParameterValue = result.OutParameters["firstTen"].Value as CimInstance[]; + Assert.True(outParameterValue.All(v => v.CimSystemProperties.ClassName.Equals("Numbers", StringComparison.OrdinalIgnoreCase)), "Results have the right class name"); + Assert.True(outParameterValue.All(v => v.CimInstanceProperties["Numbers"] != null), "Results have 'Numbers' property"); + Assert.True(outParameterValue.All(v => v.CimInstanceProperties["Numbers"].CimType == CimType.SInt64Array), "Results have 'Numbers' property with correct type"); + + Assert.Equal(((long[])(outParameterValue[0].CimInstanceProperties["Numbers"].Value))[9], 10, "1st result is correct"); + Assert.Equal(((long[])(outParameterValue[1].CimInstanceProperties["Numbers"].Value))[9], 20, "2nd result is correct"); + Assert.Equal(((long[])(outParameterValue[2].CimInstanceProperties["Numbers"].Value))[9], 30, "3rd result is correct"); + } + } + */ + [Fact] + public void InvokeInstanceMethod_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Assert.Throws(() => + { + return cimSession.InvokeMethod(@"root\cimv2", (CimInstance)null, "MethodName", methodParameters); + }); + } + } + + [Fact] + public void InvokeInstanceMethod_Instance_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Helpers.AssertException( + () => cimSession.InvokeMethod((CimInstance)null, "MethodName", methodParameters), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void InvokeInstanceMethod_MethodName_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Assert.Throws(() => + { + return cimSession.InvokeMethod(@"root\cimv2", instanceId, null, methodParameters); + }); + } + } + + [Fact] + public void InvokeInstanceMethodAsync_Namespace_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + Assert.Null(instanceId.CimSystemProperties.Namespace, "Sanity check: instanceId.CimSystemProperties.Namespace = null"); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Helpers.AssertException( + () => cimSession.InvokeMethodAsync(instanceId, "MethodAsyncName", methodParameters), + e => Assert.Equal(e.ParamName, "instance", "Got correct ArgumentNullException.ParamName")); + } + } + + [Fact] + public void InvokeInstanceMethodAsync_Instance_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Assert.Throws( + () => { + cimSession.InvokeMethodAsync(@"root\cimv2", (CimInstance)null, "MethodAsyncName", methodParameters); + return null; + }); + } + } + + [Fact] + public void InvokeInstanceMethodAsync_Instance_Null_NoNamespace() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Helpers.AssertException( + () => cimSession.InvokeMethodAsync((CimInstance)null, "MethodAsyncName", methodParameters), + e => Assert.Equal(e.ParamName, "instance", "Got correct A4rgumentNullException.ParamName")); + } + } + + [Fact] + public void InvokeInstanceMethodAsync_MethodAsyncName_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimInstance instanceId = new CimInstance("CIM_OSProcess"); + instanceId.CimInstanceProperties.Add(CimProperty.Create("Handle", Process.GetCurrentProcess().Id.ToString(), CimType.String, CimFlags.Key)); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Assert.Throws(() => + { + return cimSession.InvokeMethodAsync(@"root\cimv2", instanceId, null, methodParameters); + }); + } + } + + [Fact] + public void InvokeStaticMethod_MethodName_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Assert.Throws(() => + { + return cimSession.InvokeMethod(@"root\cimv2", "ClassName", null, methodParameters); + }); + } + } + + [Fact] + public void InvokeStaticMethodAsync_MethodName_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); + Assert.Throws(() => + { + return cimSession.InvokeMethodAsync(@"root\cimv2", "ClassName", null, methodParameters); + }); + } + } + + [TDDFact] + public void Subscribe() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimOperationOptions options = new CimOperationOptions(); + //options.Timeout = TimeSpan.FromMilliseconds(20000); + IEnumerable enumeratedFiles = cimSession.Subscribe( + @"root\cimv2", + "WQL", + @"Select * from CIM_OSProcessStartTrace", + options + ); + Assert.NotNull(enumeratedFiles, "cimSession.Subscribe returned something other than null"); + //Start a process here + IEnumerator iterator = enumeratedFiles.GetEnumerator(); + bool bGotInstance = false; + Thread.Sleep(3000); + Helpers.StartDummyProcess(); + + while (iterator.MoveNext()) + { + CimSubscriptionResult instance = iterator.Current; + Assert.True((instance.Instance.CimInstanceProperties["ProcessName"].CimType == CimType.String), "Got correct type of 'Name' property"); + bGotInstance = true; + iterator.Dispose(); + break; + } + Assert.True(bGotInstance, "Got some results back from CimSession.Subscribe"); + } + } + + [TDDFact] + public void Subscribe_DeliveryOptionsInterval() + { + using (CimSession cimSession = CimSession.Create(Environment.MachineName, new WSManSessionOptions())) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimSubscriptionDeliveryOptions options = new CimSubscriptionDeliveryOptions(CimSubscriptionDeliveryType.Pull); + options.SetInterval("__MI_SUBSCRIPTIONDELIVERYOPTIONS_SET_HEARTBEAT_INTERVAL", TimeSpan.FromSeconds(30), 0); + + //options.Timeout = TimeSpan.FromMilliseconds(20000); + IEnumerable enumeratedFiles = cimSession.Subscribe( + @"root\cimv2", + "WQL", + @"Select * from CIM_OSProcessStartTrace", + options + ); + Assert.NotNull(enumeratedFiles, "cimSession.Subscribe returned something other than null"); + //Start a process here + using (IEnumerator iterator = enumeratedFiles.GetEnumerator()) + { + bool bGotInstance = false; + Thread.Sleep(3000); + Helpers.StartDummyProcess(); + + while (iterator.MoveNext()) + { + CimSubscriptionResult instance = iterator.Current; + Assert.True( + (instance.Instance.CimInstanceProperties["ProcessName"].CimType == CimType.String), + "Got correct type of 'Name' property"); + bGotInstance = true; + break; + } + Assert.True(bGotInstance, "Got some results back from CimSession.Subscribe"); + } + } + } + + private void Subscribe_DeliveryOptionsDateTime_Core(CimSubscriptionDeliveryOptions options) + { + DateTime startTime = DateTime.UtcNow; + + using (CimSession cimSession = CimSession.Create(Environment.MachineName, new WSManSessionOptions())) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + //options.Timeout = TimeSpan.FromMilliseconds(20000); + IEnumerable enumeratedFiles = cimSession.Subscribe( + @"root\cimv2", + "WQL", + @"Select * from CIM_OSProcessStartTrace", + options + ); + Assert.NotNull(enumeratedFiles, "cimSession.Subscribe returned something other than null"); + //Start a process here + Helpers.AssertException( + delegate + { + using (IEnumerator iterator = enumeratedFiles.GetEnumerator()) + { + bool bGotInstance = false; + Thread.Sleep(3000); + Helpers.StartDummyProcess(); + + while (iterator.MoveNext()) + { + CimSubscriptionResult instance = iterator.Current; + Assert.True( + (instance.Instance.CimInstanceProperties["ProcessName"].CimType == + CimType.String), + "Got correct type of 'Name' property"); + bGotInstance = true; + } + Assert.True(bGotInstance, "Got some results back from CimSession.Subscribe"); + } + }, + delegate (CimException e) + { + Assert.True(e.NativeErrorCode == NativeErrorCode.Failed, "Got the expected NativeErrorCode"); + }); + } + + TimeSpan testDuration = DateTime.UtcNow - startTime; + Assert.True(testDuration > TimeSpan.FromSeconds(8), "Test should last more than 5 seconds"); + Assert.True(testDuration < TimeSpan.FromSeconds(60), "Test should last less than 60 seconds"); + } + + [TDDFact] + public void Subscribe_DeliveryOptionsDateTime_TimeSpan() + { + CimSubscriptionDeliveryOptions options = new CimSubscriptionDeliveryOptions(CimSubscriptionDeliveryType.Pull); + options.SetDateTime("__MI_SUBSCRIPTIONDELIVERYOPTIONS_SET_EXPIRATION_TIME", TimeSpan.FromSeconds(10), 0); + Subscribe_DeliveryOptionsDateTime_Core(options); + } + /* + [Fact] + public void SubscribeAsync() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CimOperationOptions options = new CimOperationOptions(); + //options.Timeout = TimeSpan.FromMilliseconds(20000); + options.CancellationToken = cancellationTokenSource.Token; + + IObservable observableFiles = cimSession.SubscribeAsync( + @"root\cimv2", + "WQL", + @"Select * from CIM_OSProcessStartTrace", + options + ); + Assert.NotNull(observableFiles, "cimSession.Subscribe returned something other than null"); + + AsyncItem unraveledObservable = Helpers.ObservableToSingleItem(observableFiles); + cancellationTokenSource.Cancel(); + Assert.True(unraveledObservable != null, "Did not get any instance back from CimSession.Subscribe"); + Assert.True((unraveledObservable.Item.Instance.CimInstanceProperties["ProcessName"].CimType == CimType.String), "Got correct type of 'Name' property"); + } + } + */ + [Fact] + public void Subscribe_Dialect_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + Assert.Throws(() => + { + return cimSession.Subscribe( + @"root\cimv2", + null, + @"Select * from __InstanceCreationEvent WITHIN 2 where TargetInstance isa 'CIM_OSProcess'"); + }); + } + } + + [Fact] + public void Subscribe_Query_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.Subscribe( + @"root\cimv2", + "WQL", + null); + }); + } + } + + [Fact] + public void SubscribeAsync_Dialect_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + Assert.Throws(() => + { + return cimSession.SubscribeAsync( + @"root\cimv2", + null, + @"Select * from __InstanceCreationEvent WITHIN 2 where TargetInstance isa 'CIM_OSProcess'"); + }); + } + } + + [Fact] + public void SubscribeAsync_Query_Null() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + + Assert.Throws(() => + { + return cimSession.SubscribeAsync( + @"root\cimv2", + "WQL", + null); + }); + } + } + + [TDDFact] + public void GetNonexistQualifer() + { + using (CimSession cimSession = CimSession.Create(null)) + { + Assert.NotNull(cimSession, "cimSession should not be null"); + CimClass enumeratedClass = cimSession.GetClass(@"root\cimv2", "CIM_OSProcess"); + Assert.NotNull(enumeratedClass, "cimSession.GetClass returneded null"); + + //Check non-exist class qualifiers + Assert.Null(enumeratedClass.CimClassQualifiers["nonexists"], "CimClass.CimClassQualifiers returneded not null"); + + //Check non-exist class property qualifiers + Assert.NotNull(enumeratedClass.CimClassProperties["Caption"], "enumeratedClass.CimClassProperties returneded null"); + Assert.NotNull(enumeratedClass.CimClassProperties["Caption"].Qualifiers, "enumeratedClass.CimClassProperties[Caption].Qualifiers returneded null"); + Assert.Null(enumeratedClass.CimClassProperties["Caption"].Qualifiers["nonexist"], "enumeratedClass.CimClassProperties[Caption].Qualifiers[nonexist] returneded not null"); + + //Check non-exist method qualifier + Assert.NotNull(enumeratedClass.CimClassMethods["Create"], @"CimClass.CimClassMethods[Create] returneded null"); + Assert.Null(enumeratedClass.CimClassMethods["Create"].Qualifiers["nonexist"], @"CimClass.CimClassMethods[Create].Qualifiers[nonexist] returneded not null"); + + //Check non-exist method parameter qualifier + Assert.NotNull(enumeratedClass.CimClassMethods["Create"].Parameters["CommandLine"].Qualifiers, @"CimClass.CimClassMethods[Create].Parameters[CommandLine].Qualifiers returneded null"); + Assert.Null(enumeratedClass.CimClassMethods["Create"].Parameters["CommandLine"].Qualifiers["nonexist"], @"CimClass.CimClassMethods[Create].Parameters[CommandLine].Qualifiers[nonexist] returneded not null"); + } + } } } \ No newline at end of file diff --git a/test/Microsoft.Management.Infrastructure.Tests/UnitTests/TestData/dscinstance.mof b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/TestData/dscinstance.mof index e3a178a..68924c6 100644 --- a/test/Microsoft.Management.Infrastructure.Tests/UnitTests/TestData/dscinstance.mof +++ b/test/Microsoft.Management.Infrastructure.Tests/UnitTests/TestData/dscinstance.mof @@ -111,6 +111,8 @@ Class MSFT_ConfigurationDocument "Configuration document Help URI." )] String HelpInfoUri; }; + + instance of MSFT_WindowsCredential as $x { UserName="AAA";