コード例 #1
0
ファイル: DomainExtractorTests.cs プロジェクト: frapid/frapid
 public void ShouldExtractDomainNameTest(string url, string expected)
 {
     var logger = new FakeLogger();
     var extractor = new DomainNameExtractor(logger);
     string result = extractor.GetDomain(url);
     Assert.Equal(expected, result);
 }
コード例 #2
0
        public void InterceptWithGenericArgAndPredicate_TwoInterceptors_InterceptsTheInstanceWithBothInterceptors()
        {
            // Arrange
            var logger = new FakeLogger();

            var container = new Container();

            container.RegisterSingleton<ILogger>(logger);
            container.Register<ICommand, CommandThatLogsOnExecute>();

            container.InterceptWith<InterceptorThatLogsBeforeAndAfter>(IsACommandPredicate);
            container.InterceptWith<InterceptorThatLogsBeforeAndAfter2>(IsACommandPredicate);

            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.BeforeText = "Start1 ");
            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter2>(i => i.BeforeText = "Start2 ");
            container.RegisterInitializer<CommandThatLogsOnExecute>(c => c.ExecuteLogMessage = "Executing");
            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.AfterText = " Done1");
            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter2>(i => i.AfterText = " Done2");
            
            // Act
            var command = container.GetInstance<ICommand>();

            command.Execute();

            // Assert
            Assert.AreEqual("Start2 Start1 Executing Done1 Done2", logger.Message);
        }
コード例 #3
0
        public void Intercept_CollectionWithRegistrationInstances_InterceptsTheInstances()
        {
            var logger = new FakeLogger();

            var container = new Container();

            container.RegisterSingleton<ILogger>(logger);
            container.RegisterCollection<ICommand>(new[] 
            {
                Lifestyle.Transient.CreateRegistration(typeof(ICommand), typeof(ConcreteCommand), container),
                Lifestyle.Transient.CreateRegistration(typeof(ConcreteCommand), container),
            });

            container.InterceptWith<InterceptorThatLogsBeforeAndAfter>(IsACommandPredicate);

            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.BeforeText = "Log ");

            // Act
            var commands = container.GetAllInstances<ICommand>().ToList();

            commands.ForEach(Execute);

            // Assert
            Assert.AreEqual("Log Log ", logger.Message);
        }
コード例 #4
0
        public ActionResult TestSettings(TestSmtpSettings testSettings)
        {
            ILogger logger = null;
            try {
                var fakeLogger = new FakeLogger();
                var smtpChannelComponent = _smtpChannel as Component;
                if (smtpChannelComponent != null) {
                    logger = smtpChannelComponent.Logger;
                    smtpChannelComponent.Logger = fakeLogger;
                }

                // Temporarily update settings so that the test will actually use the specified host, port, etc.
                var smtpSettings = _orchardServices.WorkContext.CurrentSite.As<SmtpSettingsPart>();

                smtpSettings.Address = testSettings.From;
                smtpSettings.Host = testSettings.Host;
                smtpSettings.Port = testSettings.Port;
                smtpSettings.EnableSsl = testSettings.EnableSsl;
                smtpSettings.RequireCredentials = testSettings.RequireCredentials;
                smtpSettings.UseDefaultCredentials = testSettings.UseDefaultCredentials;
                smtpSettings.UserName = testSettings.UserName;
                smtpSettings.Password = testSettings.Password;

                if (!smtpSettings.IsValid()) {
                    fakeLogger.Error("Invalid settings.");
                }
                else {
                    _smtpChannel.Process(new Dictionary<string, object> {
                        {"Recipients", testSettings.To},
                        {"Subject", testSettings.Subject},
                        {"Body", testSettings.Body},
                        {"ReplyTo", testSettings.ReplyTo},
                        {"Bcc", testSettings.Bcc},
                        {"CC", testSettings.Cc}
                    });
                }

                if (!String.IsNullOrEmpty(fakeLogger.Message)) {
                    return Json(new { error = fakeLogger.Message });
                }

                return Json(new {status = T("Message sent.").Text});
            }
            catch (Exception e) {
                return Json(new {error = e.Message});
            }
            finally {
                var smtpChannelComponent = _smtpChannel as Component;
                if (smtpChannelComponent != null) {
                    smtpChannelComponent.Logger = logger;
                }

                // Undo the temporarily changed smtp settings.
                _orchardServices.TransactionManager.Cancel();
            }
        }
