Ejemplo n.º 1
0
        public async Task ConnectAsyncShouldSuccessfullyConnectToTwitch()
        {
            // Arrange
            var client = new TwitchClient(_output.BuildLoggerFor <TwitchClient>());

            TwitchMessage.Welcome welcome = null;

            var cts = new CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromMinutes(1));
            async Task ReadLoop()
            {
                while (client.IsConnected && welcome is null)
                {
                    welcome = await client.ReadMessageAsync <TwitchMessage.Welcome>(token : cts.Token);
                }
            }

            // Act
            await client.ConnectAsync("justinfan0227", "");

            await ReadLoop();

            // Assert
            Assert.NotNull(welcome);
        }
 public TestBase(ITestOutputHelper testOutputHelper)
 {
     Logger     = testOutputHelper.BuildLoggerFor <TestBase>();
     TestConfig = TestConfig.Load();
     TestConfig.Options.Logger      = testOutputHelper.BuildLoggerFor <MicrosoftDynamicsClient>();
     TestConfig.Options.LogMetadata = false;
 }
Ejemplo n.º 3
0
        public CacheTests(ITestOutputHelper output)
        {
            var env = new HostingEnvironment {
                EnvironmentName = Environments.Development
            };
            var opts = Options.Create(new MemoryDistributedCacheOptions());

            underlyingDistributedCache = new MemoryDistributedCache(opts);
            cacheSyncManager           = new CacheSyncManager(output.BuildLoggerFor <CacheSyncManager>());
            cache = new Cache(underlyingDistributedCache, cacheSyncManager, env, output.BuildLoggerFor <Cache>());
        }
Ejemplo n.º 4
0
        public void ThrowsExceptionWhenCreatedWithNullManagerTest()
        {
            var logger = _output.BuildLoggerFor <ClaimsTransformer>();

            Action action = () => new ClaimsTransformer(null, logger);

            action.Should().Throw <ArgumentNullException>();
        }
        public BlogTest(ITestOutputHelper outputHelper)
        {
            //for consistency:
            //gcloud beta emulators firestore start --host-port=localhost:8888 --
            Environment.SetEnvironmentVariable("FIRESTORE_EMULATOR_HOST", "localhost:8888");
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "/raid/repos/epsweb-firestore/EPSWeb.Common.Firestore/epsweb-217515-5631b4260996.json");
            //Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS","/your/credential/key.json");
            output = outputHelper;
            log    = output.BuildLoggerFor <BlogRepo>();

            blog = new BlogRepo(new FirestoreConfig
            {
                Root         = "blogtest",
                Emulator     = true,
                EmulatorUrl  = "http://localhost:8888",
                EmulatorPort = 8888,
                ProjectId    = "epsweb-217515"
            }, log);

            posts = new List <BlogPost>();

            for (int i = 0; i < 20; i++)
            {
                posts.Add(new BlogPost
                {
                    body     = Lorem.Paragraphs(500, 250, 3).ToCombinedString(),
                    overview = Lorem.Sentence(10),
                    tags     = Lorem.Words(5).Split(',').ToCombinedString(),
                    title    = $"blog post {i}",
                    slug     = $"blog-post-{i}"
                });
            }
        }
Ejemplo n.º 6
0
        [InlineData("WebDriver", "src/version.json", "0.149.20")]              // internal repository
        public void GetVersionTest(string repositoryName, string versionPath, string expectedVersion)
        {
            string path =
                Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
                    @"Source\Repos",
                    repositoryName);


            const int count = 100;

            ILogger <VersionResolver> logger = count == 1 ? output.BuildLoggerFor <VersionResolver>() : NullLogger <VersionResolver> .Instance;

            for (int i = 0; i < count; i++)
            {
                GitRepository   repository = new GitRepository(path);
                VersionResolver resolver   = new WalkingVersionResolver(repository, versionPath, logger);

                var version = resolver.GetVersion();
                Assert.Equal(expectedVersion, version);

                if (count == 1)
                {
                    var stats = repository.GetCacheStatistics();
                }
            }
        }
