private void InitTest_btnReport_Click(List <Group> groups, List <ReportEntities.DataDumpReport> dataDumpReports = null, string selectedFormat = null, string blastFieldIdString = null)
        {
            var shimHttpContext = new ShimHttpContext();

            SetPageProperties_btnReport_Click();
            SetPageControls_btnReport_Click();
            ShimDateTime.TryParseStringDateTimeOut       = DateTimeTryParse_btnReport_Click;
            ShimDataDumpReport.AllInstances.groupListGet = (ddr) => groups;
            if (!string.IsNullOrEmpty(selectedFormat))
            {
                _drpExport.SelectedValue = selectedFormat;
            }
            ShimBlastFieldsName.GetByBlastFieldIDInt32User = (id, user) => blastFieldIdString != null ? new BlastFieldsName()
            {
                Name = $"{blastFieldIdString}{id}"
            } : null;
            ShimHttpServerUtility.AllInstances.MapPathString = (su, s) => Assembly.GetExecutingAssembly().Location;
            ReportFakes.ShimDataDumpReport.GetListInt32DateTimeDateTimeString = (cid, endData, startDate, gId) => dataDumpReports;
            ShimHttpContext.AllInstances.ServerGet             = (context) => new ShimHttpServerUtility();
            ShimHttpContext.CurrentGet                         = () => shimHttpContext;
            ShimHttpContext.AllInstances.ResponseGet           = (c) => new ShimHttpResponse();
            ShimReport.AllInstances.LoadReportDefinitionStream = (r, s) => { };
            ShimLocalReport.AllInstances.SetParametersIEnumerableOfReportParameter = (r, parameters) => { };
            ShimLocalReport.AllInstances.Refresh = (r) => { };
            ShimReport.AllInstances.RenderStringStringStringOutStringOutStringOutStringArrayOutWarningArrayOut = ReportRender_btnReport_Click;
        }
Ejemplo n.º 2
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");
            }
        }
Ejemplo n.º 3
0
        public void Render_HttpContextNotNull_RenderHTMLTextWrite(string browser)
        {
            // Arrange
            SetUp();
            var shimHttpContext = new ShimHttpContext();

            ShimHttpContext.CurrentGet = () => shimHttpContext.Instance;
            var stringWriter     = new StringWriter();
            var outputTextWriter = new HtmlTextWriter(stringWriter);

            _toolColorPicker.Page         = GetMockOfPage(browser).Instance;
            _toolColorPicker.AutoPostBack = true;
            _privateObject.SetField("_allowDHTML", false);
            ShimControl.AllInstances.ParentGet = (obj) =>
            {
                return(stubToolbar);
            };

            // Act
            _privateObject.Invoke(_MethodRender, new object[] { outputTextWriter });
            var actualResult = stringWriter.ToString();

            // Assert
            actualResult.ShouldSatisfyAllConditions(
                () => actualResult.ShouldNotBeNullOrWhiteSpace(),
                () => actualResult.ShouldContain(_InputHidden)
                );
            TearDown();
        }
Ejemplo n.º 4
0
        public void SyncPlantData_HappyPath()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

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

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

                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                 //Expected Result
                var expectedResult = new
                {
                    status = "valid",
                    message = "Success: DPI plant data will be updated in the next 10 minutes."
                };

                var fakeCurrentSubscriber = new ShimCurrentSubscriber
                {
                   LocationIdGet = () => "0089451",
                   DpiRegionGet = ()=>"CT"
                };

                ShimCurrentSubscriber.SessionInstanceGet = () => fakeCurrentSubscriber;

                // Call FacilitiesController SyncPlantData
                ShimEnterpriseClient.AllInstances.SyncPlantDataStringHeaderArgs = delegate { return true; };

                //Act
                var actualResult = FacilitiesControllerForTests.SyncPlantData() as JsonResult;

                // Test Validation
                Assert.IsNotNull(actualResult, "JsonResult returned is null");
                Assert.IsNotNull(actualResult.Data, "JsonResult Data returned is null");
                Assert.AreEqual(expectedResult.ToString(), actualResult.Data.ToString());
            }
        }
Ejemplo n.º 5
0
        public void GetNotes_Second_WTNUSI_USES_Associated_Triad_USI_to_get_Notes()
        {
            //Arrange
            var response = new ServiceHistoryCollectionDto();
            const string subID = "SUBID";
            const string expectedID = "PROVISIONEDID";

            var passedUsi = string.Empty;

            using (ShimsContext.Create())
            {
                SIMPLTestContext testContext = new SIMPLTestContext();
                var fakeUser = testContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUser;
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "mjw425"
                };

                var session = GetShimmedSession();

                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                ShimRosettianClient.AllInstances.GetServiceHistorySearchServiceHistoryDtoUserDto = (client, criteria, user) =>
                {
                    passedUsi = criteria.SubscriberId;
                    return response;
                };
                var dataSourcerequest = new DataSourceRequest()
                {
                    Aggregates = new List<AggregateDescriptor>(),
                    Filters = new List<IFilterDescriptor>(),
                    Groups = new List<GroupDescriptor>(),
                    Page = 1,
                    PageSize = 0,
                    Sorts = new List<SortDescriptor>()
                };
                var fromDate = DateTime.Now.AddDays(-7).ToString();
                var toDate = DateTime.Now.AddDays(7).ToString();
                var defaultFilterAsJson =
                   "{'NoteTypes':['Triad'],'IsCustomDate':true,'FromDateRange':'" + fromDate + "','ToDateRange':'" + toDate + "','SubscriberId':'" + subID + "','LocationId':'1319028645001', 'ProvisionedId': '"+expectedID+"'}";
                //Act
                var result = NotesControllerForTest.GetNotes(dataSourcerequest, defaultFilterAsJson) as JsonResult;
                //Assert
                Assert.AreEqual(expectedID, passedUsi, string.Format("Did not used provisioned USI: {0}, Actual: {1}", expectedID, passedUsi));//change to expectedid
            }
        }
Ejemplo n.º 6
0
        public void A_user_logs_in_when_Single_Concurrent_Login_Feature_is_enabled_but_error_occurs_when_saving_the_username_and_session_data()
        {
            using (ShimsContext.Create())
            {
                // Given a known user that is not logged in yet
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                LoginControllerForTests.ControllerContext = new ControllerContext()
                {
                    HttpContext = contextStub
                };

                #endregion LoginModel class, AttemptToLogUserIn method

                // And the Single Concurrent Login Feature is enabled

                // As there are unit tests for IsCheckEnabledActor, I am mocking the reference to IsCheckEnabled
                var wasIsCheckEnabledCalled = false;
                ShimSingleConcurrentLoginRules.AllInstances.IsCheckEnabled = (resultValue) =>
                {
                    wasIsCheckEnabledCalled = true;
                    return true;
                };

                // When that user is trying to log in

                #region LoginModel class, AttemptToLogUserIn method

                var wasASPPAuthenticateCalled = false;
                ShimUserManagement.AllInstances.AuthenticateStringString = (userNameValue, passwordValue, results) =>
                {
                    wasASPPAuthenticateCalled = true;
                    return UserManagement.AuthenticationResults.Success;
                };

                var wasASPPGetUserDetailsCalled = false;
                ShimUserManagement.AllInstances.GetUserDetailsString = (userNameValue, results) =>
                {
                    wasASPPGetUserDetailsCalled = true;
                    return new ASPP_Users();
                };

                var wasASPPGetUserGroupsCalled = false;
                ShimUserManagement.AllInstances.GetUserGroupsString = (userNameValue, results) =>
                {
                    wasASPPGetUserGroupsCalled = true;

                    // need to add at least one group - doing just enough to get beyond the guard in LoginModel.cs
                    var myASPP_Group = new ASPP_Groups
                    {
                        Group_ID = 1
                    };

                    return new List<ASPP_Groups>
                    {
                        myASPP_Group
                    };
                };

                // Then the data is not saved correctly

                // Note: the CreateSIMPLLoginTrackerRecord method should be called

                // When the CreateSIMPLLoginTrackerRecord method is called,
                // the SIMPLLoginTrackers.Add line will throw an exception because
                // it cannot find SIMPLEntities connection string in the config;
                // this is fine for our purposes as it throws as exception.

                // And the data is not added to the cache

                // Note: the AddSIMPLLoginTrackerRecordToCache method should not be called
                var wasAddSIMPLLoginTrackerRecordToCacheCalled = false;
                ShimSIMPLSessionEntitiesCache.AddSIMPLLoginTrackerRecordToCacheStringSIMPLLoginTracker = (userNameValue, myLoginTrackerValue) =>
                {
                    wasAddSIMPLLoginTrackerRecordToCacheCalled = true;
                    return true;
                };

                // And the user is not logged in

                #region back in the LoginViewModel class, AttemptToLogUserIn method

                var session = new ShimHttpSessionState { SessionIDGet = () => "doesNotMatter"};
                var context = new ShimHttpContext();
                var applicationShim = new ShimHttpApplicationState();
                context.ApplicationGet = () => applicationShim;
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Note: the CurrentUser.SetInstance method should not be called
                var wasCurrentUserSetInstanceStringCalled = false;
                var currentUserSetInstanceCount = 0;
                ShimCurrentUser.SetInstanceString = (uniqueId) =>
                {
                    wasCurrentUserSetInstanceStringCalled = true;
                    currentUserSetInstanceCount++;
                };

                // Note: the CurrentUser.SessionInstance method should not be called
                var wasCurrentUserSessionInstanceGetCalled = false;
                ShimCurrentUser.SessionInstanceGet = () =>
                {
                    wasCurrentUserSessionInstanceGetCalled = true;
                    return new ShimCurrentUser();
                };

                // Note: the SyncWithOrImportDataFromASPP method should not be called
                var wasLoginModelSyncWithOrImportDataFromASPPCalled = false;
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingServiceValue, userNameSentToLoginModelValue) =>
                {
                    wasLoginModelSyncWithOrImportDataFromASPPCalled = true;
                };

                // Note: the CurrentUser.Clear method should not be called
                var wasCurrentUserClearCalled = false;
                ShimCurrentUser.Clear = () =>
                {
                    wasCurrentUserClearCalled = true;
                };

                // Note: the UserEvents.InitializeSession method should not be called
                var wasUserEventsInitializeSessionCalled = false;
                ShimUserEvents.AllInstances.InitializeSessionStringString = (userEvents, uniqueIdValue, userHostAddressValue) =>
                {
                    wasUserEventsInitializeSessionCalled = true;
                };

                // Note: the FormsAuthentication.SetAuthCookie method should not be called
                var wasFormsAuthenticationSetAuthCookieCalled = false;
                ShimFormsAuthentication.SetAuthCookieStringBoolean = (userNameValue, createPersistentCookieValue) =>
                {
                    wasFormsAuthenticationSetAuthCookieCalled = true;
                };

                ShimErrorLoggingService.AllInstances.LogErrorException = (method, myException) =>
                {
                    // Not returning anything, just redirecting the call
                };

                #endregion back in the LoginViewModel class, AttemptToLogUserIn method

                var result = LoginControllerForTests.UserLogin(userName, password, returnUrl);
                Assert.IsNotNull(result, "LoginController returned null");
                Assert.IsTrue(result is ViewResult, "LoginController didn't return a ViewResult");

                var resultViewResult = result as ViewResult;
                Assert.IsNotNull(resultViewResult.Model, "resultViewResult.Model is null");
                Assert.IsTrue(resultViewResult.Model is LoginViewModel, "resultViewResult.Model is not LoginViewModel");

                var resultLoginViewModel = resultViewResult.Model as LoginViewModel;
                Assert.AreEqual("Unable to save the Login Record, please contact support (Single Concurrent Login Enabled)", resultLoginViewModel.Message, "resultLoginViewModel.Message did not have the expected value");

                Assert.IsTrue(wasASPPAuthenticateCalled, "wasASPPAuthenticateCalled is false");
                Assert.IsTrue(wasASPPGetUserDetailsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasASPPGetUserGroupsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasIsCheckEnabledCalled, "wasIsCheckEnabledCalled is false");

                // Not able to check if the CreateSIMPLLoginTrackerRecord method was called because
                // we are not using a Shim for that (as we are calling the live method)

                // These are negative checks to make sure that the other code was not called
                Assert.IsFalse(wasAddSIMPLLoginTrackerRecordToCacheCalled, "wasAddSIMPLLoginTrackerRecordToCacheCalled is true");
                Assert.IsFalse(wasCurrentUserSetInstanceStringCalled, "wasCurrentUserSetInstanceStringCalled is true");
                Assert.AreEqual(0, currentUserSetInstanceCount, "currentUserSetInstanceCount did not match expected value");
                Assert.IsFalse(wasCurrentUserSessionInstanceGetCalled, "wasCurrentUserSessionInstanceGetCalled is true");
                Assert.IsFalse(wasCurrentUserClearCalled, "wasCurrentUserClearCalled is true");
                Assert.IsFalse(wasLoginModelSyncWithOrImportDataFromASPPCalled, "wasLoginModelSyncWithOrImportDataFromASPPCalled is true");
                Assert.IsFalse(wasUserEventsInitializeSessionCalled, "wasUserEventsInitializeSessionCalled is true");
                Assert.IsFalse(wasFormsAuthenticationSetAuthCookieCalled, "wasFormsAuthenticationSetAuthCookieCalled is true");
            }
        }
        /// <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);
        }
        public void EditResidentialGateway_hasMainRg_hasListOtherRgs_hasIpVideoDevice_ValidateSuccessScenario()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

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

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

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

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

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

                // current location
                const string expectedLocationId = "123456789";

                // expected all devices on current location
                var customFieldsDto = RgTestData_CustomFieldsCollection();
                var mainRg = RgTestData_MainRg(customFieldsDto, expectedLocationId);
                var ipVideoDevice = RgTestData_IpVideoDevice(customFieldsDto, expectedLocationId);
                var otherRgs = RgTestData_OtherRgList(customFieldsDto, expectedLocationId);

                // rg to be updated
                var rgTobeUpdated = otherRgs.First();
                rgTobeUpdated.UnitAddress = "12345678";

                // set location and sub
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => expectedLocationId;
                ShimCurrentSubscriber.AllInstances.SubIdGet = o => "1234567";
                ShimCurrentSubscriber.AllInstances.WanIpAddressGet = o => "10.10.10.10";

                // set eidt residential gateway to true
                ShimRosettianClient.AllInstances.UpdateONTPortsEquipmentCriteriaCollectionDtoUserDto = (myTestclient, myEquipmentCriteriaDto, userDto) => true;

                // expected search results after Update RG
                var searchEquipmentsResult = new List<EquipmentDto>();
                searchEquipmentsResult.AddRange(mainRg);
                searchEquipmentsResult.AddRange(otherRgs);
                searchEquipmentsResult.Add(ipVideoDevice);

                // set search results to expected
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, mySearchFields, myUserDto) => searchEquipmentsResult;

                // expected custom fields
                var equipmentDataDto = mainRg.First(x => x.SerialNumber.EndsWith("D01"));
                equipmentDataDto.CustomFields = customFieldsDto.ToList();

                // set load eqiupment for main RG
                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => equipmentDataDto;

                // set custom fields
                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto = (myTestClient, myUserDto) => customFieldsDto;

                // set ip video device path
                ShimVirtualPathUtility.ToAbsoluteString = (myTestString) => @"http://testapp/images/DVR.png";

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // RG to be updated
                var model4Update = new ResidentialGatewayModel
                {
                    ID = rgTobeUpdated.SerialNumber,
                    UnitAddress = rgTobeUpdated.UnitAddress
                };

                // call EditResidentialGateway of ResidentialGatewayController
                var result = residentialController.EditResidentialGateway(model4Update) as JsonResult;

                // validate json result
                Assert.IsNotNull(result, "Returned Json result is null");

                dynamic resultData = result.Data;
                var status = resultData.status as string;
                var errorMessage = string.Empty;
                if (status == "error")
                {
                    errorMessage = resultData.errorMessage;
                }
                Assert.AreEqual("valid", status, "status is not valid - {0}", errorMessage);
                var renderedPartial = resultData.returnedPartial as string;
                Assert.IsNotNull(renderedPartial, "Prerendered partial is null.");
            }
        }