コード例 #5
0
        private static ExpiredFileRemovalJob GetTestObject(List <UploadedFile> files)
        {
            IUploadedFileRepository repository = Substitute.For <IUploadedFileRepository>();

            repository.GetFiles().Returns(Task.FromResult <IList <UploadedFile> >(files.ToList()));
            repository.When(r => r.Delete(Arg.Any <FileIdentifier>()))
            .Do(c => files.RemoveAll(f => c.Arg <FileIdentifier>().Equals(f.Id)));

            return(new ExpiredFileRemovalJob(repository, FakeLogger.Get <ExpiredFileRemovalJob>()));
        }
コード例 #6
0
        public void Add_AnyString_WritesToLog(string number, string loggedMessage)
        {
            IMyLogger logger = new FakeLogger();

            var calculator = StringCalculatorFactory(true, logger);

            calculator.Add(number);

            Assert.AreEqual(loggedMessage, logger.Message);
        }
コード例 #7
0
        public void GetLdapUserManipulator()
        {
            var configRepo    = new LdapConfigRepository();
            var logger        = new FakeLogger();
            var ldapConnector = LdapConnectorFactory.GetLdapConnector(new LdapAdminModeChecker(configRepo), configRepo, logger);
            ILdapUserManipulator ldapUserManipulator = LdapUserManipulatorFactory.GetUserManipulator(ldapConnector,
                                                                                                     logger, configRepo);

            Assert.IsInstanceOfType(ldapUserManipulator, typeof(ILdapUserManipulator));
        }
コード例 #8
0
ファイル: DomainValidatorTests.cs プロジェクト: frapid/frapid
        public void ValidatorTest(string domainName, bool expected)
        {
            var logger = new FakeLogger();
            var seriazlier = new FakeDomainSerializer();

            var validator = new DomainValidator(logger, seriazlier);
            bool result = validator.IsValid(domainName);

            Assert.Equal(expected, result);
        }
コード例 #9
0
ファイル: SslDomainCheckTests.cs プロジェクト: frapid/frapid
        public void CheckIfSslIsEnforcedTest(string domain, bool shouldBeEnforced)
        {
            var logger = new FakeLogger();
            var serializer = new FakeDomainSerializer();

            var check = new SslDomainCheck(logger, serializer);
            bool result = check.EnforceSsl(domain);

            Assert.Equal(shouldBeEnforced, result);
        }
コード例 #10
0
ファイル: ClientStoreTests.cs プロジェクト: AChumbler/idsrvEx
        public async Task FindClientByIdAsync_WhenClientDoesNotExist_ExpectNull(DbContextOptions <ConfigurationDbContext> options)
        {
            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                var store  = new ClientStore(context, FakeLogger <ClientStore> .Create());
                var client = await store.FindClientByIdAsync(Guid.NewGuid().ToString());

                client.Should().BeNull();
            }
        }
コード例 #11
0
 void CreateViewModel(FakePackageManagementSolution solution)
 {
     viewModelParent            = CreateViewModelParent();
     viewModel                  = new TestablePackageViewModel(viewModelParent, solution);
     fakePackage                = viewModel.FakePackage;
     this.fakeSolution          = solution;
     packageManagementEvents    = viewModel.PackageManagementEvents;
     fakeLogger                 = viewModel.FakeLogger;
     fakeUninstallPackageAction = solution.FakeProjectToReturnFromGetProject.FakeUninstallPackageAction;
 }
コード例 #12
0
        public void CheckIfSslIsEnforcedTest(string domain, bool shouldBeEnforced)
        {
            var logger     = new FakeLogger();
            var serializer = new FakeDomainSerializer();

            var  check  = new SslDomainCheck(logger, serializer);
            bool result = check.EnforceSsl(domain);

            Assert.Equal(shouldBeEnforced, result);
        }
