public void CreateUserHash_HandleConcurrentRequestProperly()
        {
            HttpContext[] contexts = new []
            {
                HttpContextHelper.GetContextWithIp("192.168.132.17"),
                HttpContextHelper.GetContextWithIp("192.168.132.18"),
                HttpContextHelper.GetContextWithIp("192.168.132.19")
            };

            TestIdentityProvider       provider   = new ("ProviderWrapper", new IpBasedUserIdentityProvider());
            UserHashIdentityMiddleware middleware = GetMiddelware(saltProvider: null, provider);

            Enumerable.Range(0, 100).AsParallel()
            .Select(index =>
            {
                int contextIndex = index % contexts.Length;
                string hash      = middleware.CreateUserHash(contexts[contextIndex]);
                return(contextIndex, hash);
            })
            .GroupBy(hashIndexPair => hashIndexPair.contextIndex)
            .Select(hashesPerContext => hashesPerContext.Distinct().Count())
            .ForAll(uniquHashesPerContext => {
                Assert.AreEqual(1, uniquHashesPerContext, "Hashes for the same context should be identical");
            });
        }
        public void CreateUserHash_UseSalt()
        {
            Random           random       = new Random();
            TestSaltProvider saltProvider = new TestSaltProvider();

            random.NextBytes(saltProvider.Salt);
            UserHashIdentityMiddleware middleware = GetMiddelware(saltProvider: saltProvider);

            HttpContext context     = HttpContextHelper.GetContextWithIp("192.168.100.1");
            string      initialHash = middleware.CreateUserHash(context);

            random.NextBytes(saltProvider.Salt);
            string changedHash = middleware.CreateUserHash(context);

            Assert.AreNotEqual(changedHash, initialHash);
        }
        public void CreateUserHash_CallProvidersInOrder(bool firstApplicable, bool secondApplicable, bool firstShouldBeCalled, bool secondShouldBeCalled)
        {
            HttpContext                context    = HttpContextHelper.GetContextWithIp("192.168.201.1");
            TestIdentityProvider       mock1      = new ("Provider1", 15) { IsApplicable = firstApplicable };
            TestIdentityProvider       mock2      = new ("Procider2", 10) { IsApplicable = secondApplicable };
            UserHashIdentityMiddleware middleware = GetMiddelware(saltProvider: null, mock1, mock2);

            string hash = middleware.CreateUserHash(context);

            mock1.AssertCallsAndReset(firstShouldBeCalled);
            mock2.AssertCallsAndReset(secondShouldBeCalled);

            if (!firstApplicable && !secondApplicable)
            {
                Assert.AreEqual(string.Empty, hash, "Hash should be empty when all providers not applicable");
            }
        }