Ejemplo n.º 9
0
        public void User_can_load_a_location_that_is_not_associated_to_a_subscriber_with_no_devices()
        {
            //Setup
            var myContext = new SIMPLTestContext();
            const string locationId = "9999999";

            using (ShimsContext.Create())
            {
                // Given a user
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                // Fake the session state for HttpContext
                // http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/
                var session = new ShimHttpSessionState();
                session.ItemGetString = (key) => { if (key == "LoadedLocation") 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;

                ShimCurrentSubscriber.UpdateSubscriberLocationModel = delegate { };

                // And a known location
                var fakeLocationDto = myContext.GetFakeLocationDtoObject(locationId);

                ShimRosettianClient.AllInstances.LoadLocationStringUserDto = (myRosettianClient, myLocationId, myUserDto) => fakeLocationDto;

                // And the location has no devices
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto = (myRosettianClient, mySearchFields, myUser) => new List<EquipmentDto>();

                // And the location is not associated to a subscriber
                var fakeSubscriberDto = new List<SubscriberDto>();
                ShimRosettianClient.AllInstances.SearchSubscribersSearchFieldsDtoUserDto = (myRosettianClient, mySearchFields, myUserDto) => fakeSubscriberDto;

                // When loading that location
                var actionResult = SubscriberControllerForTests.LoadLocation(locationId) as ViewResult;

                // Then the user receives a response
                Assert.IsNotNull(actionResult, "SubscriberController LoadLocation method returned null");

                // And the response is successful
                Assert.AreEqual("Index2", actionResult.ViewName, "actionResult.RouteValues[\"action\"]");

                // And the response returns the location information
                var expectedModel = fakeLocationDto.MapToSubscriberModel();
                var actualModel = actionResult.Model as SubscriberModel;
                Assert.IsNotNull(actualModel, "The model returned was empty");
                Assert.IsNotNull(actualModel.SubLocationModel, "The sub location model returned was empty");
                Assert.IsTrue(expectedModel.SubLocationModel.Address1.Equals(actualModel.SubLocationModel.Address1), "The Address was different");

                // And the location matches the requested location
                Assert.AreEqual(locationId, actualModel.SubLocationModel.LocationID, "Location Id did not match the one that was searched for.");

                // And the notes tab is the selected tab
                Assert.AreEqual(5, actualModel.SelectedTabIndex, "The default tab was not the notes tab");
            }
        }
Ejemplo n.º 10
0
        public void Index_When_SubscriberID_Is_WhiteSpace_And_No_Previous_Customer_Is_Loaded_Should_Be_Redirected_To_Search_Page()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                string subscriberID = " ";
                string deviceID = string.Empty;

                // Fake the session state for HttpContext
                // http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/
                var session = new 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;

                // Fake the CurrentSubscriber.IsLoad call
                ShimCurrentSubscriber.AllInstances.IsLoadedGet = (myResult) => false;

                // 1st Act
                var result = SubscriberControllerForTests.Index(subscriberID, deviceID);

                // 1st Assert
                Assert.IsNotNull(result, "SubscriberController Index returned null");
                Assert.IsTrue(result is RedirectToRouteResult, "Not a RedirectToRouteResult");

                // 2nd Act
                var resultRedirectToRouteResult = (RedirectToRouteResult)result;

                // 2nd Assert
                Assert.IsNotNull(resultRedirectToRouteResult, "Cast to RedirectToRouteResult is null");
                Assert.AreEqual(2, resultRedirectToRouteResult.RouteValues.Count);
                Assert.AreEqual("Search", resultRedirectToRouteResult.RouteValues["action"], "actionResult.RouteValues[\"action\"]");
                Assert.AreEqual("Search", resultRedirectToRouteResult.RouteValues["controller"], "actionResult.RouteValues[\"controller\"]");
            }
        }
Ejemplo n.º 11
0
        public void Technicians_See_Only_Voice_Related_Data_In_Change_Subscriber_Services_Window()
        {
            using (ShimsContext.Create())
            {
                SIMPLTestContext testContext = new SIMPLTestContext();
                var session = GetShimmedSession();
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                //set up the services
                ShimCurrentSubscriber.GetInstance = () => new ShimCurrentSubscriber
                {
                    DataProductTypeGet = () => SubscriberEnums.DataProductType.XDsl,
                    VideoProductTypeGet = () => SubscriberEnums.VideoProductType.IpTv,
                    StateGet = () => "CT",
                    WtnGet = () => "2061272727",
                    ProvisionedServicesListGet = () => GetProvisionedServices()
                };

                ShimCurrentUser.AsUserDto = () => new UserDto()
                {
                    Email = "fake_Email",
                    Name = "fake_Name",
                    Role = "Tech"
                };

                //User is in Tech role
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "Tech",
                };

                ShimCurrentUser.RetrieveUserRolesString = (x) => new List<int>
                {
                    Convert.ToInt32(SIMPLDbEnums.RoleTypeEnum.Tech)
                };

                ShimCurrentUser.AllInstances.RolesGet = (x) => new List<int>
                {
                    Convert.ToInt32(SIMPLDbEnums.RoleTypeEnum.Tech)
                };

                //Shimming the web.config read where it will specify which services are available for Tech's edit functionality
                var serviceToBeFilteredOut = "RNGDWN";
                var appCollection = new NameValueCollection();
                appCollection.Add("AvailableServicesForTechEdit", "ADSL,VDSL,VOICE");
                appCollection.Add("FilteredChildServicesForTechEdit", serviceToBeFilteredOut);
                ShimConfigurationManager.AppSettingsGet = () => appCollection;

                ShimServices.ProvisioningServicesGet = delegate
                {
                    return GetAvailableServices(); //This are the services which will be available for the subscriber
                };

                ShimSubscriberServicesModel.AllInstances._provisionedServicesGet = delegate
                {
                    return GetProvisionedServices(); //These are all the provisioned sercives for the subscriber
                };

                var expectedAvailableServices = GetAvailableServicesForTechRole();
                var expectedProvisionedServices = GetProvisionedServicesForTechRole();

                //Need to call this to instantiate the subscriber service model properly.
                var initialModel = ServicesControllerForTests.Index();
                Assert.IsNotNull(initialModel,"Controller returned null for index request");

                var result = ServicesControllerForTests.EditServices(initialModel.Model as SubscriberServicesModel);
                Assert.IsNotNull(result, "Controller returned null for 'EditServices_Partial' request");
                Assert.IsTrue(result is PartialViewResult);
                Assert.AreEqual((result as PartialViewResult).ViewName, "EditServices_Partial","Retured view is not 'EditServices_Partial'");

                var viewModel = (result as PartialViewResult).Model as SubscriberServicesModel;
                Assert.IsNotNull(viewModel);
                var availableSvcs = viewModel.AvailableServicesDictionary;
                var provisionedSvcs = viewModel.ProvisionedServicesDictionary;

                Assert.IsNotNull(availableSvcs,"Available services object is null");
                Assert.IsNotNull(provisionedSvcs, "Provisioned services object is null");

                //Just counting the retuned available and provisioned services will suffice
                int actualNumberOfProvisionedServices = 0;
                int actualNumberOfAvailableServices = 0;

                foreach (var className in availableSvcs.Keys)
                {
                    foreach (var child in availableSvcs[className])
                    {
                        actualNumberOfAvailableServices++;
                    }
                }

                foreach (var className in provisionedSvcs.Keys)
                {
                    foreach (var child in provisionedSvcs[className])
                    {
                        actualNumberOfProvisionedServices++;
                    }
                }

                Assert.AreEqual(expectedAvailableServices.Count,actualNumberOfAvailableServices,String.Format("Available services don't match. Expected: {0} and Returned: {1}",expectedAvailableServices.Count,actualNumberOfAvailableServices));
                Assert.AreEqual(expectedProvisionedServices.Count, actualNumberOfProvisionedServices, String.Format("Provisioned services don't match. Expected: {0} and Returned: {1}", expectedProvisionedServices.Count, actualNumberOfProvisionedServices));

                var actualAvailableServices = availableSvcs.SelectMany(x => x.Value).ToList();
                var actualProvisionedServices = provisionedSvcs.SelectMany(x => x.Value).ToList();

                Assert.AreEqual(0,actualAvailableServices.Where(x => x.Name == serviceToBeFilteredOut).ToList().Count(),"Available services contains value. It should be empty.");
                Assert.AreEqual(0,actualProvisionedServices.Where(x => x.Name == serviceToBeFilteredOut).ToList().Count(),"Provisioned services contains value. It should be empty. Count");
            }
        }
