예제 #1
0
        public void GetFacilityAddress_When_CurrentSubscriber_SessionInstance_is_Null()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                var expectedFacilityAddress = new FacilityAddress();
                // Fake the session state for HttpContext
                // http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/
                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState();
                session.ItemGetString = (key) => { if (key == "Subscriber") return null; return null; };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // GetInstance will return the Faked instance
                var myCurrentSubscriber = CurrentSubscriber.GetInstance();

                // Act
                // While we are using a fake, we haven't faked the SessionInstance which
                // means this will be null and this in turn means that
                //GetFacilityAddress should return a new FacilityAddress
                var actualFacilityAddress = myCurrentSubscriber.GetFacilityAddress();

                // Assert
                Assert.IsNotNull(actualFacilityAddress, "CurrentSubscriber.GetInstance().GetFacilityAddress() is null");
                var jss = new JavaScriptSerializer();
                Assert.AreEqual(jss.Serialize(expectedFacilityAddress),jss.Serialize(actualFacilityAddress), "There is a difference between the expected and actual address");
            }
        }
        /// <summary>
        /// The get shim http context base, used for tests. Must be encapsulated in
        /// using (ShimsContext.Create())
        /// {}
        /// statement.
        /// </summary>
        /// <param name="useCookie">
        /// Set to true if cookies are used.
        /// </param>
        /// <returns>
        /// Shimmed httpContextBase. <see cref="HttpContextBase"/>.
        /// </returns>
        private static HttpContext GetShimHttpContext(bool useCookie = true)
        {
            string[] allFactorEnumFieldValueKeys  = new string[] { "factorEnumFieldValue_1091_0_0_1097_2" };
            string[] allFactorEnumFieldValueKeys2 = new string[] { "factorEnumFieldValue2_1091_0_0_1097_2" };
            string[] allFactorEnumFieldValueKeys3 = new string[] { "factorEnumFieldValue3_1091_0_0_1097_2" };
            string   key1 = "1";
            string   key2 = "2";
            string   key3 = "3";

            NameValueCollection nameValueCollection = new NameValueCollection();

            nameValueCollection.Add("factorEnumFieldValue_1091_0_0_1097_2", key1);
            nameValueCollection.Add("factorEnumFieldValue2_1091_0_0_1097_2", key2);
            nameValueCollection.Add("factorEnumFieldValue3_1091_0_0_1097_2", key3);

            //var mockHttpContext = MockRepository.GenerateStub<HttpContextBase>();
            //mockHttpContext.Stub(c => c.Request.Form.AllKeys).Return(allFactorEnumFieldValueKeys).Repeat.Any();
            ////mockHttpContext.Stub(c => c.Request.Form.AllKeys.Where(key => key.StartsWith("factorEnumFieldValue_"))).Return(allFactorEnumFieldValueKeys).Repeat.Any();
            ////mockHttpContext.Stub(c => c.Request.Form.AllKeys.Where(key => key.StartsWith("factorEnumFieldValue2_"))).Return(allFactorEnumFieldValueKeys2).Repeat.Any();
            ////mockHttpContext.Stub(c => c.Request.Form.AllKeys.Where(key => key.StartsWith("factorEnumFieldValue3_"))).Return(allFactorEnumFieldValueKeys3).Repeat.Any();
            //
            //mockHttpContext.Stub(c => c.Request.Form).Return(value).Repeat.Any();



            var cookie = new HttpCookieCollection();

            cookie.Add(new HttpCookie("CultureInfo", "en-GB"));
            var queryString = new NameValueCollection();

            queryString.Add("error", "false");
            queryString.Add("handler", "true");
            var cultureInfo = new HttpCookie("CultureInfo", "en-GB");

            if (useCookie)
            {
                cookie.Add(cultureInfo);
            }

            HttpRequest stubHttpRequestBase = new System.Web.Fakes.ShimHttpRequest()
            {
                CookiesGet = () => { return(cookie); },
                FormGet    = () =>
                {
                    if (true)
                    {
                        return(nameValueCollection);
                    }
                    else
                    {
                        return(nameValueCollection);
                    }
                },
                QueryStringGet = () => { return(queryString); },
            };


            HttpResponse response = new System.Web.Fakes.ShimHttpResponse()
            {
                CookiesGet = () => { return(cookie); }
            };
            HttpServerUtilityBase untilityBase = new System.Web.Fakes.StubHttpServerUtilityBase()
            {
                UrlEncodeString = (info) => { return(cultureInfo.ToString()); },
                MapPathString   = (path) => { return(SelectedPath); }
            };
            HttpServerUtility untility = new System.Web.Fakes.ShimHttpServerUtility()
            {
                UrlEncodeString = (info) => { return(cultureInfo.ToString()); },
                MapPathString   = (path) => { return(SelectedPath); },
            };



            HttpApplicationState state = new System.Web.Fakes.ShimHttpApplicationState()
            {
                AddStringObject = (cacheKey, userContext) =>
                {
                    IUserContext tempContext = userContext as IUserContext;

                    if (tempContext.Locale.Id == DyntaxaTestSettings.Default.SwedishLocaleId)
                    {
                        ApplicationUserContextSV = tempContext;
                    }
                    else
                    {
                        ApplicationUserContext = tempContext;
                    }
                }
            };

            var context = new ShimHttpContext
            {
                ApplicationGet = () => { return(state); },
                RequestGet     = () => { return(stubHttpRequestBase); },
                ResponseGet    = () => { return(response); },
                ServerGet      = () => { return(untility); }
            };

            ShimHttpContext.CurrentGet = () =>
            {
                return(context);
            };


            // Create session varables
            var session = new System.Web.SessionState.Fakes.ShimHttpSessionState()
            {
                ItemGetString = (key) =>
                {
                    if (key == DyntaxaSettings.Default.ApplicationContextCacheKey)
                    {
                        return(ApplicationUserContext);
                    }
                    else if (key == DyntaxaSettings.Default.ApplicationContextCacheKey + DyntaxaTestSettings.Default.EnglishLocale)
                    {
                        return(ApplicationUserContext);
                    }
                    else if (key == DyntaxaSettings.Default.ApplicationContextCacheKey + DyntaxaTestSettings.Default.SwedishLocale)
                    {
                        return(ApplicationUserContextSV);
                    }
                    else if (key == "userContext")
                    {
                        if (UserContextData.IsNotNull())
                        {
                            return(UserContextData);
                        }
                        else
                        {
                            return(ApplicationUserContext);
                        }
                    }
                    else if (key == "RevisionId")
                    {
                        return(SessionRevisionId);
                    }
                    else if (key == "TaxonId")
                    {
                        return(SessionTaxonId);
                    }
                    else if (key == "Revision")
                    {
                        return(SessionRevision);
                    }
                    else if (key == "SpeciesFactHostTaxonIdList")
                    {
                        return(SessionSpeciesFactHostTaxonIdList);
                    }
                    return(null);
                },
                ItemSetStringObject = (key, sessionObject) =>
                {
                    if (key == "TaxonId")
                    {
                        SessionTaxonId = sessionObject as TaxonIdTuple;
                    }
                },
            };


            System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet =
                (o) =>
            {
                return(session);
            };

            // Creat cash varables
            var cache = new System.Web.Caching.Fakes.ShimCache()
            {
                ItemGetString = (key) =>
                {
                    if (key == DyntaxaSettings.Default.ApplicationContextCacheKey)
                    {
                        return(ApplicationUserContext);
                    }
                    else if (key == DyntaxaSettings.Default.ApplicationContextCacheKey + DyntaxaTestSettings.Default.EnglishLocale)
                    {
                        return(ApplicationUserContext);
                    }
                    else if (key == DyntaxaSettings.Default.ApplicationContextCacheKey + DyntaxaTestSettings.Default.SwedishLocale)
                    {
                        return(ApplicationUserContextSV);
                    }
                    else if (key == "userContext")
                    {
                        if (UserContextData.IsNotNull())
                        {
                            return(UserContextData);
                        }
                        else
                        {
                            return(ApplicationUserContext);
                        }
                    }
                    else if (key == "RevisionId")
                    {
                        return(SessionRevisionId);
                    }
                    else if (key == "TaxonId")
                    {
                        return(SessionTaxonId);
                    }
                    else if (key == "Revision")
                    {
                        return(SessionRevision);
                    }
                    else if (key == "SpeciesFactHostTaxonIdList")
                    {
                        return(SessionSpeciesFactHostTaxonIdList);
                    }
                    return(null);
                },
            };


            System.Web.Fakes.ShimHttpContext.AllInstances.CacheGet =
                (o) =>
            {
                return(cache);
            };

            return(context);
        }