Ejemplo n.º 7
0
        public void BuildLoggerForTLogsAccordingToLogLevel(LogLevel configuredLevel, LogLevel logLevel, bool isEnabled)
        {
            var logger = _output.BuildLoggerFor <TestOutputHelperExtensionsTests>(configuredLevel);

            logger.Should().BeAssignableTo <ILogger <TestOutputHelperExtensionsTests> >();

            logger.Log(logLevel, "Hey, does this work? Check the test trace log.");

            if (isEnabled)
            {
                logger.Entries.Should().HaveCount(1);
            }
            else
            {
                logger.Entries.Should().BeEmpty();
            }
        }
Ejemplo n.º 8
0
 public TranscoderTests(ITestOutputHelper output)
 {
     _files      = new Mock <IFileSystem>();
     _transcoder = new KTranscoder(
         _files.Object,
         Options.Create(new BasicOptions()),
         output.BuildLoggerFor <KTranscoder>()
         );
 }
Ejemplo n.º 9
0
 public PluginLoaderTests(ITestOutputHelper output)
 {
     _logger        = output.BuildLoggerFor <IPluginLoader>();
     _path          = FindPluginsDir();
     _pluginOptions = new PluginOptions
     {
         Directories = new DirectoryInfo[] { _path }
     };
 }
 public HibpClientTests(ITestOutputHelper outputHelper)
 {
     _outputHelper = outputHelper;
     subOptions    = Options.Create(new HibpConfiguration()
     {
         ApiKey = "#{APIKEY}#"
     });
     subHttpClientFactory = Substitute.For <IHttpClientFactory>();
     subLogger            = outputHelper.BuildLoggerFor <HibpClient>();
 }
Ejemplo n.º 11
0
 public bool InjectLogger <T>()
 {
     if (_logger != null)
     {
         var l = (ILogger <T>)_logger.BuildLoggerFor <T>();
         this.Register(() => l);
         return(true);
     }
     return(false);
 }
        public ThumbnailsGeneratingTests(ITestOutputHelper output)
        {
            IImageResizing imageResizing = new ImageResizing();

            _blobStorage     = new MockImageBlobStorage();
            _metadataStorage = new MockImageMetadataStorage();

            IImageIdentifierProvider imageIdentifierProvider = new ImageIdentifierProvider();

            _thumbnailsService = new ImageThumbnailService(output.BuildLoggerFor <ImageThumbnailService>(), imageResizing, _blobStorage, _metadataStorage, imageIdentifierProvider, this);
        }
Ejemplo n.º 13
0
 public RenameCommand_PathToSeriesFile(ITestOutputHelper output)
 {
     // arrange
     _output  = output;
     _logger  = _output.BuildLoggerFor <Console.Commands.Rename.Command>();
     _options = new Console.Commands.Rename.Options
     {
         Path = "~/downloads/My.Show.S01.E01.Episode.Title.1080p.BDRIP.SCENE-REPACK",
     };
     _renamer = A.Fake <IRenameFoldersAndFiles>();
     _command = new Console.Commands.Rename.Command(_logger, _renamer);
 }
Ejemplo n.º 14
0
        private ISpellCheckerService CreateSpellCheckerService(out Mock <IDataSource> mockDataSource)
        {
            mockDataSource = CreateMockDataSource();

            // logging
            ILogger <SpellCheckerService> logger = _output.BuildLoggerFor <SpellCheckerService>();

            ISpellCheckerService service = new SpellCheckerService(
                mockDataSource.Object,
                logger);

            return(service);
        }