Ejemplo n.º 12
0
        public void Admin_Role_Should_Be_Able_To_See_All_Available_Services()
        {
            using (ShimsContext.Create())
            {
                var testContext = new SIMPLTestContext();
                var session = GetShimmedSession();
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                //set up the services
                ShimCurrentSubscriber.GetInstance = () => new ShimCurrentSubscriber
                {
                    DataProductTypeGet = () => SubscriberEnums.DataProductType.XDsl,
                    VideoProductTypeGet = () => SubscriberEnums.VideoProductType.IpTv,
                    StateGet = () => "CT",
                    WtnGet = () => "2061272727",
                    ProvisionedServicesListGet = () => GetProvisionedServices()
                };

                ShimCurrentUser.AsUserDto = () => new UserDto()
                {
                    Email = "fake_Email",
                    Name = "fake_Name",
                    Role = "Admin"
                };

                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "UITestUser"
                };

                ShimCurrentUser.RetrieveUserRolesString = (x) => new List<int>
                {
                    1
                };

                ShimCurrentUser.AllInstances.RolesGet = (x) => new List<int>
                {
                    1
                };

                //var appCollection = new NameValueCollection();
                //appCollection.Add("AvailableServicesForTechEdit", "ADSL,VDSL");
                //ShimConfigurationManager.AppSettingsGet = () => new NameValueCollection { "",""};

                ShimServices.ProvisioningServicesGet = delegate
                {
                    return GetAvailableServices();
                };

                ShimSubscriberServicesModel.AllInstances._provisionedServicesGet = delegate
                {
                    return GetProvisionedServices();
                };

                var expectedNumberOfAvailableServices = GetAvailableServices().Count;
                var expectedNumberOfProvisionedServices = GetProvisionedServices().Count;

                //Need to call this to instantiate the subscriber service model properly.
                var initialModel = ServicesControllerForTests.Index();
                Assert.IsNotNull(initialModel,"Initial model is null. Index should map out the SubscriberServicesModel");

                var result = ServicesControllerForTests.EditServices(initialModel.Model as SubscriberServicesModel);
                Assert.IsNotNull(result,"Result null, expecting partial result.");
                Assert.IsTrue(result is PartialViewResult);
                var viewModel = (result as PartialViewResult).Model as SubscriberServicesModel;
                Assert.IsNotNull(viewModel);
                var availableSvcs = viewModel.AvailableServicesDictionary;
                var provisionedSvcs = viewModel.ProvisionedServicesDictionary;
                Assert.IsNotNull(availableSvcs,"This property returns the available services for the subscriber and should not be null.");

                //Just counting the retuned available and provisioned services will suffice
                var actualNumberOfAvailableServices = availableSvcs.Keys.SelectMany(className => availableSvcs[className]).Count();

                var actualNumberOfProvisionedServices = provisionedSvcs.Keys.SelectMany(className => provisionedSvcs[className]).Count();

                //Then ALL the available services are displayed in 'Change Subscriber Services' window
                Assert.AreEqual(expectedNumberOfAvailableServices,actualNumberOfAvailableServices,String.Format("Available services mismatch. Expected Services: {0} and Actual Services: {1}",expectedNumberOfAvailableServices,actualNumberOfAvailableServices));
                Assert.AreEqual(expectedNumberOfProvisionedServices, actualNumberOfProvisionedServices, String.Format("Provisioned services mismatch. Expected Services: {0} and Actual Services: {1}", expectedNumberOfProvisionedServices, actualNumberOfProvisionedServices));
            }
        }
        public void Index_hasIpVideoDevices_IpVideoDeviceHasBadUnitAddress()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

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

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

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

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

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = o => session;
                ShimCurrentSubscriber.AllInstances.HasTivoServiceOnlyGet = delegate { return false; };

                // current location
                const string expectedLocationId = "123456789";

                // expected all devices on current location
                var customFieldsDto = RgTestData_CustomFieldsCollection();
                var mainRg = RgTestData_MainRg(customFieldsDto, expectedLocationId);
                var otherRgs = RgTestData_OtherRgList(customFieldsDto, expectedLocationId);
                var ipVideoDevices = new List<EquipmentDto>
                {
                    RgTestData_IpVideoDevice(customFieldsDto, expectedLocationId),
                    RgTestData_IpVideoDevice2(customFieldsDto, expectedLocationId)
                };
                Assert.IsTrue(ipVideoDevices.Any(x => string.IsNullOrWhiteSpace(x.UnitAddress)), "1 of IP video devices should have null or empty unit address");

                // expected search results
                var searchEquipmentsResult = new List<EquipmentDto>();
                searchEquipmentsResult.AddRange(mainRg);
                searchEquipmentsResult.AddRange(otherRgs);
                searchEquipmentsResult.AddRange(ipVideoDevices);

                // set search results to expected search results
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, mySearchFields, myUserDto) => searchEquipmentsResult;

                // set load phones shim
                var loadSubscriberPhonesResult = new List<PhoneDto>();
                ShimCurrentSubscriber.AllInstances.ProvisionedPhonesListGet = o => loadSubscriberPhonesResult;

                // expected custom fields
                var equipmentDataDto = mainRg.First(x => x.SerialNumber.EndsWith("D01"));
                equipmentDataDto.CustomFields = customFieldsDto.ToList();

                // epected RG details
                var expectedIpAddressValue = equipmentDataDto.CustomFields.First(x => x.Label == "WAN_IP_ADDR").Value;
                var expectedBaseModelValue = equipmentDataDto.Type.ONTModel.BaseModel;
                var expectedSerialNumber = equipmentDataDto.SerialNumber.Substring(0, equipmentDataDto.SerialNumber.Length - 3);
                var expectedUnitAddress = equipmentDataDto.UnitAddress;
                var expectedMacAddressValue = equipmentDataDto.CustomFields.First(x => x.Label == "ENET_MAC_ADDR").Value;

                // set WanIpAddress
                ShimCurrentSubscriber.AllInstances.SubIdGet = o => "1234567";
                ShimCurrentSubscriber.AllInstances.WanIpAddressGet = o => expectedIpAddressValue;
                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = (client, subId, userDto) => new SubscriberDto();
                ShimCurrentSubscriber.UpdateWanIpAddressString = (myWanIpAddress) => { };

                // set load equipment for main RG
                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => equipmentDataDto;

                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto = (myTestClient, myUserDto) => customFieldsDto;
                ShimVirtualPathUtility.ToAbsoluteString = (myTestString) => @"http://testapp/images/DVR.png";
                ShimDBCache.LocationsGet = delegate { return new List<Location>(); };

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // call Index of ResidentialGatewayController
                var result = residentialController.Index("12345", expectedLocationId, null) as PartialViewResult ?? new PartialViewResult();

                // validate partial view and model is not null
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result.ViewName.Equals("Index"), "View names do not match.");

                var residentialGatewayModel = (ResidentialGatewayModel)(result.Model);
                Assert.IsNotNull(residentialGatewayModel);

                // validate the ErrorInfo is null
                Assert.IsNull(residentialGatewayModel.ErrorInfo);

                // validate main RG details
                Assert.AreEqual(expectedIpAddressValue, residentialGatewayModel.IPAddress, "IP does not match.");
                Assert.AreEqual(expectedUnitAddress, residentialGatewayModel.UnitAddress, "UnitAddress does not match.");
                Assert.AreEqual(expectedMacAddressValue, residentialGatewayModel.MacAddress, "MacAddress does not match.");
                Assert.AreEqual(expectedBaseModelValue, residentialGatewayModel.Model, "Model number does not match.");
                Assert.AreEqual(expectedSerialNumber, residentialGatewayModel.ID, "Serial number does not match.");

                // validate other RGs list
                Assert.IsTrue(residentialGatewayModel.OtherRGList.Any(), "No other RGs found.");
                Assert.AreEqual(otherRgs.Count, residentialGatewayModel.OtherRGList.Count, "Other RGs count does not match.");
                otherRgs = otherRgs.OrderBy(x => x.SerialNumber).ToList();
                residentialGatewayModel.OtherRGList = residentialGatewayModel.OtherRGList.OrderBy(x => x.ID).ToList();
                for (int i = 0; i < otherRgs.Count; i++)
                {
                    var expected = otherRgs[i];
                    var actual = residentialGatewayModel.OtherRGList[i];
                    Assert.AreEqual(expected.SerialNumber.Substring(0, expected.SerialNumber.Length - 3), actual.ID, "Other RG serial number does not match.");
                    Assert.AreEqual(expected.LocationId, actual.LocationID, "Other RG location id does not match.");
                    Assert.AreEqual(expected.Status, actual.Status, "Other RG status does not match.");
                    Assert.AreEqual(expected.UnitAddress, actual.UnitAddress, "Other RG UnitAddress does not match.");
                    Assert.AreEqual(expected.Type.ONTModel.BaseModel, actual.Model, "Other RG UnitAddress does not match.");
                }

                // validate ip video device
                Assert.IsTrue(residentialGatewayModel.VideoDevices.Any(), "No video devices found.");
                Assert.AreEqual(ipVideoDevices.Count, residentialGatewayModel.VideoDevices.Count, "IP Video devices count does not match.");
                ipVideoDevices = ipVideoDevices.OrderBy(x => x.SerialNumber).ToList();
                residentialGatewayModel.VideoDevices = residentialGatewayModel.VideoDevices.OrderBy(x => x.ID).ToList();

                Assert.IsTrue(ipVideoDevices.Any(x => string.IsNullOrWhiteSpace(x.UnitAddress)), "1 of expected IP video devices should have null or empty unit address");
                for (var i = 0; i < ipVideoDevices.Count; i++)
                {
                    var expected = ipVideoDevices[i];
                    var actual = residentialGatewayModel.VideoDevices[i];
                    Assert.AreEqual(expected.Type.Category.ToString(), actual.Type, "IP Video device type mismatch.");
                    Assert.AreEqual(expected.Type.Model, actual.Model.ModelName, "IP Video device model mismatch.");
                    Assert.AreEqual(expected.SerialNumber, actual.ID, "IP Video device serial number does not match.");
                    Assert.AreEqual(expected.Status, actual.Status, "IP Video device  does not match.");
                    Assert.AreEqual(expected.UnitAddress, actual.GuidInfo.Tooltip, "IP Video device UnitAddress does not match.");
                    if (string.IsNullOrWhiteSpace(expected.UnitAddress))
                    {
                        Assert.IsTrue(string.IsNullOrWhiteSpace(actual.GuidInfo.Tooltip), "Actual unit address should be null for {0}", actual.ID);
                        Assert.AreEqual("No Data", actual.GuidInfo.Guid, "GUID should be displayed as No Data if unit address is null or empty");
                    }
                }
            }
        }
        public void Index_HappyPath()
        {
            using (ShimsContext.Create())
            {

                //Arrange
                var myContext = new SIMPLTestContext();

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

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

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

                // SIMPL.Session.Fakes.ShimCurrentSubscriber.SessionInstanceGet = () => new ShimCurrentSubscriber();

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

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

                //Expected result
                const string expectedIpAddressLabel = "WAN_IP_ADDR";
                const string expectedIpAddressValue = "10.143.22.1";
                const string expectedBaseModelValue = "A5550";
                const string expectedSerialNumber = "PACE99999991";
                const string expectedUnitAddress = "0D-U9-M6-D2-D7";
                const string expectedLocationId = "locId";
                const string expectedRoomLocationLabel = "ROOM_LOCATION";
                const string expectedRoomLocationValue = "TEST ROOM";
                const string expectedMacAddressLable = "ENET_MAC_ADDR";
                const string expectedMacAddressValue = "A0B1C2D3E4F5";

                var customFieldsDto = new List<CustomFieldDto>();
                var expectedIpAddressCustomField = new CustomFieldDto
                {
                    Label = expectedIpAddressLabel,
                    Value = expectedIpAddressValue,
                };
                customFieldsDto.Add(expectedIpAddressCustomField);

                var expectedRoomLocationCustomField = new CustomFieldDto
                {
                    Label = expectedRoomLocationLabel,
                    Value = expectedRoomLocationValue
                };
                customFieldsDto.Add(expectedRoomLocationCustomField);

                var expectedMacAddressCustomField = new CustomFieldDto
                {
                    Label = expectedMacAddressLable,
                    Value = expectedMacAddressValue
                };
                customFieldsDto.Add(expectedMacAddressCustomField);

                var customFieldsCollection = new CustomFieldCollectionDto
                {
                    expectedIpAddressCustomField,
                    expectedRoomLocationCustomField,
                    expectedMacAddressCustomField
                };

                var RgType = new EquipmentTypeDto
                {
                    ONTModel = new ONTModelDto
                    {
                        BaseModel = expectedBaseModelValue
                    },
                    Category = EquipmentCategoryDto.RGDataPort
                };

                var IPVideoType = new EquipmentTypeDto
                {
                    ONTModel = new ONTModelDto
                    {
                        BaseModel = expectedBaseModelValue
                    },
                    Category = EquipmentCategoryDto.DVR,
                    IptvCapable = true
                };

                var equipmentDataDto = new EquipmentDto
                {
                    SerialNumber = expectedSerialNumber + "D01",
                    CustomFields = customFieldsDto,
                    UnitAddress = expectedUnitAddress,
                    LocationId = expectedLocationId,
                    Type = RgType,
                    Status = "ACTIVE"
                };

                var equipmentPhoneDto = new EquipmentDto
                {
                    SerialNumber = expectedSerialNumber + "P01",
                    CustomFields = customFieldsDto,
                    UnitAddress = expectedUnitAddress,
                    LocationId = expectedLocationId,
                    Type = RgType,
                    Status = "ACTIVE"
                };

                var ipVideoDevice = new EquipmentDto
                {
                    SerialNumber = expectedSerialNumber + "P01",
                    CustomFields = customFieldsDto,
                    UnitAddress = expectedUnitAddress,
                    LocationId = expectedLocationId,
                    Type = IPVideoType,
                    Status = "ACTIVE"
                };

                var searchEquipmentsResult = new List<EquipmentDto>();
                searchEquipmentsResult.Add(equipmentDataDto);
                searchEquipmentsResult.Add(equipmentPhoneDto);
                searchEquipmentsResult.Add(ipVideoDevice);

                var loadSubscriberPhonesResult = new List<PhoneDto>();

                // shim CurrentSubscriber WanIpAddress
                ShimCurrentSubscriber.GetInstance = () => new ShimCurrentSubscriber
                {
                    WanIpAddressGet = () => expectedIpAddressValue,
                    ProvisionedPhonesListGet = () => loadSubscriberPhonesResult
                };

                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, mySearchFields, myUserDto) => searchEquipmentsResult;

                equipmentDataDto.CustomFields = customFieldsDto;

                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => equipmentDataDto;

                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto =
                    (myTestClient, myUserDto) => customFieldsCollection;

                ShimVirtualPathUtility.ToAbsoluteString =
                    (myTestString) => @"http://testapp/images/DVR.png";

                ShimDBCache.LocationsGet = delegate { return new List<Location>(); };

                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();
                var result = residentialController.Index("subID", "locID", "devID") as PartialViewResult ?? new PartialViewResult();
                Assert.IsNotNull(result, "Partial view result returned is null.");
                Assert.IsTrue(result.ViewName.Equals("Index"), "View names do not match.");
                Assert.AreEqual(expectedIpAddressValue, ((ResidentialGatewayModel)(result.Model)).IPAddress, "Expected IP does not match with actual IP.");
                Assert.AreEqual(expectedUnitAddress, ((ResidentialGatewayModel)(result.Model)).UnitAddress, "Expected UnitAddress does not match with actual Unit Address.");
                Assert.AreEqual(expectedMacAddressValue, ((ResidentialGatewayModel)(result.Model)).MacAddress, "Expected MacAddress does not match with actual Mac Address.");
                Assert.AreEqual(expectedBaseModelValue, ((ResidentialGatewayModel)(result.Model)).Model, "Expected Model number does not match with actual Model number.");
                Assert.AreEqual(expectedSerialNumber, ((ResidentialGatewayModel)(result.Model)).ID, "Expected serial number does not match with actual serial number.");
                Assert.IsTrue(((ResidentialGatewayModel)(result.Model)).VideoDevices.Any(), "No video devices found.");
                Assert.IsTrue(((ResidentialGatewayModel)(result.Model)).VideoDevices.First().Type.Equals("DVR"), "IP Video device type mismatch.");
                Assert.IsTrue(((ResidentialGatewayModel)(result.Model)).VideoDevices.First().RoomLocation.Any(), "No Room locations found.");
            }
        }
        public void If_TiVo_Only_Subscriber_Redirect_to_RF_Video_Partial()
        {
            using (ShimsContext.Create())
            {

                //Arrange
                var myContext = new SIMPLTestContext();

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

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

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

                // SIMPL.Session.Fakes.ShimCurrentSubscriber.SessionInstanceGet = () => new ShimCurrentSubscriber();

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                        {
                            return null;
                        }
                        if (s == "Subscriber")
                        {
                            return new List<string>();
                        }
                        return null;
                    }
                };

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

                ShimCurrentSubscriber.AllInstances.HasTivoServiceOnlyGet = delegate { return true; };

                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();
                var result = residentialController.Index("subID", "locID", "devID");

                Assert.IsNotNull(result);
                Assert.IsTrue(result is RedirectToRouteResult);

                var action = result as RedirectToRouteResult;

                Assert.AreEqual("LoadVideoMgmt", action.RouteValues["action"], string.Format("The redirect should have been to the LoadVideoMgmt action, instead it redirected to {0}", action.RouteValues["action"]));
                Assert.AreEqual("VideoDevice", action.RouteValues["controller"], string.Format("The redirect should have been to the VideoDevice controller, instead it redirected to {0}", action.RouteValues["controller"]));

            }
        }
        public void ActivateResidentialGateway_hasNoMainRg_hasListOtherRgs_hasIpVideoDevice_ValidateSuccessScenario()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

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

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

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

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

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

                //Expected result
                const string expectedIpAddressLabel = "WAN_IP_ADDR";
                const string expectedIpAddressValue = "10.143.22.1";
                const string expectedBaseModelValue = "A5550";
                const string expectedSerialNumber = "PACE99999991";
                const string expectedUnitAddress = "001E46";
                const string expectedLocationId = "123456789";
                const string expectedRoomLocationLabel = "ROOM_LOCATION";
                const string expectedRoomLocationValue = "TEST ROOM";
                const string expectedMacAddressLable = "ENET_MAC_ADDR";
                const string expectedMacAddressValue = "A0B1C2D3E4F5";
                const string expectedSelectedRoomLabel = "SELECTED_ROOM";
                const string expectedSelectedRoomValue = "MASTER BED ROOM";

                var customFieldsDto = new List<CustomFieldDto>();
                // RG custom fields
                var expectedIpAddressCustomField = new CustomFieldDto
                {
                    Label = expectedIpAddressLabel,
                    Value = expectedIpAddressValue,
                };
                customFieldsDto.Add(expectedIpAddressCustomField);

                var expectedMacAddressCustomField = new CustomFieldDto
                {
                    Label = expectedMacAddressLable,
                    Value = expectedMacAddressValue
                };
                customFieldsDto.Add(expectedMacAddressCustomField);

                // ip video device custom fields
                var expectedRoomLocationCustomField = new CustomFieldDto
                {
                    Label = expectedRoomLocationLabel,
                    Value = expectedRoomLocationValue
                };
                customFieldsDto.Add(expectedRoomLocationCustomField);

                var expectedSelectedRoomCustomField = new CustomFieldDto
                {
                    Label = expectedSelectedRoomLabel,
                    Value = expectedSelectedRoomValue
                };
                customFieldsDto.Add(expectedSelectedRoomCustomField);

                var customFieldsCollection = new CustomFieldCollectionDto
                {
                    expectedIpAddressCustomField,
                    expectedRoomLocationCustomField,
                    expectedMacAddressCustomField
                };

                var rgType = new EquipmentTypeDto
                {
                    ONTModel = new ONTModelDto
                    {
                        BaseModel = expectedBaseModelValue
                    },
                    Category = EquipmentCategoryDto.RGDataPort
                };

                var ipVideoType = new EquipmentTypeDto
                {
                    Model = "ISP7500",
                    Category = EquipmentCategoryDto.DVR,
                    IptvCapable = true
                };

                // main active RG
                var equipmentDataDto = new EquipmentDto
                {
                    SerialNumber = expectedSerialNumber + "D01",
                    CustomFields = customFieldsDto,
                    UnitAddress = expectedUnitAddress,
                    LocationId = expectedLocationId,
                    Type = rgType,
                    Status = "ACTIVE"
                };
                var mainRg = new List<EquipmentDto>
                {
                    equipmentDataDto,
                    new EquipmentDto
                    {
                        SerialNumber = expectedSerialNumber + "P01",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "ACTIVE"
                    },
                    new EquipmentDto
                    {
                        SerialNumber = expectedSerialNumber + "P02",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "ACTIVE"
                    }
                };

                // ip video device
                var ipVideoDevice = new EquipmentDto
                {
                    SerialNumber = "STBTEST1234",
                    CustomFields = new List<CustomFieldDto> { expectedRoomLocationCustomField },
                    UnitAddress = "1234567890",
                    LocationId = expectedLocationId,
                    Type = ipVideoType,
                    Status = "ACTIVE"
                };

                // other RGs on the account
                var otherRgs = new List<EquipmentDto>
                {
                    new EquipmentDto
                    {
                        SerialNumber = "RGCREATE1234" + "D01",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "IGNORE"
                    },
                    new EquipmentDto
                    {
                        SerialNumber = "RGCREATE2345" + "D01",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "IGNORE"
                    },
                    new EquipmentDto
                    {
                        SerialNumber = "RGCREATE3456" + "D01",
                        CustomFields = customFieldsDto,
                        UnitAddress = expectedUnitAddress,
                        LocationId = expectedLocationId,
                        Type = rgType,
                        Status = "IGNORE"
                    },
                };

                // set location
                ShimCurrentSubscriber.AllInstances.LocationIdGet = o => expectedLocationId;

                // set WanIpAddress
                ShimCurrentSubscriber.AllInstances.SubIdGet = o => "1234567";
                ShimCurrentSubscriber.AllInstances.WanIpAddressGet = o => "12:12:12:12";
                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = (client, subId, userDto) => new SubscriberDto();
                ShimCurrentSubscriber.UpdateWanIpAddressString = (myWanIpAddress) => { };

                // set activate residential gateway to true
                ShimRosettianClient.AllInstances.ActivateResidentialGatewayStringStringUserDto =
                    (myTestclient, mylocationId, myDeviceId, userDto) => true;

                // expected search results after Activate RG
                var searchEquipmentsResult = new List<EquipmentDto>();
                searchEquipmentsResult.AddRange(mainRg);
                searchEquipmentsResult.AddRange(otherRgs);
                searchEquipmentsResult.Add(ipVideoDevice);

                // set search results to expected
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myTestClient, mySearchFields, myUserDto) => searchEquipmentsResult;

                // expected custom fields
                equipmentDataDto.CustomFields = customFieldsDto;

                // set load eqiupment for main RG
                ShimRosettianClient.AllInstances.LoadEquipmentStringBooleanUserDto =
                    (myTestClient, myEquipmentId, returnExtraData, myUserDto) => equipmentDataDto;

                // set custom fields
                ShimRosettianClient.AllInstances.GetCustomFieldsUserDto = (myTestClient, myUserDto) => customFieldsCollection;

                // set ip video device path
                ShimVirtualPathUtility.ToAbsoluteString = (myTestString) => @"http://testapp/images/DVR.png";

                // get service for ResidentialGatewayController
                var residentialController = DependencyResolver.Current.GetService<ResidentialGatewayController>();

                // call ActivateResidentialGateway of ResidentialGatewayController
                var result = residentialController.ActivateResidentialGateway(expectedSerialNumber, expectedLocationId) as JsonResult;

                // validate json result
                Assert.IsNotNull(result, "Returned Json result is null");

                dynamic resultData = result.Data;
                var status = resultData.status as string;
                var errorMessage = string.Empty;
                if (status == "error")
                {
                    errorMessage = resultData.errorMessage;
                }
                Assert.AreEqual("valid", status, "status is not valid - {0}", errorMessage);
                var renderedPartial = resultData.returnedPartial as string;
                Assert.IsNotNull(renderedPartial, "Prerendered partial is null.");
            }
        }