예제 #3
0
        public void AttemptToLogUserIn_UserIsFound_NoReturnUrlProvided()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                const string userName = "******";
                const string password = "******";
                const string userHostAddress = "doesNotMatter";
                var returnUrl = string.Empty;
                var wasCurrentUserClearCalled = false;
                var wasLoginModelAttemptToLogUserInCalled = false;
                var wasLoginModelSyncWithOrImportDataFromASPPCalled = false;
                var wasCurrentUserSessionInstanceGetCalled = false;
                var wasCurrentUserSetInstanceStringCalled = false;
                var wasUserEventsInitializeSessionCalled = false;
                var wasFormsAuthenticationSetAuthCookieCalled = false;
                var wasCreateLoginRecord = false;

                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState()
                {
                    ItemGetString = (key) =>
                    {
                        return key == "CurrentUser" ? new ShimCurrentUser() : null;
                    }
                };

                var context = new System.Web.Fakes.ShimHttpContext();
                var applicationShim = new System.Web.Fakes.ShimHttpApplicationState();
                context.ApplicationGet = () => applicationShim;

                System.Web.Fakes.ShimHttpContext.CurrentGet = () => context;

                System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet = (o) => session;

                ShimLoginModel.AllInstances.AttemptToLogUserInStringString = (loginModel, userNameSentToLoginModel, passwordSentToLoginModel) =>
                {
                    wasLoginModelAttemptToLogUserInCalled = true;
                    return new LoginModel {Errors = false};
                };

                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingService, userNameSentToLoginModel) =>
                {
                    wasLoginModelSyncWithOrImportDataFromASPPCalled = true;
                };

                ShimCurrentUser.Clear = () =>
                {
                    wasCurrentUserClearCalled = true;
                };

                ShimCurrentUser.SessionInstanceGet = () =>
                {
                    wasCurrentUserSessionInstanceGetCalled = true;
                    return new ShimCurrentUser();
                };

                ShimCurrentUser.SetInstanceString = (uniqueId) =>
                {
                    wasCurrentUserSetInstanceStringCalled = true;
                };

                ShimUserEvents.AllInstances.InitializeSessionStringString = (userEvents, uniqueId, userHostAddressValue) =>
                {
                    wasUserEventsInitializeSessionCalled = true;
                };

                ShimFormsAuthentication.SetAuthCookieStringBoolean = (userNameValue, createPersistentCookie) =>
                {
                    wasFormsAuthenticationSetAuthCookieCalled = true;
                };

                ShimSingleConcurrentLoginManager.AllInstances.CreateLoginRecordStringString = (methodName, userNameValue, sessionIdValue) =>
                {
                    wasCreateLoginRecord = true;
                    return true;
                };

                // Act
                var resultAttemptToLogUserIn = LoginViewModelForTests.AttemptToLogUserIn(userName, password, userHostAddress, returnUrl);

                // Assert
                // Only testing the items that could be impacted by the logic of this test
                Assert.IsNotNull(resultAttemptToLogUserIn, "resultAttemptToLogUserIn");
                Assert.IsTrue(wasCurrentUserClearCalled, "wasCurrentUserClearCalled");
                Assert.IsTrue(wasLoginModelAttemptToLogUserInCalled, "wasGetInitialLoginViewModelStringStringStringCalled");
                Assert.IsTrue(wasLoginModelSyncWithOrImportDataFromASPPCalled, "wasLoginModelSyncWithOrImportDataFromASPPCalled");
                Assert.IsTrue(wasCurrentUserSessionInstanceGetCalled, "wasCurrentUserSessionInstanceGetCalled");
                Assert.IsTrue(wasCurrentUserSetInstanceStringCalled, "wasCurrentUserSetInstanceStringCalled");
                Assert.IsTrue(wasUserEventsInitializeSessionCalled, "wasUserEventsInitializeSessionCalled");
                Assert.IsTrue(wasFormsAuthenticationSetAuthCookieCalled, "wasFormsAuthenticationSetAuthCookieCalled");
                Assert.IsTrue(wasCreateLoginRecord, "wasCreateLoginRecord");
                Assert.AreEqual(Constants.Urls.SearchPageSubscriberTab, resultAttemptToLogUserIn.RedirectUrl, "RedirectUrl");
            }
        }
        public void PerformOperation_HappyPath()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                SIMPL.Session.Fakes.ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // Fake the session state for HttpContext
                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                ShimRosettianClient.AllInstances.PerformEquipmentOperationListOfEquipmentOperationDtoUserDto  =
                    (myTestClient, myEquipOpsList, myUserDto) => true;

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                var deviceIDs = new List<string>
                {
                    "deviceID"
                };
                var deviceIDsAsJSON = serializer.Serialize(deviceIDs);

                // First Act
                var operationsController = DependencyResolver.Current.GetService<OperationsController>();
                var result = operationsController.PerformOperation(deviceIDsAsJSON, "Reboot");

                // First Assert
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result is PartialViewResult, "result is not a PartialViewResult");

                // Second Act
                var resultPartialResult = result as PartialViewResult;

                // Second Assert
                Assert.AreEqual("LoadQueryResults_Partial", resultPartialResult.ViewName, "ViewName doesn't match expected value");
                Assert.IsTrue(resultPartialResult.Model is DeviceQueryResultsViewModel, "partialViewResult is not EquipmentOperationsModel");

                // Third Act
                var operationModel = resultPartialResult.Model as DeviceQueryResultsViewModel;

                // Third Assert
                Assert.AreEqual("200", operationModel.QueryResponse.Code, "Response Code doesn't match expected value");
                Assert.AreEqual("Operation performed successfully", operationModel.QueryResponse.Message, "Response Message doesn't match expected value");
            }
        }
        public void PerformOperation_SadPath()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

                //Build FakeDto
                var fakeUserDto = myContext.GetFakeUserDtoObject();

                //Fake call to CurrentUser.AsUserDto()
                SIMPL.Session.Fakes.ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // Fake the session state for HttpContext
                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                var fakeValidationFault = new ValidationFaultDto()
                {
                    Details = new List<ValidationDetailDto>()
                    {
                        new ValidationDetailDto()
                        {
                            Key = "NA",
                            Message = "Error Message",
                            Tag = "NA"
                        }
                    }
                };

                ShimRosettianClient.AllInstances.PerformEquipmentOperationListOfEquipmentOperationDtoUserDto  =
                    (myTestClient, myEquipOpsList, myUserDto) => { throw new FaultException<ValidationFaultDto>(fakeValidationFault); };

                // TestingShim is a class that is inside the EquipmentController.cs file
                ShimTestingShim.HandleExceptionByEnvironmentException = (myException) => { throw new FaultException<ValidationFaultDto>(fakeValidationFault); };

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                var deviceIDs = new List<string>
                {
                    "deviceID"
                };
                var deviceIDsAsJSON = serializer.Serialize(deviceIDs);

                ShimErrorLoggingService.AllInstances.LogErrorException = (myClient, myException) => { };

                // First Act
                var operationsController = DependencyResolver.Current.GetService<OperationsController>();
                var result = operationsController.PerformOperation(deviceIDsAsJSON, "Reboot");

                // First Assert
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result is PartialViewResult, "result is not a PartialViewResult");

                // Second Act
                var resultPartialResult = result as PartialViewResult;

                // Second Assert
                Assert.AreEqual("LoadQueryResults_Partial", resultPartialResult.ViewName, "ViewName doesn't match expected value");
                Assert.IsTrue(resultPartialResult.Model is DeviceQueryResultsViewModel, "partialViewResult is not EquipmentOperationsModel");

                // Third Act
                var operationModel = resultPartialResult.Model as DeviceQueryResultsViewModel;

                // Third Assert
                Assert.AreEqual("500", operationModel.QueryResponse.Code, "Response Code doesn't match expected value");
                Assert.AreEqual("Error Message", operationModel.QueryResponse.Message, "Response Message doesn't match expected value");
            }
        }