<commit_before>﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.ServiceModel;
using Helsenorge.Registries.Abstractions;
using Helsenorge.Registries.Mocks;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Helsenorge.Registries.Tests
{
	[TestClass]
	[DeploymentItem(@"Files", @"Files")]
	public class CollaborationRegistryTests
	{
		private CollaborationProtocolRegistryMock _registry;
		private LoggerFactory _loggerFactory;
		private ILogger _logger;

		[TestInitialize]
		public void Setup()
		{
			var settings = new CollaborationProtocolRegistrySettings()
			{
				UserName = "username",
				Password = "password",
				EndpointName = "BasicHttpBinding_ICommunicationPartyService",
				WcfConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None),
				CachingInterval = TimeSpan.FromSeconds(5),
				MyHerId = 93238 // matches a value in a CPA test file
			};

			_loggerFactory = new LoggerFactory();
			_loggerFactory.AddDebug();
			_logger = _loggerFactory.CreateLogger<CollaborationRegistryTests>();

			var memoryCache = new MemoryCache(new MemoryCacheOptions());
			var distributedCache = new MemoryDistributedCache(memoryCache);

			_registry = new CollaborationProtocolRegistryMock(settings, distributedCache);
			_registry.SetupFindAgreementById(i =>
			{
				var file = Path.Combine("Files", $"CPA_{i:D}.xml");
				return File.Exists(file) == false ? null : File.ReadAllText(file);
			});
			_registry.SetupFindAgreementForCounterparty(i =>
			{
				var file = Path.Combine("Files", $"CPA_{i}.xml");
				return File.Exists(file) == false ? null : File.ReadAllText(file);
			});
			_registry.SetupFindProtocolForCounterparty(i =>
			{
				if (i < 0)
				{
					throw new FaultException(new FaultReason("Dummy fault from mock"));
				}
				var file = Path.Combine("Files", $"CPP_{i}.xml");
				return File.Exists(file) == false ? null : File.ReadAllText(file);
			});
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void Constructor_Settings_Null()
		{
			var memoryCache = new MemoryCache(new MemoryCacheOptions());
			var distributedCache = new MemoryDistributedCache(memoryCache);

			new CollaborationProtocolRegistry(null, distributedCache);
		}
		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void Constructor_Cache_Null()
		{
			new CollaborationProtocolRegistry(new CollaborationProtocolRegistrySettings(), null);
		}

		[TestMethod]
		public void Read_CollaborationProfile()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.AreEqual(profile.CpaId, Guid.Empty);
			Assert.AreEqual("Digitale innbyggertjenester", profile.Name);
			Assert.AreEqual(14, profile.Roles.Count);
			Assert.IsNotNull(profile.SignatureCertificate);
			Assert.IsNotNull(profile.EncryptionCertificate);

			var role = profile.Roles[0];
			Assert.AreEqual("DIALOG_INNBYGGER_DIGITALBRUKERreceiver", role.Name);
			Assert.AreEqual("1.1", role.VersionString);
			Assert.AreEqual(new Version(1, 1), role.Version);
			Assert.AreEqual(2, role.ReceiveMessages.Count);
			Assert.AreEqual(2, role.SendMessages.Count);
			var message = role.ReceiveMessages[0];
			Assert.AreEqual("DIALOG_INNBYGGER_DIGITALBRUKER", message.Name);
			Assert.AreEqual("sb.test.nhn.no/DigitalDialog/93238_async", message.DeliveryChannel);
			Assert.AreEqual(DeliveryProtocol.Amqp, message.DeliveryProtocol);

			var part = message.Parts.First();
			Assert.AreEqual(1, part.MaxOccurrence);
			Assert.AreEqual(0, part.MinOccurrence);
			Assert.AreEqual("http://www.kith.no/xmlstds/msghead/2006-05-24", part.XmlNamespace);
			Assert.AreEqual("MsgHead-v1_2.xsd", part.XmlSchema);
		}

		[TestMethod]
		public void Read_CollaborationProfile_NotFound()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 1234).Result;
			Assert.IsNull(profile);
		}

		[TestMethod]
		public void Read_CollaborationProfile_FromCache()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile);
			// read a couple of times to ensure that serialization doesn't cause any exceptions
			profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile);
			profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile);
		}

		[TestMethod]
		public void Read_CollaborationAgreement_ById()
		{
			var profile = _registry.FindAgreementByIdAsync(_logger, Guid.Parse("49391409-e528-4919-b4a3-9ccdab72c8c1")).Result;

			Assert.AreEqual("<NAME>", profile.Name);
			Assert.AreEqual(93252, profile.HerId);
			Assert.AreEqual(14, profile.Roles.Count);

			Assert.IsNotNull(profile.SignatureCertificate);
			Assert.IsNotNull(profile.EncryptionCertificate);
		}
		[TestMethod]
		public void Read_CollaborationAgreement_ByCounterparty()
		{
			var profile = _registry.FindAgreementForCounterpartyAsync(_logger, 93252).Result;

			Assert.AreEqual(profile.HerId, 93252);
			Assert.AreEqual(profile.Name, "<NAME>");
			Assert.AreEqual(profile.CpaId, new Guid("{9333f3de-e85c-4c26-9066-6800055b1b8e}"));
			Assert.IsNotNull(profile.EncryptionCertificate);
			Assert.IsNotNull(profile.SignatureCertificate);
			Assert.AreEqual(profile.Roles.Count, 14);
		}
		[TestMethod]
		public void Read_CollaborationAgreement_NotFound()
		{
			var profile = _registry.FindAgreementForCounterpartyAsync(_logger, 1234).Result;
			Assert.IsNull(profile);
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void FindMessageForSender_ArgumentNull()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile.FindMessageForSender(null));
		}
		[TestMethod]
		public void FindMessageForSender_Found()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile.FindMessageForSender("DIALOG_INNBYGGER_EKONTAKT"));
		}
		[TestMethod]
		public void FindMessageForSender_NotFound()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNull(profile.FindMessageForSender("BOB"));
		}
		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void FindMessageForReceiver_ArgumentNull()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile.FindMessageForReceiver(null));<commit_msg>CPA tester<commit_after>﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.ServiceModel;