コード例 #13
0
        public void TryRemoveLoggerTest()
        {
            var logger = new FakeLogger();

            _compoundLogger.TryAddLogger(logger);
            Assert.IsNotEmpty(_compoundLogger.Loggers);

            _compoundLogger.TryRemoveLogger(logger);
            Assert.IsEmpty(_compoundLogger.Loggers);
        }
コード例 #14
0
        public void TestConvention(string domain, string expected)
        {
            var logger     = new FakeLogger();
            var serializer = new FakeDomainSerializer();

            var    convention = new ByConvention(logger, serializer);
            string result     = convention.GetTenantName(domain);

            Assert.Equal(expected, result);
        }
コード例 #15
0
        public void SetUp()
        {
            _parser = new FakeParser();
            _logger = new FakeLogger();

            _fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>());
            _directory  = new MockDirectoryInfo(_fileSystem, @"C:\databasename");

            _service = new FileSystemScriptRepository(_directory, "servername", databaseName, _fileSystem, _parser, _logger, true);
        }
コード例 #16
0
ファイル: ByConventionTests.cs プロジェクト: frapid/frapid
        public void TestOrConvention(string domain, string or, string expected)
        {
            var logger = new FakeLogger();
            var serializer = new FakeDomainSerializer();

            var convention = new ByConvention(logger, serializer);
            string result = convention.GetTenantName(domain, or);

            Assert.Equal(expected, result);
        }
コード例 #17
0
        public void ValidatorTest(string domainName, bool expected)
        {
            var logger     = new FakeLogger();
            var seriazlier = new FakeDomainSerializer();

            var  validator = new DomainValidator(logger, seriazlier);
            bool result    = validator.IsValid(domainName);

            Assert.Equal(expected, result);
        }
コード例 #18
0
ファイル: EtlPipelineTests.cs プロジェクト: ywscr/bulk-writer
            public ILogger CreateLogger(string categoryName)
            {
                lock (_lock)
                {
                    var logger = new FakeLogger();
                    LoggerInstances.Add(logger);

                    return(logger);
                }
            }
コード例 #19
0
        public void CheckIfStaticDomainTest(string domain, bool isStatic)
        {
            var logger = new FakeLogger();
            var serializer = new FakeDomainSerializer();

            var check = new StaticDomainCheck(logger, serializer);
            bool result = check.IsStaticDomain(domain);

            Assert.Equal(isStatic, result);
        }
コード例 #20
0
        public async Task GetAllResources_WhenAllResourcesRequested_ExpectAllResourcesIncludingHidden(DbContextOptions <ConfigurationDbContext> options)
        {
            var visibleIdentityResource = CreateIdentityTestResource();
            var visibleApiResource      = CreateApiResourceTestResource();
            var visibleApiScope         = CreateApiScopeTestResource();
            var hiddenIdentityResource  = new IdentityResource {
                Name = Guid.NewGuid().ToString(), ShowInDiscoveryDocument = false
            };
            var hiddenApiResource = new ApiResource
            {
                Name   = Guid.NewGuid().ToString(),
                Scopes = { Guid.NewGuid().ToString() },
                ShowInDiscoveryDocument = false
            };
            var hiddenApiScope = new ApiScope
            {
                Name = Guid.NewGuid().ToString(),
                ShowInDiscoveryDocument = false
            };

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                context.IdentityResources.Add(visibleIdentityResource.ToEntity());
                context.ApiResources.Add(visibleApiResource.ToEntity());
                context.ApiScopes.Add(visibleApiScope.ToEntity());

                context.IdentityResources.Add(hiddenIdentityResource.ToEntity());
                context.ApiResources.Add(hiddenApiResource.ToEntity());
                context.ApiScopes.Add(hiddenApiScope.ToEntity());

                context.SaveChanges();
            }

            Resources resources;

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                var store = new ResourceStore(context, FakeLogger <ResourceStore> .Create());
                resources = await store.GetAllResourcesAsync();
            }

            Assert.NotNull(resources);
            Assert.NotEmpty(resources.IdentityResources);
            Assert.NotEmpty(resources.ApiResources);
            Assert.NotEmpty(resources.ApiScopes);

            Assert.Contains(resources.IdentityResources, x => x.Name == visibleIdentityResource.Name);
            Assert.Contains(resources.IdentityResources, x => x.Name == hiddenIdentityResource.Name);

            Assert.Contains(resources.ApiResources, x => x.Name == visibleApiResource.Name);
            Assert.Contains(resources.ApiResources, x => x.Name == hiddenApiResource.Name);

            Assert.Contains(resources.ApiScopes, x => x.Name == visibleApiScope.Name);
            Assert.Contains(resources.ApiScopes, x => x.Name == hiddenApiScope.Name);
        }