Ejemplo n.º 17
0
        public void An_upsell_records_with_a_known_billing_order_number_and_complete_status_is_successfully_updated()
        {
            using (ShimsContext.Create())
            {
                // Setup
                var myContext = new SIMPLTestContext();
                var session = GetShimmedSession();

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Given a user
                // And the user can resolve upsell records
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "abc123"
                };

                // And a known upsell record id
                const int upsellRecordId = 111111;

                // And a complete upsell status
                const int upsellStatus = (int)UpsellStatus.Complete;

                // And a known billing order number
                const string billingOrderNumber = "999999999";

                //And a known billing region
                ShimBusinessFacade.AllInstances.GetDpiRegionFromStateNonStaticString = delegate { return "CT"; };

                // And an known subscriber
                const string subscriberId = "KnownSubId";

                //And the order number validation is turned on
                ShimFeatureFlags.IsEnabledString = delegate { return true; };

                // When updating the upsell record
                var fakeAccountDto = myContext.GetFakeAccountDtoObject();
                fakeAccountDto.Location = myContext.GetFakeLocationDtoObject("111111111");
                var fakeCustomFieldDto = myContext.GetFakeCustomFieldDto();
                var fakeSubscriberDto = myContext.GetFakeSubscriberDto(subscriberId, "TEST", "TEST", "555-555-1212", fakeCustomFieldDto, fakeAccountDto);
                var findOrderResponse = new retrieveCustomerAccountOrderDetailsResponse1
                {
                    retrieveCustomerAccountOrderDetailsResponse = new retrieveCustomerAccountOrderDetailsResponse
                    {
                        retrieveCustomerAccountOrderDetailsOutput = new msg_Customer
                        {
                            Payload = new[]
                            {
                                new Customer
                                {
                                    CustomerAccount = new[]
                                    {
                                        new CustomerAccount
                                        {
                                            CustomerOrder = new[]
                                            {
                                                new CustomerOrder
                                                {
                                                    CustomerOrderItem = new[]
                                                    {
                                                        new CustomerOrderItem()
                            }
                        }
                    }
                                        }
                                    }
                                }
                            }
                        }
                    }
                };
                ShimCustomerOrderInformationClient.AllInstances.SIMPLDALCustomerOrderInformationCustomerOrderInformationretrieveCustomerAccountOrderDetailsretrieveCustomerAccountOrderDetailsRequest = delegate { return findOrderResponse; };
                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = delegate { return fakeSubscriberDto; };

                DAL.Implementation.Fakes.ShimUpsellRepository.AllInstances.UpdateRecordInt32Int32StringString = delegate { };
                var result = UpsellControllerForTests.UpdateUpsellRecord(upsellRecordId, subscriberId, upsellStatus, billingOrderNumber) as HttpStatusCodeResult;

                //Was data returned
                Assert.IsNotNull(result, "No result returned from UpdateUpsellRecord");

                // Then the record is updated

                // And the status indicates the update was successful
                Assert.IsNotNull(result, "Update Upsell Record returned null");
                Assert.AreEqual(200, result.StatusCode, string.Format("The status code returned was not success. It was {0}", result.StatusCode));

            }
        }