Ejemplo n.º 15
0
        public PackageManagerTests(ITestOutputHelper output)
        {
            _logger = output.BuildLoggerFor <IPackageManager>();

            _cacheDir = new DirectoryInfo(".packs");
            if (_cacheDir.Exists)
            {
                _cacheDir.Delete(true);
                _cacheDir.Create();
            }

            _webClient = new HttpClient();
        }
        public async Task InvokeDoesNotRunExecutorWhenDelegateIsSuccessfulTest()
        {
            RequestDelegate next     = delegate { return(Task.CompletedTask); };
            var             logger   = _output.BuildLoggerFor <OversizeDataExceptionMiddleware>();
            var             executor = Substitute.For <IResultExecutor>();
            var             context  = Substitute.For <HttpContext>();
            var             config   = Model.Create <PhotoConfig>();

            var sut = new OversizeDataExceptionMiddleware(next, logger, executor, config);

            await sut.Invoke(context).ConfigureAwait(false);

            await executor.DidNotReceive().Execute(Arg.Any <HttpContext>(), Arg.Any <ObjectResult>())
            .ConfigureAwait(false);
        }
Ejemplo n.º 17
0
        public IntegrationTests(ITestOutputHelper output)
        {
            _output = output;
            var logger = output.BuildLoggerFor <Client>();

            var obj       = JObject.Parse(File.ReadAllText("..\\..\\..\\device.json"));
            var ipAddress = obj["IpAddress"].Value <string>();

            _client = new Client(new KeyStore(new FileService()), logger)
            {
                CommandTimeout = 60000
            };
            _client.ConnectAsync(ipAddress).Wait();
        }
        internal GraphClusterIntegrationTest(
            GraphClusterCollectionFixture graphClusterCollectionFixture,
            ITestOutputHelper testOutputHelper)
        {
            TestOutputHelper = testOutputHelper;

            Endpoints = graphClusterCollectionFixture.Neo4jOptions.Endpoints
                        .Where(epc => epc.Enabled)
                        .Select(epc => CreateFakeNeoEndpoint(epc.Name !));

            GraphReplicaSetLowLevelLogger = testOutputHelper.BuildLoggerFor <GraphReplicaSetLowLevel>();
            GraphLogger = testOutputHelper.BuildLoggerFor <Graph>();

            var graphReplicaSets = graphClusterCollectionFixture.Neo4jOptions.ReplicaSets
                                   .Select(rsc => new GraphReplicaSetLowLevel(
                                               rsc.ReplicaSetName !,
                                               ConstructGraphs(rsc, Endpoints, GraphLogger),
                                               GraphReplicaSetLowLevelLogger));

            GraphClusterLowLevelLogger = testOutputHelper.BuildLoggerFor <GraphClusterBuilder>();

            GraphClusterLowLevel = new GraphClusterLowLevel(graphReplicaSets, GraphClusterLowLevelLogger);
        }
Ejemplo n.º 19
0
        public Renamer_PathToSeriesFile(ITestOutputHelper output)
        {
            _output     = output;
            _logger     = _output.BuildLoggerFor <Renamer.Renamer>();
            _folders    = A.Fake <IRenameFolders>();
            _files      = A.Fake <IRenameFiles>();
            _filesystem = new System.IO.Abstractions.TestingHelpers.MockFileSystem(new Dictionary <string, MockFileData>
            {
                { "/home/ken/downloads/My.Show.S01.E01.Episode.Title.1080p.BDRIP.SCENE-REPACK", new MockFileData("1234567890") },
            }, "");

            _renamer = new Renamer.Renamer(_logger, _folders, _files, _filesystem);
            Path     = "/home/ken/downloads/My.Show.S01.E01.Episode.Title.1080p.BDRIP.SCENE-REPACK";
        }