コード例 #21
0
        public void ValidatorTest(string tenantName, bool expected)
        {
            var logger     = new FakeLogger();
            var seriazlier = new FakeDomainSerializer();
            var convention = new ByConvention(logger, seriazlier);

            var  validator = new TenantValidator(logger, seriazlier, convention);
            bool result    = validator.IsValid(tenantName);

            Assert.Equal(expected, result);
        }
コード例 #22
0
ファイル: TenantValidatorTests.cs プロジェクト: frapid/frapid
        public void ValidatorTest(string tenantName, bool expected)
        {
            var logger = new FakeLogger();
            var seriazlier = new FakeDomainSerializer();
            var convention = new ByConvention(logger, seriazlier);

            var validator = new TenantValidator(logger, seriazlier, convention);
            bool result = validator.IsValid(tenantName);

            Assert.Equal(expected, result);
        }
コード例 #23
0
        public void IsLoginOK_WhenLoginOK_CallsLogger()
        {
            FakeLogger mockLog = new FakeLogger();

            var loginManager = new LoginManagerWithMock(mockLog);
            loginManager.AddUser("u","p");

            loginManager.IsLoginOK("u", "p");

            StringAssert.Contains("login ok: user: u", mockLog.Text);
        }
コード例 #24
0
        public async Task StoreAsync_WhenPersistedGrantStored_ExpectSuccess()
        {
            var persistedGrant = CreateTestObject();

            var store = new PersistedGrantStore(_context, FakeLogger <PersistedGrantStore> .Create());
            await store.StoreAsync(persistedGrant);

            var foundGrant = (await _context.PersistedGrants.WhereEqualTo("Key", persistedGrant.Key).GetSnapshotAsync())[0].ConvertTo <Entities.PersistedGrant>();

            Assert.NotNull(foundGrant);
        }
コード例 #25
0
        public void Write_To_The_Log()
        {
            var logger = new FakeLogger();

            var controller = new HelloController(logger);

            controller.Execute(new FakeRequestContext());

            Assert.IsNotNull(logger.LogResult);
            Assert.IsTrue(logger.LogResult.Length > 0);
        }