Ejemplo n.º 18
0
        public void Upsell_submit_is_partially_successful()
        {
            using (ShimsContext.Create())
            {
                #region Initial Setup
                SIMPLTestContext testContext = new SIMPLTestContext();
                var session = GetShimmedSession();

                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                ShimCurrentSubscriber.GetInstance = () => new ShimCurrentSubscriber
                {
                    DataProductTypeGet = () => SubscriberEnums.DataProductType.XDsl,
                    VideoProductTypeGet = () => SubscriberEnums.VideoProductType.IpTv,
                    StateGet = () => "CT",
                    WtnGet = () => "2061272727",
                    ProvisionedServicesListGet = () => new List<ServiceDto>
                    {
                        new ServiceDto
                        {
                            Action = "None",
                            ClassName = "DATA - DSL SPEED",
                            Description = "12 MBPS/1.5 MBPS",
                            Name = "D12M1M",
                            Type =  ServiceClassTypeDto.None
                        },
                        new ServiceDto
                        {
                            Action = "None",
                            ClassName = "DSL - TECHNOLOGY CODE",
                            Description = "HSIA SERVICES",
                            Name = "VDSL",
                            Type =  ServiceClassTypeDto.None
                        }
                    }
                };

                ShimUpsellRepository.AllInstances.GetUpsellProductClassesDefinitions = delegate
                {
                    return new List<UpsellProductClassDefinitionDto>();
                };

                //Given a user
                //And user is authenticated to process Upsell submission
                var fakeUser = testContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUser;
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "mjw425"
                };

                string upsellJsonData = "[{'ClassName':'DATA - DSL SPEED','Name':'D12M1M','Description':'12MBPS / 1.5MBPS'},{'ClassName':'DATA - DSL SPEED','Name':'D18M1M','Description':'18MBPS / 1.5MBPS'},{'ClassName':'F-SECURE','Name':'CANYW','Description':'Content Anywhere'},{'ClassName':'F-SECURE','Name':'DCPRO','Description':'Dropcam Pro'}]";
                string autorizeBy = "Mark";

                //No need to call Update subscriber hence shimming the method
              //  bool isUpdateSubscriberCalled = false;
                ShimRosettianClient.AllInstances.UpdateSubscriberSubscriberDtoBooleanUserDto = delegate { return true; };

                ShimCurrentSubscriber.UpdateSubscriberDto = delegate { };
                //ShimMailHelper.AllInstances.Send = delegate { };

                #endregion

                const int numOfProductsInTheReq = 2;
                //If num of products are even then half of them will fail. If num of products are odd then every even item in the req will fail.
                const int numOfProductsThatShouldFail = 1;

                //And all the required fields are captured for Upsell submission
                UpsellSubmittedOrder subReq = new UpsellSubmittedOrder
                {
                    SimpleId = 2,
                    SubscriberId = "490000608154",
                    SubscriberName = "DWAYNE BROWN",
                    TelephoneNumber = "9999999999",
                    SubmittedBy = "mjw425",
                    SubmissionDate = new DateTimeOffset(DateTime.Now).ToString(),
                    StatusDescription = UpsellStatus.New.ToString(),
                    AuthorizedBy = "Mark",
                    AccountType = "R",

                };

                List<UpsellSubmittedProduct> prodInReq = new List<UpsellSubmittedProduct>()
            {
                new UpsellSubmittedProduct()
                               {
                                   ProductId = 1,
                                   ProductName = "D18M1M",
                                   ProductDescription = "18MBPS / 1.5MBPS",
                                   productAction = "A"
                               },
                               new UpsellSubmittedProduct()
                               {
                                   ProductId = 2,
                                   ProductName = "D12M1M",
                                   ProductDescription = "12MBPS / 1.5MBPS",
                                   productAction = "R"
                               }
            };

                //And submitting order to Offline Order System is enabled
                bool isFeatureFlagOn = false;
                ShimFeatureFlags.IsEnabledString = (o) => isFeatureFlagOn = true;

                //And failure occurs processing Offline Order Submission
                //When Order is submitted
                OfflineOrderSubmitResponse offlineSubmissionResponse = null;
                bool shouldFailTheSubmission = false;

                ShimOfflineOrderSystemClient.AllInstances.SubmitOrderToOfflineOrderSystemOfflineOrderSubmitRequest =
                              delegate
                              {
                                  if (isFeatureFlagOn)
                                  {

                                      // Since request going to be partially successful we need a way to control that.
                                      //The way control is acheived is by toggeling 'shouldFailTheSubmission' boolean
                                      if (shouldFailTheSubmission)
                                      {
                                          shouldFailTheSubmission = false;
                                          return offlineSubmissionResponse = new OfflineOrderSubmitResponse
                                          {
                                              //return dummy content. this will be different for each
                                              Content = "{'message': 'The request is invalid.','modelState': {'simple.simpleId': ['An error has occurred.','\'Simple Id\' should not be empty.']}}",
                                              IsSuccess = false,
                                              StatusCode = HttpStatusCode.BadRequest
                                          };
                                      }
                                      else
                                      {
                                          shouldFailTheSubmission = true;
                                          //Then Upsell submission is successful
                                          return offlineSubmissionResponse = new OfflineOrderSubmitResponse
                                          {
                                              Content = "",
                                              IsSuccess = true,
                                              StatusCode = HttpStatusCode.Created
                                          };
                                      }

                                  }
                                  return offlineSubmissionResponse;
                              };

                //Then Upsell Submission is saved outside Offline Order System
                ShimUpsellRepository.AllInstances.AddRecordUpsellSubmissionDtoIEnumerableOfUpsellProductChangeDto =
                     delegate
                     {
                         //And all required fields are captured for Upsell submission
                         return new UpsellAddRecordResult()
                         {
                             UpsellNewRecord = subReq,

                             UpsellNewlyAddedProducts = prodInReq,
                         };
                     };

                //Shimming logging of product level failures
                bool didProductFailsLogged = false;
                int numOfProductFailed = 0;
                ShimUpsellRepository.AddOfflineProductFailuresInt32OfflineOrderSubmitResponse = delegate
                {
                    didProductFailsLogged = true;
                    numOfProductFailed++;  //Keeping track of how many products failed to reach Offline Order System
                };

                //Shimming the update status database call
                bool didRecordStatusUpdatedInSIML = false;
                UpsellStatus recStatus = UpsellStatus.Offline_Submission_Successful;
                ShimUpsellRepository.UpdateRecordStatusInt32UpsellStatus = delegate
                {

                    if (numOfProductFailed == numOfProductsInTheReq)  //Two since there are only two product in the data.
                    {
                        recStatus = UpsellStatus.Offline_Submission_Failed;
                    }
                    else if (numOfProductFailed < numOfProductsInTheReq)
                    {
                        recStatus = UpsellStatus.Offline_Submission_Partially_Successful;
                    }

                    return didRecordStatusUpdatedInSIML = true;
                };

                //Shimming method that sends email
                bool isEmailSend = false;
                ShimEmailRepository.AllInstances.SendMail = delegate
                {
                    return isEmailSend = true;
                };

                //Action
                var result = UpsellControllerForTests.SubmitUpsell(upsellJsonData, autorizeBy) as PartialViewResult;

                //Was data returned?
                Assert.IsNotNull(result, "No result returned from UpdateUpsellRecord");

                //And Upsell Offline Order Submission is unsuccessful
                //Assert.IsNotNull(offlineSubmissionResponse, "Offline submission response is null");
                //Assert.IsFalse(offlineSubmissionResponse.IsSuccess, String.Format("Offline submission returned response: {0} and Status Code: {1}", offlineSubmissionResponse.IsSuccess, offlineSubmissionResponse.StatusCode));

                //And record indicate that the submission to the Offline Order System was unsuccessful
                Assert.IsTrue(didRecordStatusUpdatedInSIML, "Record status was not updated in SIMPL. Set value: {0}", didRecordStatusUpdatedInSIML);
                Assert.AreEqual(recStatus, UpsellStatus.Offline_Submission_Partially_Successful, "Record status should be 'Partially Successful'.Instead it was updated to: {0}", recStatus);

                //And Upsell product failed to reach Offline Order System are saved
                Assert.IsTrue(didProductFailsLogged, "Adding product failures to db is not called.");
                Assert.AreEqual(numOfProductFailed, numOfProductsThatShouldFail, String.Format("Num of product logged are not same as the products in request. Failed Product: {0} and Products in req: {1}", numOfProductFailed, numOfProductsThatShouldFail));

                //And email with failure details is send to Offline Order System
                Assert.IsTrue(isEmailSend, "No email is send.");
            }
        }
Ejemplo n.º 19
0
        public void Index_When_Subscriber_Has_CopperFacility_And_Should_Be_Redirected_To_CopperFacility_Page_One_XBox_Multiple_DropTerm_Not_In_The_Correct_Order()
        {
            using (ShimsContext.Create())
            {
                const string subscriberID = "999000795553";
                const string locationID = "";
                const string deviceID = "";

                var session = GetShimmedSession();

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

                var mySIMPLTestContext = new SIMPLTestContext();

                var expectedTDMSwitch = mySIMPLTestContext.GetFakeTDMSwitch();

                var expectedGWR = mySIMPLTestContext.GetFakeGWRDto();

                var expectedDSLAM = mySIMPLTestContext.GetFakeDSLAM();

                const int numberOfXConnectItems = 1;
                var previousXConnectTerminalNames = new string[]
                {
                    "TerminalAssignmentDtoXbox0{0}_PreviousTerminalNameValue"
                };
                var currentXConnectTerminalNames = new string[]
                {
                    "TerminalAssignmentDtoXbox0{0}_TerminalNameValue"
                };
                var expectedXConnectList = mySIMPLTestContext.GetFakeListXConnect(numberOfXConnectItems, previousXConnectTerminalNames, currentXConnectTerminalNames);

                const int numberOfDropTermItems = 3;
                var previousDropTermTerminalNames = new string[]
                {
                    "TerminalAssignmentDtoXbox01_TerminalNameValue",
                    "TerminalAssignmentDtoDropTerm01_TerminalNameValue",
                    "TerminalAssignmentDtoDropTerm02_TerminalNameValue"
                };
                var currentDropTermTerminalNames = new string[]
                {
                    "TerminalAssignmentDtoDropTerm01_TerminalNameValue",
                    "TerminalAssignmentDtoDropTerm02_TerminalNameValue",
                    "TerminalAssignmentDtoDropTerm03_TerminalNameValue",
                };
                var expectedDropTermList = mySIMPLTestContext.GetFakeListDropTerm(numberOfDropTermItems, previousDropTermTerminalNames, currentDropTermTerminalNames);

                var expectedDropTermSequenceList = new List<List<DropTerm>>
                {
                    expectedDropTermList
                };

                var expectedFacilityAddress = mySIMPLTestContext.GetFakeFacilityAddress();

                var localServicePathList = mySIMPLTestContext.GetFakeListServicePath();

                var expectedServiceLocation = mySIMPLTestContext.GetFakeServiceLocation(expectedFacilityAddress, localServicePathList, subscriberID);

                var expectedMappedData = new CopperFacilityViewModel
                {
                    Environment = "Parent_Environment",
                    TDMSwitch = expectedTDMSwitch,
                    GWR = expectedGWR,
                    DSLAM = expectedDSLAM,
                    XConnectList = expectedXConnectList,
                    DropTermSequenceList = expectedDropTermSequenceList,
                    ServiceLocation = expectedServiceLocation
                };

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

                // Fake the CurrentSubscriber.SubId call
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myProperty) => subscriberID;

                // Fake the CurrentSubscriber.SubId call
                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myProperty) => locationID;
                ShimCurrentSubscriber.AllInstances.DpiRegionGet = delegate { return "CT"; };

                var numberOfXBoxItems = numberOfXConnectItems;
                var previousXBoxTerminalNames = previousXConnectTerminalNames;
                var currentXBoxTerminalNames = currentXConnectTerminalNames;
                var fakeListTerminalAssignmentDtoForXBox = mySIMPLTestContext.GetFakeListTerminalAssignmentDtoForXBox(numberOfXBoxItems, previousXBoxTerminalNames, currentXBoxTerminalNames);

                var fakeListTerminalAssignmentDto = fakeListTerminalAssignmentDtoForXBox.ToList();

                var fakeListTerminalAssignmentDtoForDropTerm = mySIMPLTestContext.GetFakeListTerminalAssignmentDtoForDropTerm(numberOfDropTermItems, previousDropTermTerminalNames, currentDropTermTerminalNames);

                // swamp all of the items in the fakeListTerminalAssignmentDtoForDropTerm
                var tempDropTermTerminalAssignmentDto = fakeListTerminalAssignmentDtoForDropTerm[0];
                fakeListTerminalAssignmentDtoForDropTerm[0] = fakeListTerminalAssignmentDtoForDropTerm[1];
                fakeListTerminalAssignmentDtoForDropTerm[1] = fakeListTerminalAssignmentDtoForDropTerm[2];
                fakeListTerminalAssignmentDtoForDropTerm[2] = tempDropTermTerminalAssignmentDto;

                fakeListTerminalAssignmentDto.AddRange(fakeListTerminalAssignmentDtoForDropTerm);

                var fakePairAssignmentDto = mySIMPLTestContext.GetFakePairAssignmentDto(fakeListTerminalAssignmentDto);

                var fakeListPairAssignmentDto = new List<PairAssignmentDto>
                {
                    fakePairAssignmentDto
                };

                var fakeCopperPlantDataDto = mySIMPLTestContext.GetFakeCopperPlantDataDto(fakeListPairAssignmentDto);

                var fakePlantDataDto = new PlantDataDto
                {
                    CopperPlantData = fakeCopperPlantDataDto
                };

                var fakeServiceAddressDto = mySIMPLTestContext.GetFakeServiceAddressDto();

                var fakeGetFacilitiesResponseDto = mySIMPLTestContext.GetFakeGetFacilitiesResponseDto(subscriberID, fakeServiceAddressDto, fakePlantDataDto);

                ShimEnterpriseClient.AllInstances.GetFacilitiesDataGetFacilitiesRequestDtoHeaderArgs =
                    delegate { return fakeGetFacilitiesResponseDto; };

                ShimCurrentSubscriber.AllInstances.FacilitiesDataGet = (myProperty) => fakeGetFacilitiesResponseDto;

                // Fake the FacilityViewModel.ShouldShowFiber call
                ShimFacilityViewModel.AllInstances.GetFacilityTypeStringString = delegate { return FacilityType.Copper; };

                // A single ONT
                EquipmentDto myEquipmentDto1 = new EquipmentDto();
                myEquipmentDto1.Type = new EquipmentTypeDto();
                myEquipmentDto1.Type.ONTModel = new ONTModelDto();
                myEquipmentDto1.SerialNumber = "123456";

                // A single Video Device
                EquipmentDto myEquipmentDto2 = new EquipmentDto();
                myEquipmentDto2.Type = new EquipmentTypeDto();
                myEquipmentDto2.Type.ONTModel = null;
                myEquipmentDto2.SerialNumber = "123456";

                // Build Fake fakeEquipmentDto
                var fakeEquipmentDto = new List<EquipmentDto>();
                fakeEquipmentDto.Add(myEquipmentDto1);
                fakeEquipmentDto.Add(myEquipmentDto2);

                var fakeUserDto = new UserDto()
                {
                    Email = "FakeEmail",
                    Name = "FakeName",
                    Role = "FakeRole"
                };

                // Fake the RosettianClient.SearchEquipment call
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myRosettianClient, mySubscriberID, myUserObject) => fakeEquipmentDto;

                //Fake call to CurrentUser.AsUserDto()
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                // 1st Act
                var result = EquipmentControllerForTests.Index(subscriberID, locationID, deviceID);

                // 1st set of Asserts
                Assert.IsNotNull(result, "EquipmentController Index returned null");
                Assert.IsTrue(result is PartialViewResult, "Not a PartialViewResult");

                // 2nd Act
                var resultPartialViewResult = (PartialViewResult)result;

                // 2nd set of Asserts
                Assert.IsNotNull(resultPartialViewResult, "Cast to PartialViewResult is null");
                Assert.IsNotNull(resultPartialViewResult.Model, "Model is null");
                Assert.IsTrue(resultPartialViewResult.Model is CopperFacilityViewModel, "Model not CopperFacilityViewModel");

                // 3rd Act
                var resultPartialViewResultModel = (CopperFacilityViewModel)resultPartialViewResult.Model;

                // 3rd set of Asserts
                var successCode = "200";
                Assert.AreEqual(successCode, resultPartialViewResultModel.ActionResponse.Code, "Test threw an exception {0}{0}{1}", Environment.NewLine, resultPartialViewResultModel.ActionResponse.Message);

                // 4th Act
                var jss = new JavaScriptSerializer();

                // 4th set of Asserts
                Assert.AreEqual(jss.Serialize(expectedMappedData.DropTermSequenceList), jss.Serialize(resultPartialViewResultModel.DropTermSequenceList), "DropTermSequenceList didn't match");
                Assert.AreEqual(jss.Serialize(expectedMappedData.DSLAM), jss.Serialize(resultPartialViewResultModel.DSLAM), "DSLAM didn't match");
                Assert.AreEqual(jss.Serialize(expectedMappedData.Environment), jss.Serialize(resultPartialViewResultModel.Environment), "Enviroment didn't match");
                Assert.AreEqual(jss.Serialize(expectedMappedData.GWR), jss.Serialize(resultPartialViewResultModel.GWR), "GWR didn't match");
                Assert.AreEqual(jss.Serialize(expectedMappedData.PathCount), jss.Serialize(resultPartialViewResultModel.PathCount), "PathCount didn't match");
                Assert.AreEqual(jss.Serialize(expectedMappedData.ServiceLocation), jss.Serialize(resultPartialViewResultModel.ServiceLocation), "ServiceLocation didn't match");
                Assert.AreEqual(jss.Serialize(expectedMappedData.TDMSwitch), jss.Serialize(resultPartialViewResultModel.TDMSwitch), "TDMSwitch didn't match");
                Assert.AreEqual(jss.Serialize(expectedMappedData.XConnectList), jss.Serialize(resultPartialViewResultModel.XConnectList), "XConnectList didn't match");
            }
        }