Ejemplo n.º 20
0
        public async Task TestDiffAndMarkdown()
        {
            var changedOpenAPI = TestUtils.GetOpenAPICompare().FromLocations(OpenAPIDoc1, OpenAPIDoc2);
            var logger         = _testOutputHelper.BuildLoggerFor <MarkdownRender>();
            var render         = await new MarkdownRender(logger).Render(changedOpenAPI);

            try
            {
                await File.WriteAllTextAsync("testDiff.md", render);
            }
            catch (Exception e)
            {
                _testOutputHelper.WriteLine(e.ToString());
            }
        }
Ejemplo n.º 21
0
        public WriterAppTests(ITestOutputHelper outputHelper)
        {
            var logger = outputHelper.BuildLoggerFor <EasyRates.WriterApp.WriterApp>();

            clock.Setup(x => x.UtcNow).Returns(currentTime);

            cases = new[]
            {
                new RatesUpdaterMock.InvokeCase(),
                new RatesUpdaterMock.InvokeCase(),
                new RatesUpdaterMock.InvokeCase(),
                new RatesUpdaterMock.InvokeCase()
            };
            updater = new RatesUpdaterMock(cases);
            app     = new EasyRates.WriterApp.WriterApp(updater, timetable.Object, new SystemClock(), logger);
        }
Ejemplo n.º 22
0
        public DispatcherServiceTests(ITestOutputHelper output)
        {
            MessageHandlerRegistryOptions messageHandlerRegistryOptions = new MessageHandlerRegistryOptions();

            messageHandlerRegistryOptions.Add(typeof(TestHandler));
            MessageHandlerRegistry registry = new MessageHandlerRegistry(output.BuildLoggerFor <MessageHandlerRegistry>(), Options.Create(messageHandlerRegistryOptions));
            ServiceCollection      services = new ServiceCollection();

            services.AddSingleton(registry);
            services.AddTransient <TestHandler>();
            services.AddLogging(builder =>
            {
                builder.AddXunit(output);
            });
            httpContextFactory = () => new DefaultHttpContext
            {
                RequestServices = services.BuildServiceProvider().CreateScope().ServiceProvider
            };
        }
 public WelcomeServiceTests(ITestOutputHelper outputHelper)
 {
     _logger = outputHelper.BuildLoggerFor <WelcomeService>();
     _botMock.Setup(b => b.SendTextMessageAsync(
                        It.IsAny <ChatId>(),
                        It.IsAny <string>(),
                        It.IsAny <ParseMode>(),
                        It.IsAny <bool>(),
                        It.IsAny <bool>(),
                        It.IsAny <int>(),
                        It.IsAny <IReplyMarkup>(),
                        It.IsAny <CancellationToken>()
                        )).ReturnsAsync(new Message());
     _botMock.Setup(b => b.GetChatMemberAsync(
                        It.IsAny <ChatId>(),
                        It.IsAny <int>(),
                        It.IsAny <CancellationToken>()
                        )).ReturnsAsync(new ChatMember());
 }
Ejemplo n.º 24
0
        protected TestWithOutput(ITestOutputHelper iTestOutputHelper)
        {
            ITestOutputHelper = iTestOutputHelper;
            Logger            = iTestOutputHelper.BuildLogger();
            var nowUtc = DateTimeOffset.UtcNow;

            StartEpoch = nowUtc.AddDays(-30).ToUnixTimeSeconds();
            EndEpoch   = nowUtc.ToUnixTimeSeconds();
            var configuration       = LoadConfiguration("appsettings.json");
            var autoTaskCredentials = configuration.AutoTaskCredentials;

            Client = new Client(
                autoTaskCredentials.Username,
                autoTaskCredentials.Password,
                iTestOutputHelper.BuildLoggerFor <Client>());
            AutoTaskClient = new AutoTaskClient(new AutoTaskConfiguration {
                Username = autoTaskCredentials.Username, Password = autoTaskCredentials.Password
            });
            Stopwatch = Stopwatch.StartNew();
        }