コード例 #26
0
        public async Task FindByDeviceCodeAsync_WhenDeviceCodeExists_ExpectDataRetrievedCorrectly()
        {
            using var ravenStore = GetDocumentStore();
            await new DeviceFlowCodeIndex().ExecuteAsync(ravenStore);

            var testDeviceCode = $"device_{Guid.NewGuid().ToString()}";
            var testUserCode   = $"user_{Guid.NewGuid().ToString()}";

            var expectedSubject        = $"sub_{Guid.NewGuid().ToString()}";
            var expectedDeviceCodeData = new DeviceCode
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 10, 19, 16, 14, 29),
                Lifetime        = 300,
                IsOpenId        = true,
                Subject         = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>
                {
                    new Claim(JwtClaimTypes.Subject, expectedSubject)
                }))
            };

            using (var session = ravenStore.OpenSession())
            {
                session.Store(new DeviceFlowCode
                {
                    DeviceCode   = testDeviceCode,
                    UserCode     = testUserCode,
                    ClientId     = expectedDeviceCodeData.ClientId,
                    SubjectId    = expectedDeviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                    CreationTime = expectedDeviceCodeData.CreationTime,
                    Expiration   = expectedDeviceCodeData.CreationTime.AddSeconds(expectedDeviceCodeData.Lifetime),
                    Data         = serializer.Serialize(expectedDeviceCodeData)
                });
                session.SaveChanges();
            }

            WaitForIndexing(ravenStore);

            DeviceCode code;

            using (var session = ravenStore.OpenAsyncSession())
            {
                var store = new DeviceFlowStore(session, new PersistentGrantSerializer(),
                                                FakeLogger <DeviceFlowStore> .Create());
                code = await store.FindByDeviceCodeAsync(testDeviceCode);
            }

            code.Should().BeEquivalentTo(expectedDeviceCodeData,
                                         assertionOptions => assertionOptions.Excluding(x => x.Subject));

            code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject)
            .Should().NotBeNull();
        }
コード例 #27
0
        public async Task StoreAsync_WhenPersistedGrantStored_ExpectSuccess()
        {
            var persistedGrant = CreateTestObject();

            var store = new PersistedGrantStore(g.operationalDb, FakeLogger <PersistedGrantStore> .Create());
            await store.StoreAsync(persistedGrant);

            var foundGrant = g.operationalDb.Select <Storage.Entities.PersistedGrant>().Where(x => x.Key == persistedGrant.Key).First();

            Assert.NotNull(foundGrant);
        }
コード例 #28
0
        public void Logger_SetLoggerWhenSourceRepositoryIsAggregateRepository_LoggerOnAggregateRepositoryIsSet()
        {
            var aggregateRepository = new AggregateRepository(new FakePackageRepository [0]);

            CreateProject(aggregateRepository);
            var expectedLogger = new FakeLogger();

            project.Logger = expectedLogger;

            Assert.AreEqual(expectedLogger, aggregateRepository.Logger);
        }
コード例 #29
0
 public LikesController(
     IMapper mapper,
     ILikeRepository likeRepository,
     FakeLogger logger,
     IAccountRepository accountRepository)
 {
     _mapper            = mapper;
     _likeRepository    = likeRepository;
     _logger            = logger;
     _accountRepository = accountRepository;
 }
        public async Task FindClientByIdAsync_WhenClientDoesNotExist_ExpectNull()
        {
            var storeHolder = GetConfigurationDocumentStoreHolder();

            WaitForIndexing(storeHolder.IntegrationTest_GetDocumentStore());

            var store  = new ClientStore(storeHolder, FakeLogger <ClientStore> .Create());
            var client = await store.FindClientByIdAsync(Guid.NewGuid().ToString());

            client.Should().BeNull();
        }
コード例 #31
0
        public void UsingConditionalDirectives()
        {
            var logger = new FakeLogger();

#if LOG
            logger.WriteLogMessage("Message 1");
#endif

#if LOG
            logger.WriteLogMessage("Message 2");
#endif
        }
コード例 #32
0
        public ActionResult TestSettings(TestSmsSettings testSettings)
        {
            ILogger logger = null;

            try {
                var fakeLogger          = new FakeLogger();
                var smsChannelComponent = _smsChannel as Component;
                if (smsChannelComponent != null)
                {
                    logger = smsChannelComponent.Logger;
                    smsChannelComponent.Logger = fakeLogger;
                }

                // Temporarily update settings so that the test will actually use the specified host, port, etc.
                var smsSettings = _orchardServices.WorkContext.CurrentSite.As <SmsSettingsPart>();

                smsSettings.AccountSid   = testSettings.AccountSid;
                smsSettings.AuthToken    = testSettings.AuthToken;
                smsSettings.TwilioNumber = testSettings.From;

                if (!smsSettings.IsValid())
                {
                    fakeLogger.Error("Invalid settings.");
                }
                else
                {
                    _smsChannel.Process(new Dictionary <string, object> {
                        { "Recipients", testSettings.To },
                        { "Body", testSettings.Body }
                    });
                }

                if (!String.IsNullOrEmpty(fakeLogger.Message))
                {
                    return(Json(new { error = fakeLogger.Message }));
                }

                return(Json(new { status = T("Message sent.").Text }));
            }
            catch (Exception e) {
                return(Json(new { error = e.Message }));
            }
            finally {
                var smsChannelComponent = _smsChannel as Component;
                if (smsChannelComponent != null)
                {
                    smsChannelComponent.Logger = logger;
                }

                // Undo the temporarily changed smtp settings.
                _orchardServices.TransactionManager.Cancel();
            }
        }