Ejemplo n.º 20
0
        public void RefreshDevices_HappyPath()
        {
            //Setup
            var myContext = new SIMPLTestContext();

            using (ShimsContext.Create())
            {
                // Given a user
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

                ShimCurrentSubscriber.AllInstances.LocationIdGet = (currentSubscriber) => "FakeLocationId";
                ShimCurrentSubscriber.AllInstances.MaxStbGet = (currentSubscriber) => "4";

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

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

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

                ShimCurrentSubscriber.SessionInstanceGet = () =>  new ShimCurrentSubscriber();

                // A single ONT
                EquipmentDto myEquipmentDto1 = new EquipmentDto();
                myEquipmentDto1.Status = "ACTIVE";
                myEquipmentDto1.Type = new EquipmentTypeDto();
                myEquipmentDto1.Type.ONTModel = new ONTModelDto();
                myEquipmentDto1.Type.ONTModel.Model = "Model";
                myEquipmentDto1.SerialNumber = "SerialNumber1";

                // A single Video Device
                EquipmentDto myEquipmentDto2 = new EquipmentDto();
                myEquipmentDto2.Status = "IGNORE";
                myEquipmentDto2.Type = new EquipmentTypeDto();
                myEquipmentDto2.Type.ONTModel = null;
                myEquipmentDto2.SerialNumber = "SerialNumber2";

                var equipments = new List<EquipmentDto>();
                equipments.Add(myEquipmentDto1);
                equipments.Add(myEquipmentDto2);

                // Fake the RosettianClient.SearchEquipment call
                ShimRosettianClient.AllInstances.SearchEquipmentSearchFieldsDtoUserDto =
                    (myRosettianClient, mySubscriberID, myUserObject) => equipments;

                // When loading that device
                var actionResult = SubscriberControllerForTests.RefreshDevices() as PartialViewResult;

                Assert.IsNotNull(actionResult, "ViewResult is null.");
                var equipmentModel = actionResult.Model as SubscriberEquipmentModel;
                Assert.IsNotNull(equipmentModel, "ViewModel is null.");
                Assert.IsNotNull(equipmentModel.ONTList, "ONTList is null");
                Assert.IsTrue(equipmentModel.ONTList.Count >= 0);
                Assert.IsNotNull(equipmentModel.VideoDeviceList, "VideoDeviceList is null");
                Assert.IsTrue(equipmentModel.VideoDeviceList.Count >= 0);
            }
        }
Ejemplo n.º 21
0
        public void Index_ProvisioningLocation_withAddresses_withRateCenter_withNetworkLocCode()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            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;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                billingAccountId.PhoneNumberAsId.TelephoneNumber.Number = "TestBillingNumber";
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                // service account
                var serviceAccount = new ServiceAccountDto
                {
                    Address = new ServiceAddressDto{ Address1 = "TestServiceAddress"},
                    IsBTN = false,
                    SubscriberName = "TestServiceName",
                    TN = "TestServiceNumber",
                    USI = "TestServiceUSI",
                };
                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => serviceAccount;

                // Expected provisioning locaton
                var provLocation = new LocationDto
                {
                    ID = "12345666666444",
                    AddressLine1 = "ADDRESS1",
                    AddressLine2 = "ADDRESS2",
                    CityName = "CITY",
                    StateName = "STATE WA",
                    ZipCode = "12345",
                    HeadendCode = "01",
                    NetworkLocationCode = "1234567",
                    RateCenterName = "123456",
                };

                // CurrentSubscriber location
                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => provLocation.ID;
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => provLocation.AddressLine1;
                ShimCurrentSubscriber.AllInstances.Address2Get = (myTestParam) => provLocation.AddressLine2;
                ShimCurrentSubscriber.AllInstances.CityGet = (myTestParam) => provLocation.CityName;
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => provLocation.StateName;
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => provLocation.ZipCode;
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => provLocation.HeadendCode;
                ShimCurrentSubscriber.AllInstances.RateCenterGet = (myTestParam) => provLocation.RateCenterName;
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet =
                    (myTestParam) => provLocation.NetworkLocationCode;
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";

                // account controller
                var accountsController = DependencyResolver.Current.GetService<AccountsController>();

                // call Index action method
                var result = accountsController.Index();

                // results is no null
                Assert.IsNotNull(result);

                var accountTuple = (AccountTuple) result.Model;

                // validate billing info
                Assert.IsTrue(accountTuple.BillingAccount.Address.AddressLine1.Equals("TestBillingAddress"));
                Assert.IsTrue(accountTuple.BillingAccount.TN.Equals("TestBillingNumber"));

                // validate service address
                Assert.AreEqual(serviceAccount.Address.Address1, accountTuple.ServiceAccount.Addresses.ServiceAddress.AddressLine1, "Service Address1 does not match");
                Assert.IsTrue(accountTuple.ServiceAccount.TN.Equals("TestServiceNumber"));

                // validate provisioning location;
                var actualProvLocaton = accountTuple.ServiceAccount.Addresses.ProvisioningAddress.Location;
                Assert.AreEqual(provLocation.ID, actualProvLocaton.LocationID, "Location ID does not match");
                Assert.AreEqual(provLocation.AddressLine1, actualProvLocaton.Address1, "Address1 does not match");
                Assert.AreEqual(provLocation.AddressLine2, actualProvLocaton.Address2, "Address2 does not match");
                Assert.AreEqual(provLocation.HeadendCode, actualProvLocaton.Headend, "Headend does not match");
                Assert.AreEqual(provLocation.CityName, actualProvLocaton.City, "City does not match");
                Assert.AreEqual(provLocation.StateName, actualProvLocaton.State, "State does not match");
                Assert.AreEqual(provLocation.RateCenterName, actualProvLocaton.RateCenter, "RateCenter does not match");
                Assert.AreEqual(provLocation.NetworkLocationCode, actualProvLocaton.NetworkLocationCode, "NetworkLocationCode does not match");
            }
        }
Ejemplo n.º 22
0
        public void Index_HasAddressConflict_True()
        {
            using (ShimsContext.Create())
            {

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            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;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                const string subId = "123456789";
                const string headend = "04";
                const string locId = "123456789";
                var address1 = "2345 TEST ADDRESS1";
                var address2 = "APT 2";
                var city = "REDMOND";
                var state = "WA";
                var zip = "98052";

                // Service Address
                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => new ServiceAccountDto
                {
                    Address = new ServiceAddressDto
                    {
                        Address1 = address1,
                        Address2 = address2,
                        Locality = city,
                        StateOrProvince = state,
                        Postcode = zip
                    },
                };

                // Provisioning Service Address
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => headend;
                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => locId;
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => subId;
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => address1 + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.Address2Get = (myTestParam) => address2 + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.CityGet = (myTestParam) => city + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => state + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => zip + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.RateCenterGet = (myTestParam) => "TestRateCenter";
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet = (myTestParam) => "TestNetworkCode";

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.Index();
                Assert.IsNotNull(result);

                // Validate the HasAddressConflict flag
                var hasAddressConflict = ((AccountTuple) result.Model).ServiceAccount.Addresses.ProvisioningAddress.Location.HasAddressConflict;
                Assert.IsTrue(hasAddressConflict, "HasAddressConflict should be false");
            }
        }
Ejemplo n.º 23
0
        public void Index_HappyPath()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            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;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                billingAccountId.PhoneNumberAsId.TelephoneNumber.Number = "TestBillingNumber";
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => new ServiceAccountDto
                {
                    Address = new ServiceAddressDto{ Address1 = "TestServiceAddress"},
                    IsBTN = false,
                    SubscriberName = "TestServiceName",
                    TN = "TestServiceNumber",
                    USI = "TestServiceUSI"
                };

                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => "123456789";
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => "TestAddressLine1";
                ShimCurrentSubscriber.AllInstances.Address2Get= (myTestParam) => "TestAddressLine2";
                ShimCurrentSubscriber.AllInstances.CityGet= (myTestParam) => "TestCity";
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => "TestState";
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => "TestZip";
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => "TestHeadend";
                ShimCurrentSubscriber.AllInstances.RateCenterGet= (myTestParam) => "TestRateCenter";
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet = (myTestParam) => "TestNetworkCode";
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.Index();
                Assert.IsTrue(((AccountTuple)result.Model).BillingAccount.Address.AddressLine1.Equals("TestBillingAddress"));
                Assert.IsTrue(((AccountTuple)result.Model).BillingAccount.TN.Equals("TestBillingNumber"));
                Assert.IsTrue(((AccountTuple)result.Model).ServiceAccount.Addresses.ServiceAddress.AddressLine1.Equals("TestServiceAddress"));
                Assert.IsTrue(((AccountTuple)result.Model).ServiceAccount.TN.Equals("TestServiceNumber"));

            }
        }
Ejemplo n.º 24
0
        public void List_HappyPath()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            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;

                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myString) => "SAME";

                var list = new List<ServiceAccountDto>()
                {
                    new ServiceAccountDto
                    {
                        Address = new ServiceAddressDto { Address1 = "TestServiceAddress1", LocationId = "SAME"},
                        IsBTN = false,
                        SubscriberName = "TestServiceName",
                        TN = "TestServiceNumber1",
                        USI = "TestServiceUSI1"
                    },
                    new ServiceAccountDto
                    {
                        Address = new ServiceAddressDto { Address1 = "TestServiceAddress3", LocationId = "DIFFERENT"},
                        IsBTN = false,
                        SubscriberName = "TestServiceName",
                        TN = "TestServiceNumber3",
                        USI = "TestServiceUSI3"
                    }
                };

                ShimCurrentSubscriber.AllInstances.ServiceAccountListGet = (myTest) => list;

                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => new ServiceAccountDto
                {
                    Address = new ServiceAddressDto { Address1 = "TestServiceAddress2", LocationId = "SAME"},
                    IsBTN = false,
                    SubscriberName = "TestServiceName2",
                    TN = "TestServiceNumber2",
                    USI = "TestServiceUSI2"
                };

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.List(new DataSourceRequest());
                var gridAccounts = new List<GridAccount>(((IEnumerable<GridAccount>)((DataSourceResult)((JsonResult) result).Data).Data));
                Assert.IsTrue(gridAccounts.Any(ga => ga.Address.Contains("TestServiceAddress3")), "Result does not contain expected data.");
                Assert.IsTrue(gridAccounts.Any(ga => !ga.Address.Contains("TestServiceAddress1")), "Result contained service account having a different location id");
            }
        }
