MockExtensions.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using System.Xml.Linq;
  5. using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
  6. using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
  7. using Microsoft.AspNetCore.DataProtection.Internal;
  8. using Microsoft.AspNetCore.DataProtection.XmlEncryption;
  9. using Moq;
  10. namespace Microsoft.AspNetCore.DataProtection
  11. {
  12. internal static class MockExtensions
  13. {
  14. /// <summary>
  15. /// Sets up a mock such that given the name of a deserializer class and the XML node that class's
  16. /// Import method should expect returns a descriptor which produces the given authenticator.
  17. /// </summary>
  18. public static void ReturnAuthenticatedEncryptorGivenDeserializerTypeNameAndInput(this Mock<IActivator> mockActivator, string typeName, string xml, IAuthenticatedEncryptor encryptor)
  19. {
  20. mockActivator
  21. .Setup(o => o.CreateInstance(typeof(IAuthenticatedEncryptorDescriptorDeserializer), typeName))
  22. .Returns(() =>
  23. {
  24. var mockDeserializer = new Mock<IAuthenticatedEncryptorDescriptorDeserializer>();
  25. mockDeserializer
  26. .Setup(o => o.ImportFromXml(It.IsAny<XElement>()))
  27. .Returns<XElement>(el =>
  28. {
  29. // Only return the descriptor if the XML matches
  30. XmlAssert.Equal(xml, el);
  31. var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
  32. mockDescriptor.Setup(o => o.CreateEncryptorInstance()).Returns(encryptor);
  33. return mockDescriptor.Object;
  34. });
  35. return mockDeserializer.Object;
  36. });
  37. }
  38. /// <summary>
  39. /// Sets up a mock such that given the name of a decryptor class and the XML node that class's
  40. /// Decrypt method should expect returns the specified XML elmeent.
  41. /// </summary>
  42. public static void ReturnDecryptedElementGivenDecryptorTypeNameAndInput(this Mock<IActivator> mockActivator, string typeName, string expectedInputXml, string outputXml)
  43. {
  44. mockActivator
  45. .Setup(o => o.CreateInstance(typeof(IXmlDecryptor), typeName))
  46. .Returns(() =>
  47. {
  48. var mockDecryptor = new Mock<IXmlDecryptor>();
  49. mockDecryptor
  50. .Setup(o => o.Decrypt(It.IsAny<XElement>()))
  51. .Returns<XElement>(el =>
  52. {
  53. // Only return the descriptor if the XML matches
  54. XmlAssert.Equal(expectedInputXml, el);
  55. return XElement.Parse(outputXml);
  56. });
  57. return mockDecryptor.Object;
  58. });
  59. }
  60. }
  61. }