コード例 #33
0
        public void SetUp()
        {
            var gitExe = new Mock <IExternalProcess>();

            _parser = new FakeParser();
            _logger = new FakeLogger();

            _fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>());
            _directory  = new MockDirectoryInfo(_fileSystem, @"C:\databasename");

            _service = new GitScriptRepository(_directory, "servername", databaseName, gitExe.Object, _fileSystem, _parser, _logger, true);
        }
コード例 #34
0
        public void IsLoginOK_WhenLoginOK_CallsLogger()
        {
            FakeLogger mockLog = new FakeLogger();

            var loginManager = new LoginManagerWithMock(mockLog);

            loginManager.AddUser("u", "p");

            loginManager.IsLoginOK("u", "p");

            StringAssert.Contains("login ok: user: u", mockLog.Text);
        }
コード例 #35
0
        public void LogsErrorWhenInputIsZeroTake3()
        {
            var fakeLogger  = new FakeLogger();
            var someService = new SomeService(fakeLogger);

            someService.DoSomething(0);

            // Option 3: Create your own instance of ILogger<T> that has a non-extension version of the method
            // Doesn't work, unless you change system under test to take in a FakeLogger (which is useless)
            Assert.NotNull(FakeLogger.ProvidedException);
            Assert.NotNull(FakeLogger.ProvidedMessage);
        }
コード例 #36
0
        public void Log_ExceptionIsNotValidationException_LogsError()
        {
            // arrange
            var logger    = new FakeLogger();
            var exception = new InvalidOperationException("Something is not right");

            // act
            exception.Log(logger);

            // assert
            Assert.Equal(2, logger.LogCallCount);
        }
コード例 #37
0
        public void Log_ExceptionIsValidationException_DoesNotLogError()
        {
            // arrange
            var logger    = new FakeLogger();
            var exception = new ValidationException("Something is not right");

            // act
            exception.Log(logger);

            // assert
            Assert.Equal(0, logger.LogCallCount);
        }
コード例 #38
0
        public virtual void CallingLogExceptionWithUnhandledException_DoesNotLog()
        {
            //Arrange
            var logger = new FakeLogger <ActionStoppingException>();
            var sut    = new ActionStoppingExceptionHandler(logger);

            //Act
            Assert.Catch(() => sut.LogException(new NullReferenceException()));

            //Assert
            logger.LoggedEvents.Count.Should().Be(0);
        }
コード例 #39
0
        public virtual void CallingLogExceptionLogsForHandledException()
        {
            //Arrange
            var logger = new FakeLogger <TException>();
            var sut    = (THandler)Activator.CreateInstance(typeof(THandler), logger);

            //Act
            sut.LogException(_exceptionCreator());

            //Assert
            logger.LoggedEvents.Count.Should().Be(1);
        }
コード例 #40
0
        public virtual void CallingLogExceptionWithUnhandledException_Throws()
        {
            //Arrange
            var logger = new FakeLogger <TException>();
            var sut    = (THandler)Activator.CreateInstance(typeof(THandler), logger);

            //Act
            var exception = Assert.Catch(() => sut.LogException(new NullReferenceException()));

            //Assert
            exception.Should().BeOfType <ArgumentException>();
        }