Ejemplo n.º 25
0
        public void When_a_user_updates_an_upsell_record_with_a_malformed_billing_order_number_an_error_is_received()
        {
            using (ShimsContext.Create())
            {
                // Setup

                SIMPLTestContext myContext = new SIMPLTestContext();
                var session = GetShimmedSession();

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Given a user
                // And the user can resolve upsell records
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "abc123"
                };

                // And a known upsell record id
                const int upsellRecordId = 111111;

                // And a complete upsell status
                const int upsellStatus = (int)UpsellStatus.Complete;

                // And a malformed billing order number

                var billingOrderNumber = Convert.ToString(TestContext.DataRow["billingOrderNumber"]);

                //And a known billing region
                ShimBusinessFacade.AllInstances.GetDpiRegionFromStateNonStaticString = delegate { return "CT"; };

                // And a known subscriber
                const string subscriberId = "KnownSubId";

                //And the order number validation is turned on
                ShimFeatureFlags.IsEnabledString = delegate { return true; };

                // When updating the upsell record var currentSubscriber = new ShimCurrentSubscriber();
                var fakeAccountDto = myContext.GetFakeAccountDtoObject();
                fakeAccountDto.Location = myContext.GetFakeLocationDtoObject("111111111");
                var fakeCustomFieldDto = myContext.GetFakeCustomFieldDto();
                var fakeSubscriberDto = myContext.GetFakeSubscriberDto(subscriberId, "TEST", "TEST", "555-555-1212", fakeCustomFieldDto, fakeAccountDto);

                var findOrderResponse = new retrieveCustomerAccountOrderDetailsResponse1()
                {
                    retrieveCustomerAccountOrderDetailsResponse = new retrieveCustomerAccountOrderDetailsResponse()
                    {
                        retrieveCustomerAccountOrderDetailsOutput = new msg_Customer()
                        {

                            Header = new Header
                            {
                                HeaderExtension = new HeaderExtension { ExecutionStatusMessage = new ExecutionStatusMessage() }
                            },
                            Payload = new[]
                            {
                                new Customer()
                            }
                        }
                    }
                };
                ShimCustomerOrderInformationClient.AllInstances.SIMPLDALCustomerOrderInformationCustomerOrderInformationretrieveCustomerAccountOrderDetailsretrieveCustomerAccountOrderDetailsRequest = delegate { return findOrderResponse; };
                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = delegate { return fakeSubscriberDto; };
                SIMPL.DAL.Implementation.Fakes.ShimUpsellRepository.AllInstances.UpdateRecordInt32Int32StringString = delegate { };
                var result = UpsellControllerForTests.UpdateUpsellRecord(upsellRecordId, subscriberId, upsellStatus, billingOrderNumber) as HttpStatusCodeResult;

                // Then the record is not updated
                Assert.IsNotNull(result, "Update Upsell Record returned null");
                Assert.IsNotNull(result.StatusDescription, "No Error Message was found in the response.");

                // And an error is received
                Assert.AreEqual(500, result.StatusCode, "An error status code was not returned to the user.");

                // And the error says Please enter a valid Billing Order Number. Billing Order Numbers are 9 digits or less.
                const string expectedErrorMessage = "Please enter a valid Billing Order Number. Billing Order Numbers are 9 digits or less.";
                Assert.IsTrue(result.StatusDescription.Contains(expectedErrorMessage), string.Format("The error message for billing order number {0} received was {1}, it should have been {2}", billingOrderNumber, result.StatusDescription, expectedErrorMessage));
            }
        }
Ejemplo n.º 26
0
        public void Remarks_HappyPath()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();

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

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

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            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;

                var remarks = new List<PlantRemarkDto>();
                remarks.Add(new PlantRemarkDto
                {
                    ServiceOrderNumber = "#1234",
                    RemarkText = "Remarks"
                });

                ShimEnterpriseClient.AllInstances.GetPlantRemarksGetPlantRemarksRequestDtoHeaderArgs =
                    delegate { return remarks; };

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.Remarks("usi","tn");
                Assert.IsInstanceOfType(result, typeof(PartialViewResult));
                Assert.IsInstanceOfType(result.Model, typeof (IEnumerable<string>));
                var remarkList = new List<string>(((IEnumerable<string>) result.Model));
                Assert.IsTrue(remarkList[0].Contains("#1234") && remarkList[0].Contains("Remarks"));
            }
        }
Ejemplo n.º 27
0
        public void When_a_user_updates_an_upsell_record_with_a_missing_subscriberid_an_error_is_received()
        {
            using (ShimsContext.Create())
            {
                // Setup
                var myContext = new SIMPLTestContext();
                var session = GetShimmedSession();

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Given a user
                // And the user can resolve upsell records
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "abc123"
                };

                // And a known upsell record id
                const int upsellRecordId = 111111;

                // And a complete upsell status
                const int upsellStatus = (int)UpsellStatus.Complete;

                // And a empty billing order number
                var billingOrderNumber = string.Empty;

                //And a known billing region
                ShimBusinessFacade.AllInstances.GetDpiRegionFromStateNonStaticString = delegate { return "CT"; };

                // And a missing subscriber
                var subscriberId = string.Empty;

                //And the order number validation is turned on
                ShimFeatureFlags.IsEnabledString = delegate { return true; };

                // When updating the upsell record
                var fakeAccountDto = myContext.GetFakeAccountDtoObject();
                fakeAccountDto.Location = myContext.GetFakeLocationDtoObject("111111111");
                var fakeCustomFieldDto = myContext.GetFakeCustomFieldDto();
                var fakeSubscriberDto = myContext.GetFakeSubscriberDto(subscriberId, "TEST", "TEST", "555-555-1212", fakeCustomFieldDto, fakeAccountDto);

                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = delegate { return fakeSubscriberDto; };
                DAL.Implementation.Fakes.ShimUpsellRepository.AllInstances.UpdateRecordInt32Int32StringString = delegate { };
                var result = UpsellControllerForTests.UpdateUpsellRecord(upsellRecordId, subscriberId, upsellStatus, billingOrderNumber) as HttpStatusCodeResult;

                // Then the record is not updated
                Assert.IsNotNull(result, "Update Upsell Record returned null");
                Assert.IsNotNull(result.StatusDescription, "No Error Message was found in the response.");

                // And an error is received
                Assert.AreEqual(500, result.StatusCode, "An error status code was not returned to the user");

                // And the error states that a billing order number is required when updating an upsell record
                const string expectedErrorMessage = "SubscriberId is required to update upsell record.";
                Assert.IsTrue(result.StatusDescription.Contains(expectedErrorMessage), string.Format("The error message received was {0}, it should have been {1}", result.StatusDescription, expectedErrorMessage));
            }
        }
Ejemplo n.º 28
0
        public void A_user_logs_in_when_Single_Concurrent_Login_Feature_is_enabled_and_is_able_to_successfully_log_in()
        {
            using (ShimsContext.Create())
            {
                // Given a known user that is not logged in yet
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                LoginControllerForTests.ControllerContext = new ControllerContext()
                {
                    HttpContext = contextStub
                };

                #endregion LoginModel class, AttemptToLogUserIn method

                // And the Single Concurrent Login Feature is enabled

                // As there are unit tests for IsCheckEnabledActor, I am mocking the reference to IsCheckEnabled
                var wasIsCheckEnabledCalled = false;
                ShimSingleConcurrentLoginRules.AllInstances.IsCheckEnabled = (resultValue) =>
                {
                    wasIsCheckEnabledCalled = true;
                    return true;
                };

                // When that user is trying to log in

                #region LoginModel class, AttemptToLogUserIn method

                var wasASPPAuthenticateCalled = false;
                ShimUserManagement.AllInstances.AuthenticateStringString = (userNameValue, passwordValue, results) =>
                {
                    wasASPPAuthenticateCalled = true;
                    return UserManagement.AuthenticationResults.Success;
                };

                var wasASPPGetUserDetailsCalled = false;
                ShimUserManagement.AllInstances.GetUserDetailsString = (userNameValue, results) =>
                {
                    wasASPPGetUserDetailsCalled = true;
                    return new ASPP_Users();
                };

                var wasASPPGetUserGroupsCalled = false;
                ShimUserManagement.AllInstances.GetUserGroupsString = (userNameValue, results) =>
                {
                    wasASPPGetUserGroupsCalled = true;

                    // need to add at least one group - doing just enough to get beyond the guard in LoginModel.cs
                    var myASPP_Group = new ASPP_Groups
                    {
                        Group_ID = 1
                    };

                    return new List<ASPP_Groups>
                    {
                        myASPP_Group
                    };
                };

                // Then the data is saved correctly

                var wasCreateSIMPLLoginTrackerRecordCalled = false;
                ShimSIMPLSessionEntitiesRepository.AllInstances.CreateSIMPLLoginTrackerRecordStringString = (method, userNameValue, aspNetSessionIdValue) =>
                {
                    wasCreateSIMPLLoginTrackerRecordCalled = true;
                    return new SIMPLLoginTracker { SIMPLUsername = "******", ASPNETSessionId = "doesNotMatter", SIMPLLoginTrackerId = 1, SIMPLLoginTimeUtc = DateTime.UtcNow };
                };

                // And the data is added to the cache correctly

                var wasAddSIMPLLoginTrackerRecordToCacheCalled = false;
                ShimSIMPLSessionEntitiesCache.AddSIMPLLoginTrackerRecordToCacheStringSIMPLLoginTracker = (userNameValue, myLoginTrackerValue) =>
                {
                    wasAddSIMPLLoginTrackerRecordToCacheCalled = true;
                    return true;
                };

                // And the user is logged in successfully

                #region back in the LoginViewModel class, AttemptToLogUserIn method

                var session = new ShimHttpSessionState { SessionIDGet = () => "doesNotMatter"};
                var context = new ShimHttpContext();
                var applicationShim = new ShimHttpApplicationState();
                context.ApplicationGet = () => applicationShim;
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                var wasCurrentUserSetInstanceStringCalled = false;
                var currentUserSetInstanceCount = 0;
                ShimCurrentUser.SetInstanceString = (uniqueId) =>
                {
                    wasCurrentUserSetInstanceStringCalled = true;
                    currentUserSetInstanceCount++;
                };

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

                var wasLoginModelSyncWithOrImportDataFromASPPCalled = false;
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingServiceValue, userNameSentToLoginModelValue) =>
                {
                    wasLoginModelSyncWithOrImportDataFromASPPCalled = true;
                };

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

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

                var wasFormsAuthenticationSetAuthCookieCalled = false;
                ShimFormsAuthentication.SetAuthCookieStringBoolean = (userNameValue, createPersistentCookieValue) =>
                {
                    wasFormsAuthenticationSetAuthCookieCalled = true;
                };

                #endregion back in the LoginViewModel class, AttemptToLogUserIn method

                var result = LoginControllerForTests.UserLogin(userName, password, returnUrl);
                Assert.IsNotNull(result, "LoginController returned null");
                Assert.IsTrue(result is RedirectResult, "LoginController didn't return a RedirectResult");

                var resultRedirectResult = result as RedirectResult;
                Assert.AreEqual(returnUrl, resultRedirectResult.Url, "URL did not match expected value");

                Assert.IsTrue(wasIsCheckEnabledCalled, "wasIsCheckEnabledCalled is false");
                Assert.IsTrue(wasCreateSIMPLLoginTrackerRecordCalled, "wasCreateSIMPLLoginTrackerRecordCalled is false");
                Assert.IsTrue(wasAddSIMPLLoginTrackerRecordToCacheCalled, "wasAddSIMPLLoginTrackerRecordToCacheCalled is false");

                Assert.IsTrue(wasASPPAuthenticateCalled, "wasASPPAuthenticateCalled is false");
                Assert.IsTrue(wasASPPGetUserDetailsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasASPPGetUserGroupsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasCurrentUserSetInstanceStringCalled, "wasCurrentUserSetInstanceStringCalled is false");
                Assert.AreEqual(2, currentUserSetInstanceCount, "currentUserSetInstanceCount did not match expected value");
                Assert.IsTrue(wasCurrentUserSessionInstanceGetCalled, "wasCurrentUserSessionInstanceGetCalled is false");
                Assert.IsTrue(wasCurrentUserClearCalled, "wasCurrentUserClearCalled is false");
                Assert.IsTrue(wasLoginModelSyncWithOrImportDataFromASPPCalled, "wasLoginModelSyncWithOrImportDataFromASPPCalled is false");
                Assert.IsTrue(wasUserEventsInitializeSessionCalled, "wasUserEventsInitializeSessionCalled is false");
                Assert.IsTrue(wasFormsAuthenticationSetAuthCookieCalled, "wasFormsAuthenticationSetAuthCookieCalled is false");
            }
        }