using Helsenorge.Registries.Abstractions;
using Helsenorge.Registries.Mocks;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Helsenorge.Registries.Tests
{
	[TestClass]
	[DeploymentItem(@"Files", @"Files")]
	public class CollaborationRegistryTests
	{
		private CollaborationProtocolRegistryMock _registry;
		private LoggerFactory _loggerFactory;
		private ILogger _logger;

		[TestInitialize]
		public void Setup()
		{
			var settings = new CollaborationProtocolRegistrySettings()
			{
				UserName = "username",
				Password = "password",
				EndpointName = "BasicHttpBinding_ICommunicationPartyService",
				WcfConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None),
				CachingInterval = TimeSpan.FromSeconds(5),
				MyHerId = 93238 // matches a value in a CPA test file
			};

			_loggerFactory = new LoggerFactory();
			_loggerFactory.AddDebug();
			_logger = _loggerFactory.CreateLogger<CollaborationRegistryTests>();

			var memoryCache = new MemoryCache(new MemoryCacheOptions());
			var distributedCache = new MemoryDistributedCache(memoryCache);

			_registry = new CollaborationProtocolRegistryMock(settings, distributedCache);
			_registry.SetupFindAgreementById(i =>
			{
				var file = Path.Combine("Files", $"CPA_{i:D}.xml");
				return File.Exists(file) == false ? null : File.ReadAllText(file);
			});
			_registry.SetupFindAgreementForCounterparty(i =>
			{
				var file = Path.Combine("Files", $"CPA_{i}.xml");
				return File.Exists(file) == false ? null : File.ReadAllText(file);
			});
			_registry.SetupFindProtocolForCounterparty(i =>
			{
				if (i < 0)
				{
					throw new FaultException(new FaultReason("Dummy fault from mock"));
				}
				var file = Path.Combine("Files", $"CPP_{i}.xml");
				return File.Exists(file) == false ? null : File.ReadAllText(file);
			});
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void Constructor_Settings_Null()
		{
			var memoryCache = new MemoryCache(new MemoryCacheOptions());
			var distributedCache = new MemoryDistributedCache(memoryCache);

			new CollaborationProtocolRegistry(null, distributedCache);
		}
		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void Constructor_Cache_Null()
		{
			new CollaborationProtocolRegistry(new CollaborationProtocolRegistrySettings(), null);
		}

		[TestMethod]
		public void Read_CollaborationProfile()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.AreEqual(profile.CpaId, Guid.Empty);
			Assert.AreEqual("Digitale innbyggertjenester", profile.Name);
			Assert.AreEqual(14, profile.Roles.Count);
			Assert.IsNotNull(profile.SignatureCertificate);
			Assert.IsNotNull(profile.EncryptionCertificate);

			var role = profile.Roles[0];
			Assert.AreEqual("DIALOG_INNBYGGER_DIGITALBRUKERreceiver", role.Name);
			Assert.AreEqual("1.1", role.VersionString);
			Assert.AreEqual(new Version(1, 1), role.Version);
			Assert.AreEqual(2, role.ReceiveMessages.Count);
			Assert.AreEqual(2, role.SendMessages.Count);
			var message = role.ReceiveMessages[0];
			Assert.AreEqual("DIALOG_INNBYGGER_DIGITALBRUKER", message.Name);
			Assert.AreEqual("sb.test.nhn.no/DigitalDialog/93238_async", message.DeliveryChannel);
			Assert.AreEqual(DeliveryProtocol.Amqp, message.DeliveryProtocol);

			var part = message.Parts.First();
			Assert.AreEqual(1, part.MaxOccurrence);
			Assert.AreEqual(0, part.MinOccurrence);
			Assert.AreEqual("http://www.kith.no/xmlstds/msghead/2006-05-24", part.XmlNamespace);
			Assert.AreEqual("MsgHead-v1_2.xsd", part.XmlSchema);
		}

		[TestMethod]
		public void Read_CollaborationProfile_NotFound()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 1234).Result;
			Assert.IsNull(profile);
		}

		[TestMethod]
		public void Read_CollaborationProfile_FromCache()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile);

			// if it's not found in cache, it will cause an exception
			_registry.SetupFindProtocolForCounterparty(i =>
			{
				throw new NotImplementedException();
			});
			profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile);
		}

		[TestMethod]
		public void Read_CollaborationAgreement_ById()
		{
			var profile = _registry.FindAgreementByIdAsync(_logger, Guid.Parse("49391409-e528-4919-b4a3-9ccdab72c8c1")).Result;

			Assert.AreEqual("Testlege Testlege", profile.Name);
			Assert.AreEqual(93252, profile.HerId);
			Assert.AreEqual(14, profile.Roles.Count);

			Assert.IsNotNull(profile.SignatureCertificate);
			Assert.IsNotNull(profile.EncryptionCertificate);
		}
		[TestMethod]
		public void Read_CollaborationAgreement_ByCounterparty()
		{
			var profile = _registry.FindAgreementForCounterpartyAsync(_logger, 93252).Result;

			Assert.AreEqual(profile.HerId, 93252);
			Assert.AreEqual(profile.Name, "Test<NAME>");
			Assert.AreEqual(profile.CpaId, new Guid("{9333f3de-e85c-4c26-9066-6800055b1b8e}"));
			Assert.IsNotNull(profile.EncryptionCertificate);
			Assert.IsNotNull(profile.SignatureCertificate);
			Assert.AreEqual(profile.Roles.Count, 14);
		}
		[TestMethod]
		public void Read_CollaborationAgreement_NotFound()
		{
			var profile = _registry.FindAgreementForCounterpartyAsync(_logger, 1234).Result;
			Assert.IsNull(profile);
		}
		[TestMethod]
		public void Read_CollaborationAgreement_FromCache()
		{
			var profile = _registry.FindAgreementForCounterpartyAsync(_logger, 93252).Result;
			Assert.IsNotNull(profile);

			// if it's not found in cache, it will cause an exception
			_registry.SetupFindAgreementForCounterparty(i =>
			{
				throw new NotImplementedException();
			});
			profile = _registry.FindAgreementForCounterpartyAsync(_logger, 93252).Result;
			Assert.IsNotNull(profile);
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void FindMessageForSender_ArgumentNull()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile.FindMessageForSender(null));
		}
		[TestMethod]
		public void FindMessageForSender_Found()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile.FindMessageForSender("DIALOG_INNBYGGER_EKONTAKT"));
		}
		[TestMethod]
		public void FindMessageForSender_NotFound()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNull(profile.FindMessageForSender("BOB"));
		}
		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void FindMessageForReceiver_ArgumentNull()
		{
			var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
			Assert.IsNotNull(profile.FindMessageForReceiver(null));
{'fraction_non_alphanumeric': 0.11024425811155669, 'fraction_numerical': 0.02165512212905578, 'mean_word_length': 5.497394599715775, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4739515', 'n_tokens_mistral': 4965, 'n_tokens_neox': 4153, 'n_words': 677}