コード例 #41
0
        public void Test(string currentDomain, string expectedToken)
        {
            var logger = new FakeLogger();
            var serializer = new FakeDomainSerializer();
            var check = new StaticDomainCheck(logger, serializer);
            var tokenizer = new FakeTokenizer();

            var generator = new AntiforgeryTokenGenerator(check, tokenizer, currentDomain);
            var result = generator.GetAntiForgeryToken();
            var expected = new MvcHtmlString(expectedToken);

            Assert.Equal(expected.ToString(), result.ToString());
        }
コード例 #42
0
ファイル: DomainFinderTests.cs プロジェクト: frapid/frapid
        public void ShouldFindDomainByTenantName(string defaultSite, string synonym, string expectedDomain)
        {
            var logger = new FakeLogger();
            var serializer = new FakeDomainSerializer();
            var convention = new ByConvention(logger, serializer);

            var finder = new DomainFinder(serializer, convention);

            var found = finder.FindBySynonym(synonym, defaultSite);
            string result = found.DomainName;

            Assert.Equal(expectedDomain, result);
        }
コード例 #43
0
ファイル: TenantLocatorTests.cs プロジェクト: frapid/frapid
        public void TestConvention(string url, string expected)
        {
            string defaultTenant = "localhost";
            var logger = new FakeLogger();
            var serializer = new FakeDomainSerializer();
            var extractor = new DomainNameExtractor(logger);
            var convention = new ByConvention(logger, serializer);
            var validator = new TenantValidator(logger, serializer, convention);

            var locator = new TenantLocator(logger, extractor, convention, validator, serializer);

            string result = locator.FromUrl(url, defaultTenant);

            Assert.Equal(expected, result);
        }
コード例 #44
0
        public ActionResult TestSettings(TestSmsSettings testSettings)
        {
            ILogger logger = null;
            try {
                var fakeLogger = new FakeLogger();
                var smsChannelComponent = _smsChannel as Component;
                if (smsChannelComponent != null) {
                    logger = smsChannelComponent.Logger;
                    smsChannelComponent.Logger = fakeLogger;
                }

                // Temporarily update settings so that the test will actually use the specified host, port, etc.
                var smsSettings = _orchardServices.WorkContext.CurrentSite.As<SmsSettingsPart>();

                smsSettings.AccountSid = testSettings.AccountSid;
                smsSettings.AuthToken = testSettings.AuthToken;
                smsSettings.TwilioNumber = testSettings.From;

                if (!smsSettings.IsValid()) {
                    fakeLogger.Error("Invalid settings.");
                }
                else {
                    _smsChannel.Process(new Dictionary<string, object> {
                        {"Recipients", testSettings.To},
                        {"Body", testSettings.Body}
                    });
                }

                if (!String.IsNullOrEmpty(fakeLogger.Message)) {
                    return Json(new { error = fakeLogger.Message });
                }

                return Json(new {status = T("Message sent.").Text});
            }
            catch (Exception e) {
                return Json(new {error = e.Message});
            }
            finally {
                var smsChannelComponent = _smsChannel as Component;
                if (smsChannelComponent != null) {
                    smsChannelComponent.Logger = logger;
                }

                // Undo the temporarily changed smtp settings.
                _orchardServices.TransactionManager.Cancel();
            }
        }
コード例 #45
0
        public void TestGenerateMethod(string url, string expected)
        {
            var logger = new FakeLogger();
            var extractor = new DomainNameExtractor(logger);
            var serializer = new FakeDomainSerializer();
            var byConvention = new ByConvention(logger, serializer);
            var validator = new TenantValidator(logger, serializer, byConvention);
            const string defaultTenant = "localhost";


            var locator = new TenantLocator(logger, extractor, byConvention, validator, serializer);
            var uri = new Uri(url);
            var keyGen = new CacheKeyGenerator(uri, locator, defaultTenant);

            string result = keyGen.Generate();

            Assert.Equal(expected, result);
        }
