// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Xml.Linq; using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; namespace Microsoft.AspNetCore.DataProtection.KeyManagement { public class KeyEscrowServiceProviderExtensionsTests { [Fact] public void GetKeyEscrowSink_NullServiceProvider_ReturnsNull() { Assert.Null(((IServiceProvider)null).GetKeyEscrowSink()); } [Fact] public void GetKeyEscrowSink_EmptyServiceProvider_ReturnsNull() { // Arrange var services = new ServiceCollection().BuildServiceProvider(); // Act & assert Assert.Null(services.GetKeyEscrowSink()); } [Fact] public void GetKeyEscrowSink_SingleKeyEscrowRegistration_ReturnsAggregateOverSingleSink() { // Arrange List output = new List(); var mockKeyEscrowSink = new Mock(); mockKeyEscrowSink.Setup(o => o.Store(It.IsAny(), It.IsAny())) .Callback((keyId, element) => { output.Add(String.Format(CultureInfo.InvariantCulture, "{0:D}: {1}", keyId, element.Name.LocalName)); }); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(mockKeyEscrowSink.Object); var services = serviceCollection.BuildServiceProvider(); // Act var sink = services.GetKeyEscrowSink(); sink.Store(new Guid("39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b"), XElement.Parse("")); // Assert Assert.Equal(new[] { "39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement" }, output); } [Fact] public void GetKeyEscrowSink_MultipleKeyEscrowRegistration_ReturnsAggregate() { // Arrange List output = new List(); var mockKeyEscrowSink1 = new Mock(); mockKeyEscrowSink1.Setup(o => o.Store(It.IsAny(), It.IsAny())) .Callback((keyId, element) => { output.Add(String.Format(CultureInfo.InvariantCulture, "[sink1] {0:D}: {1}", keyId, element.Name.LocalName)); }); var mockKeyEscrowSink2 = new Mock(); mockKeyEscrowSink2.Setup(o => o.Store(It.IsAny(), It.IsAny())) .Callback((keyId, element) => { output.Add(String.Format(CultureInfo.InvariantCulture, "[sink2] {0:D}: {1}", keyId, element.Name.LocalName)); }); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(mockKeyEscrowSink1.Object); serviceCollection.AddSingleton(mockKeyEscrowSink2.Object); var services = serviceCollection.BuildServiceProvider(); // Act var sink = services.GetKeyEscrowSink(); sink.Store(new Guid("39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b"), XElement.Parse("")); // Assert Assert.Equal(new[] { "[sink1] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement", "[sink2] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement" }, output); } } }