Ejemplo n.º 29
0
        public void When_a_user_updates_an_upsell_record_with_a_unknown_subscriberid_an_error_is_received()
        {
            using (ShimsContext.Create())
            {
                // Setup
                var myContext = new SIMPLTestContext();
                var session = GetShimmedSession();

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Given a user
                // And the user can resolve upsell records
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "abc123"
                };

                // And a known upsell record id
                const int upsellRecordId = 111111;

                // And a complete upsell status
                const int upsellStatus = (int)UpsellStatus.Complete;

                // And a known billing order number
                var billingOrderNumber = "021348548";

                //And a known billing region
                ShimBusinessFacade.AllInstances.GetDpiRegionFromStateNonStaticString = delegate { return "CT"; };

                // And an unknown subscriber
                const string subscriberId = "UnknownSubId";

                //And the order number validation is turned on
                ShimFeatureFlags.IsEnabledString = delegate { return true; };

                // When updating the upsell record
                ShimRosettianClient.AllInstances.LoadSubscriberStringUserDto = delegate { throw new System.Exception("Subscriber not found");};
                DAL.Implementation.Fakes.ShimUpsellRepository.AllInstances.UpdateRecordInt32Int32StringString = delegate { };
                var result = UpsellControllerForTests.UpdateUpsellRecord(upsellRecordId, subscriberId, upsellStatus, billingOrderNumber) as HttpStatusCodeResult;

                //Was data returned?
                Assert.IsNotNull(result, "No result returned from UpdateUpsellRecord");

                // Then the record is not updated
                Assert.IsNotNull(result, "Update Upsell Record returned null");
                Assert.IsNotNull(result.StatusDescription, "No Error Message was found in the response.");

                // And an error is received
                Assert.AreEqual(500, result.StatusCode, "An error status code was not returned to the user");

                // And the error states that the upsell record needs to contain a known subscriber
                const string expectedErrorMessage = "There was an issue retrieving subscriber information from Triad. Please verify this subscriber id exists.";
                Assert.IsTrue(result.StatusDescription.Contains(expectedErrorMessage), string.Format("The error message received was {0}, it should have been {1}", result.StatusDescription, expectedErrorMessage));
            }
        }
Ejemplo n.º 30
0
        public void SyncPlantData_SadPath()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var myContext = new SIMPLTestContext();
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;

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

                ShimCurrentUser.AsUserDto = () => new SIMPLTestContext().GetFakeUserDtoObject();

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

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

                // Expected Result
                var expectedResult = new
                {
                    status = "error",
                    errorMessage = "There was an error while updating the data -- please try again"
                };

                var fakeCurrentSubscriber = new ShimCurrentSubscriber
                {
                    DpiRegionGet = () => "CT"
                };

                ShimCurrentSubscriber.SessionInstanceGet = () => fakeCurrentSubscriber;

                // Call FacilitiesController SyncPlantData
                var actualResult = FacilitiesControllerForTests.SyncPlantData() as JsonResult;

                // Test Validation
                Assert.IsNotNull(actualResult, "JsonResult returned is null");
                Assert.IsNotNull(actualResult, "JsonResult Data returned is null");
                Assert.AreEqual(expectedResult.ToString(), actualResult.Data.ToString());
            }
        }
Ejemplo n.º 31
0
        public void The_upsell_pricing_link_is_correctly_displayed_for_a_customer_with_a_known_state()
        {
            using (ShimsContext.Create())
            {
                // Setup
                ShimUpsellRepository.AllInstances.GetUpsellServiceClassesByPlatformTypeInt32Int32 = delegate { return new List<string>(); };
                ShimUpsellRepository.AllInstances.GetCustomUpsellProductsInt32Int32 = delegate { return new List<UpsellProductDto>(); };
                SIMPL.DAL.Rosettian.Fakes.ShimServices.ProvisioningServicesGet = delegate { return new List<ServiceDto>(); };
                ShimUpsellModel.AllInstances.SetCurrentProductsDictionary = delegate { return new SortedDictionary<string, List<ServiceDto>>(); };
                ShimUpsellModel.AllInstances.SetAvailableProductsDictionary = delegate { return new SortedDictionary<string, SortedList<string, ServiceDto>>(); };
                SIMPL.DAL.Rosettian.Fakes.ShimData.ValidCityStateZipsGet = () => new List<LocationDto>() { new LocationDto() { StateName = "CT" } };
                var myContext = new SIMPLTestContext();
                var session = GetShimmedSession();

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Given a user
                var fakeUserDto = myContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUserDto;
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "abc123",

                };

                //And a known subscriber
                //And the subscriber has a known state
                ShimCurrentSubscriber.GetInstance = () => new ShimCurrentSubscriber
                {
                    DataProductTypeGet = () => SubscriberEnums.DataProductType.XDsl,
                    VideoProductTypeGet = () => SubscriberEnums.VideoProductType.IpTv,
                    StateGet = () => "CT"
                };

                var result = UpsellControllerForTests.LoadUpsellContent() as PartialViewResult;

                //Then the upsell submission window is returned
                Assert.IsNotNull(result, "The response from the LoadUpsellContent was null");

                //Then the upsell submission window is returned
                Assert.IsNotNull(result, "The response from the LoadUpsellContent was null");

                // And the upsell link is returned
                // And the upsell link is correctly formed
                var upsellModel = result.Model as UpsellModel;

                //Does the UpsellModel exiat
                Assert.IsNotNull(upsellModel);

                //Is the UpsellModel set to show pricing?
                Assert.IsTrue(upsellModel.ShouldShowUpsellPricing, "ShouldShowUpsellPricing should have a value of true.");

                //If the UpsellModel is supposed to show pricing, does it?
                Assert.IsNotNull(upsellModel.UpsellPricingLink, "Upsell Pricing Link was null.");

                //Is the UpsellPricing URL the expected one
                var expectedUrl = string.Format("{0}/CT", ConfigurationManager.AppSettings["UpsellPricingURL"]);

                //TODO: The UpsellPricingLink is making a web call so the test is an integration test, not a unit test.
                //TODO: We need to either move the test to the integration test or fake the web call in the method. See Visual Studio team issue 24452
                var upsellPricingLink = upsellModel.UpsellPricingLink;
                Assert.AreEqual(expectedUrl, upsellPricingLink, string.Format("Upsell Pricing Link should be {0}. It was {1}", expectedUrl, upsellPricingLink));
            }
        }
Ejemplo n.º 32
0
        private void SetUpShims(ServiceDto aServiceDto)
        {
            // Fake the session state for HttpContext
            var session = new 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;

            //This is where the fake data is inserted
            ShimCurrentSubscriber.AllInstances.ProvisionedServicesListGet = (myTest) => new List<ServiceDto>
            {
                aServiceDto
            };
        }
Ejemplo n.º 33
0
        public void Upsell_Order_is_successfully_submitted_to_Offline_Order_System_with_required_fields()
        {
            using (ShimsContext.Create())
            {
                #region Initial Setup

                SIMPLTestContext testContext = new SIMPLTestContext();
                var session = GetShimmedSession();

                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                ShimCurrentSubscriber.GetInstance = () => new ShimCurrentSubscriber
                {
                    DataProductTypeGet = () => SubscriberEnums.DataProductType.XDsl,
                    VideoProductTypeGet = () => SubscriberEnums.VideoProductType.IpTv,
                    StateGet = () => "CT",
                    WtnGet = () => "2061272727",
                    ProvisionedServicesListGet = () => new List<ServiceDto>
                    {
                        new ServiceDto
                        {
                            Action = "None",
                            ClassName = "DATA - DSL SPEED",
                            Description = "12 MBPS/1.5 MBPS",
                            Name = "D12M1M",
                            Type = ServiceClassTypeDto.None
                        },
                        new ServiceDto
                        {
                            Action = "None",
                            ClassName = "DSL - TECHNOLOGY CODE",
                            Description = "HSIA SERVICES",
                            Name = "VDSL",
                            Type = ServiceClassTypeDto.None
                        }
                    }
                };

                ShimUpsellRepository.AllInstances.GetUpsellProductClassesDefinitions = delegate
                {
                    return new List<UpsellProductClassDefinitionDto>();
                };

                //Given a user
                //And user is authenticated to process Upsell submission
                var fakeUser = testContext.GetFakeUserDtoObject();
                ShimCurrentUser.AsUserDto = () => fakeUser;
                ShimCurrentUser.GetInstance = () => new ShimCurrentUser
                {
                    UniqueIdGet = () => "mjw425"
                };

                string upsellJsonData =
                    "[{'ClassName':'DATA - DSL SPEED','Name':'D12M1M','Description':'12MBPS / 1.5MBPS'},{'ClassName':'DATA - DSL SPEED','Name':'D18M1M','Description':'18MBPS / 1.5MBPS'},{'ClassName':'F-SECURE','Name':'CANYW','Description':'Content Anywhere'},{'ClassName':'F-SECURE','Name':'DCPRO','Description':'Dropcam Pro'}]";
                string autorizeBy = "Mark";

                //No need to call Update subscriber hence shimming the method
                ShimRosettianClient.AllInstances.UpdateSubscriberSubscriberDtoBooleanUserDto = delegate { return true; };

                ShimCurrentSubscriber.UpdateSubscriberDto = delegate { };
                //ShimMailHelper.AllInstances.Send = delegate { };

                #endregion

                // And all required fields are captured for Upsell submission
                UpsellSubmittedOrder subReq = new UpsellSubmittedOrder
                {
                    SimpleId = 2,
                    SubscriberId = "490000608154",
                    SubscriberName = "DWAYNE BROWN",
                    TelephoneNumber = "9999999999",
                    SubmittedBy = "mjw425",
                    SubmissionDate = new DateTimeOffset(DateTime.Now).ToString(),
                    StatusDescription = UpsellStatus.New.ToString(),
                    AuthorizedBy = "Mark",
                    AccountType = "R",
                };

                List<UpsellSubmittedProduct> prodInReq = new List<UpsellSubmittedProduct>()
                {
                    new UpsellSubmittedProduct()
                    {
                        ProductId = 1,
                        ProductName = "D18M1M",
                        ProductDescription = "18MBPS / 1.5MBPS",
                        productAction = "A"
                    },
                    new UpsellSubmittedProduct()
                    {
                        ProductId = 2,
                        ProductName = "D12M1M",
                        ProductDescription = "12MBPS / 1.5MBPS",
                        productAction = "R"
                    }
                };

                // And submitting order to Offline Order System is enabled
                ShimFeatureFlags.IsEnabledString = (o) => true;

                // When Upsell submission is send to Offline Order System
                //Shimming method which sends request to Offline Order System
                OfflineOrderSubmitResponse offlineSubmissionResponse = null;
                bool isSubmitToOfflineCalled = false;
                ShimOfflineOrderSystemClient.AllInstances.SubmitOrderToOfflineOrderSystemOfflineOrderSubmitRequest =
                    delegate
                    {
                        isSubmitToOfflineCalled = true;
                            //Then Upsell submission is successful
                             offlineSubmissionResponse = new OfflineOrderSubmitResponse
                            {
                                Content = "",
                                IsSuccess = true,
                                StatusCode = HttpStatusCode.Created
                            };

                        return offlineSubmissionResponse;
                    };

                //Shimming method which save the upsell order in SIMPL - Satisfy saving submit outside Offline Order Sytem
                bool isRecordSavedInSIMPL = false;
                UpsellAddRecordResult addedRecord = null;
                ShimUpsellRepository.AllInstances.AddRecordUpsellSubmissionDtoIEnumerableOfUpsellProductChangeDto =
                    delegate
                    {
                        isRecordSavedInSIMPL = true;
                        //And all required fields are captured for Upsell submission
                        addedRecord = new UpsellAddRecordResult()
                        {
                            UpsellNewRecord = subReq,

                            UpsellNewlyAddedProducts = prodInReq,
                        };
                        return addedRecord;
                    };

                //Shimming the databse update which changes the status of the record
                bool didRecordStatusUpdatedInSIML = false;
                ShimUpsellRepository.UpdateRecordStatusInt32UpsellStatus = delegate
                {
                    return didRecordStatusUpdatedInSIML = true;
                };

                //Action
                var result = UpsellControllerForTests.SubmitUpsell(upsellJsonData, autorizeBy) as PartialViewResult;

                //Was data returned?
                Assert.IsNotNull(result, "No result returned from UpdateUpsellRecord");

                // And Upsell Submission is saved outside Offline Order System
                Assert.IsTrue(isRecordSavedInSIMPL, "Order is not saved in SIMPL");
                Assert.IsNotNull(addedRecord,"Record added in SIMPL is Null");
                // Then Upsell submission is successful
                // And successful response is returned by Offline Order System
                Assert.IsTrue(isSubmitToOfflineCalled,"Offline Service was not called");
                Assert.IsNotNull(offlineSubmissionResponse,"The offline response is null");
                Assert.IsTrue(offlineSubmissionResponse.IsSuccess,
                    String.Format("Upsell submission is not successful. The returned response is: {0}",
                        offlineSubmissionResponse.IsSuccess));
                Assert.AreEqual(offlineSubmissionResponse.StatusCode, HttpStatusCode.Created,
                    string.Format("Invalid code the recieved from the service call. Expected: {0}, Recieved: {1}",
                        HttpStatusCode.Created, offlineSubmissionResponse.StatusCode));

                // And record indicates that the submission to the Offline Order System was successful
                Assert.IsTrue(didRecordStatusUpdatedInSIML,
                    "Record status is not updated, which indicates usccessful submission to Offline Order System");
            }
        }