コード例 #46
0
        public void InterceptWithFuncAndPredicate_TwoInterceptors_InterceptsTheInstanceWithBothInterceptors()
        {
            // Arrange
            var logger = new FakeLogger();

            Func<IInterceptor> interceptorCreator1 = () => new InterceptorThatLogsBeforeAndAfter(logger)
            {
                BeforeText = "Start1 ",
                AfterText = " Done1"
            };

            Func<IInterceptor> interceptorCreator2 = () => new InterceptorThatLogsBeforeAndAfter(logger)
            {
                BeforeText = "Start2 ",
                AfterText = " Done2"
            };

            var container = new Container();

            container.RegisterSingleton<ILogger>(logger);
            container.Register<ICommand, CommandThatLogsOnExecute>();

            container.InterceptWith(interceptorCreator1, IsACommandPredicate);
            container.InterceptWith(interceptorCreator2, IsACommandPredicate);

            container.RegisterInitializer<CommandThatLogsOnExecute>(c => c.ExecuteLogMessage = "Executing");

            // Act
            var command = container.GetInstance<ICommand>();

            command.Execute();

            // Assert
            Assert.AreEqual("Start2 Start1 Executing Done1 Done2", logger.Message);
        }
コード例 #47
0
        public void InterceptWithInstanceAndPredicate_InterceptingInterfacesEndingWithCommand_InterceptsTheInstance()
        {
            // Arrange
            var logger = new FakeLogger();

            var singletonInterceptor = new InterceptorThatLogsBeforeAndAfter(logger)
            {
                BeforeText = "Start ",
                AfterText = " Done"
            };

            var container = ContainerFactory.New();

            container.RegisterSingleton<ILogger>(logger);
            container.Register<ICommand, CommandThatLogsOnExecute>();
            
            container.InterceptWith(singletonInterceptor, IsACommandPredicate);

            container.RegisterInitializer<CommandThatLogsOnExecute>(c => c.ExecuteLogMessage = "Executing");

            // Act
            var command = container.GetInstance<ICommand>();

            command.Execute();

            // Assert
            Assert.AreEqual("Start Executing Done", logger.Message);
        }
コード例 #48
0
        public void InterceptWithGenericArgAndPredicate_RequestingAConcreteType_WillNotBeIntercepted()
        {
            // Arrange
            var logger = new FakeLogger();

            var container = ContainerFactory.New();

            container.RegisterSingleton<ILogger>(logger);

            container.InterceptWith<InterceptorThatLogsBeforeAndAfter>(type => type == typeof(ICommand));

            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.BeforeText = "Start ");
            container.RegisterInitializer<CommandThatLogsOnExecute>(c => c.ExecuteLogMessage = "Executing");
            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.AfterText = " Done");

            // Act
            var command = container.GetInstance<CommandThatLogsOnExecute>();

            command.Execute();

            // Assert
            Assert.AreEqual("Executing", logger.Message);
            Assert.IsTrue(command.GetType() == typeof(CommandThatLogsOnExecute));
        }
コード例 #49
0
 public LoggerExecutionWrapperTests()
 {
     _fakeLogger = new FakeLogger();
     _sut = new LoggerExecutionWrapper(_fakeLogger.Log);
 }
コード例 #50
0
 public virtual void SetUp()
 {
     _logger = new FakeLogger();
 }
コード例 #51
0
        public void Intercept_DecoratedGenericRegistrations_WorksLikeACharm()
        {
            // Arrange
            var logger = new FakeLogger();

            var container = new Container();

            container.RegisterSingleton<ILogger>(logger);
            container.Register<ICommand, CommandThatLogsOnExecute>();

            container.Register(typeof(IValidator<>), typeof(LoggingValidator<>));

            container.RegisterDecorator(typeof(IValidator<>), typeof(LoggingValidatorDecorator<>));

            container.InterceptWith<InterceptorThatLogsBeforeAndAfter>(
                t => t.IsInterface && t.Name.StartsWith("IValidator"));

            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.BeforeText = "Inercepting ");
            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.AfterText = "Intercepted ");

            // Act
            container.GetInstance<IValidator<RealCommand>>().Validate(new RealCommand());

            // Assert
            Assert.AreEqual("Inercepting Decorating Validating Decorated Intercepted ", logger.Message);
        }