Ejemplo n.º 25
0
        public CharacterBuildServiceTests(ITestOutputHelper output)
        {
            // Configure and load our user secrets
            var builder = new ConfigurationBuilder()
                          .AddUserSecrets <CharacterBuildServiceTests>();

            Configuration = builder.Build();

            // Create a temporary database to test against
            dbOptions = new DbContextOptionsBuilder <ApplicationDbContext>()
                        .UseCosmos(
                accountEndpoint: Configuration["Cosmos:Uri"],
                accountKey: Configuration["Cosmos:Key"],
                databaseName: $"Test-{Guid.NewGuid()}"
                )
                        .Options;

            using (var context = new ApplicationDbContext(dbOptions))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            // Set up AutoMapper like our Startup does
            var mappingConfig = new MapperConfiguration(mc => mc.AddProfile(new MappingProfile()));

            mapper = mappingConfig.CreateMapper();

            // Set up our valid users.  User 1 is admin.
            User1 = CreateTestUser(validUserId1, ValidUserName1, ValidUserHandle1, true);
            User2 = CreateTestUser(validUserId2, ValidUserName2, ValidUserHandle2, false);

            // This build driver creates build abstractions that accept any choice and
            // summarise by concatenating the choices.
            buildDriver = new TestBuildDriver(output);

            // This logger should log to the test output:
            logger = output.BuildLoggerFor <CharacterBuildService>();
        }
Ejemplo n.º 26
0
        public RedisCacheConnectionPoolManagerTests(ITestOutputHelper output)
        {
            // See more info here: https://gist.github.com/JonCole/e65411214030f0d823cb#file-threadpool-md
            // Everything started from here https://gist.github.com/JonCole/925630df72be1351b21440625ff2671f#file-redis-bestpractices-stackexchange-redis-md
            ThreadPool.GetMaxThreads(out var maxThread, out var maxIOThread);
            ThreadPool.SetMinThreads(maxThread / 2, maxIOThread);

            this.output = output;

            var configuration = new RedisConfiguration()
            {
                AbortOnConnectFail = true,
                KeyPrefix          = "MyPrefix__",
                Hosts = new RedisHost[]
                {
                    new RedisHost {
                        Host = "localhost", Port = 6379
                    }
                },
                AllowAdmin                = true,
                ConnectTimeout            = 3000,
                Database                  = 0,
                PoolSize                  = 5,
                ServerEnumerationStrategy = new ServerEnumerationStrategy()
                {
                    Mode       = ServerEnumerationStrategy.ModeOptions.All,
                    TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
                    UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.Throw
                }
            };

            var logger = output.BuildLoggerFor <RedisCacheConnectionPoolManager>();

            sut         = new RedisCacheConnectionPoolManager(configuration, logger);
            this.output = output;
        }
Ejemplo n.º 27
0
 public PingTests(ITestOutputHelper output)
 {
     _output = output;
     _logger = output.BuildLoggerFor <PingTests>();
 }
Ejemplo n.º 28
0
 public ExportTests(ITestOutputHelper output)
 {
     _output = output;
     _logger = output.BuildLoggerFor <ExportTests>();
 }
Ejemplo n.º 29
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="LoggingTestsBase{T}" /> class.
 /// </summary>
 /// <param name="output">The xUnit test output.</param>
 /// <param name="config">Optional logging configuration.</param>
 protected LoggingTestsBase(ITestOutputHelper output, LoggingConfig?config = null)
 {
     Output = output ?? throw new ArgumentNullException(nameof(output));
     Logger = output.BuildLoggerFor <T>(config);
 }
Ejemplo n.º 30
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="LoggingTestsBase{T}" /> class.
 /// </summary>
 /// <param name="output">The xUnit test output.</param>
 /// <param name="logLevel">The minimum log level to output.</param>
 protected LoggingTestsBase(ITestOutputHelper output, LogLevel logLevel)
 {
     Output = output ?? throw new ArgumentNullException(nameof(output));
     Logger = output.BuildLoggerFor <T>(logLevel);
 }