public void get_resources()
        {
            const string url         = "http://localhost:5001";
            const string stepName    = "init";
            const int    duration    = 3;
            const int    expectedRps = 100;
            var          endpoint    = $"{url}/resources";

            var step = HttpStep.Create(stepName, ctx =>
                                       Task.FromResult(Http.CreateRequest("GET", endpoint)
                                                       .WithCheck(response => Task.FromResult(response.IsSuccessStatusCode))));

            var assertions = new[]
            {
                Assertion.ForStep(stepName, s => s.RPS >= expectedRps),
                Assertion.ForStep(stepName, s => s.OkCount >= expectedRps * duration)
            };

            var scenario = ScenarioBuilder.CreateScenario("GET resources", step)
                           .WithConcurrentCopies(1)
                           .WithOutWarmUp()
                           .WithDuration(TimeSpan.FromSeconds(duration))
                           .WithAssertions(assertions);

            NBomberRunner.RegisterScenarios(scenario)
            .RunTest();
        }
        public async Task Test()
        {
            if (RpsTest == 0)
            {
                return;
            }

            var step = Step.Create(GetTestName(),
                                   HttpClientFactory.Create(),
                                   context =>
            {
                var request = Http.CreateRequest("GET", Url)
                              .WithHeader("accept", "text/html");

                return(Http.Send(request, context));
            }, timeout: TimeSpan.FromSeconds(Timeout));

            var scenario = ScenarioBuilder
                           .CreateScenario(GetTestName(), step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(TimeWarmUp))
                           .WithLoadSimulations(
                Simulation.RampPerSec(RpsWarmUp, TimeSpan.FromSeconds(TimeWarmUp)),
                Simulation.RampPerSec(RpsTest, TimeSpan.FromSeconds(TimeRamp)),
                Simulation.InjectPerSec(RpsTest, TimeSpan.FromSeconds(TimeTest))
                // Simulation.InjectPerSecRandom(RpsMin, RpsMax, TimeSpan.FromSeconds(Time))
                );

            var result = await RunScenario(scenario);

            VerifyResults(result);
        }
Exemple #3
0
        public static Scenario BuildUserCreationScenario(Configuration conf)
        {
            var positions = new PositionsApi(conf).Get().Records;

            var getFilteredUsersStep = Step.CreateAction("Create user", ConnectionPool.None, async x =>
            {
                var position      = new Random().Next(1, positions.Count - 1);
                var positionToPut = positions.ElementAt(position);

                var age = new Random().Next(20, 60);
                var exp = new Random().Next(1, 20);

                var response = await new UsersApi(conf).PutUserAsyncWithHttpInfo(new CreationUserModel
                {
                    DisplayName         = Guid.NewGuid().ToString(),
                    BirthDate           = DateTime.Now.AddYears(-age).ToString("yyyy-MM-dd"),
                    WorkPeriodStartDate = DateTime.Now.AddYears(-exp).ToString("yyyy-MM-dd"),
                    PositionId          = positionToPut.Id.ToString()
                });

                return(response.Data.IsSuccess == true ? Response.Ok() : Response.Fail());
            });

            return(ScenarioBuilder.CreateScenario("Create User Scenario", getFilteredUsersStep));
        }
Exemple #4
0
        public static void Run()
        {
            var step1 = Step.Create("step_1", async context =>
            {
                // you can do any logic here: go to http, websocket etc

                await Task.Delay(TimeSpan.FromMilliseconds(200));
                return(Response.Ok(42)); // this value will be passed as response for the next step
            });

            var step2 = Step.Create("step_2", async context =>
            {
                // you can do any logic here: go to http, websocket etc

                await Task.Delay(TimeSpan.FromMilliseconds(200));
                var value = context.GetPreviousStepResponse <int>(); // 42
                return(Response.Ok());
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("hello_world_scenario", new[] { step1, step2 })
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           .WithLoadSimulations(new []
            {
                Simulation.RampConcurrentScenarios(copiesCount: 10, during: TimeSpan.FromSeconds(20)),
                Simulation.KeepConcurrentScenarios(copiesCount: 10, during: TimeSpan.FromMinutes(1)),
                // Simulation.RampScenariosPerSec(copiesCount: 10, during: TimeSpan.FromSeconds(20)),
                // Simulation.InjectScenariosPerSec(copiesCount: 10, during: TimeSpan.FromMinutes(1))
            });

            NBomberRunner
            .RegisterScenarios(new[] { scenario })
            .RunInConsole();
        }
Exemple #5
0
        public static void Run()
        {
            var db = new MongoClient().GetDatabase("Test");

            Task initDb(ScenarioContext context)
            {
                var testData = Enumerable.Range(0, 2000)
                               .Select(i => new User {
                    Name = $"Test User {i}", Age = i, IsActive = true
                })
                               .ToList();

                db.DropCollection("Users", context.CancellationToken);
                return(db.GetCollection <User>("Users")
                       .InsertManyAsync(testData, cancellationToken: context.CancellationToken));
            }

            var usersCollection = db.GetCollection <User>("Users");

            var step = Step.Create("read IsActive = true and TOP 500", async context =>
            {
                await usersCollection.Find(u => u.IsActive)
                .Limit(500)
                .ToListAsync(context.CancellationToken);
                return(Response.Ok());
            });

            var scenario = ScenarioBuilder.CreateScenario("test_mongo", step)
                           .WithTestInit(initDb);

            NBomberRunner.RegisterScenarios(scenario)
            .RunInConsole();
        }
Exemple #6
0
        public static void Run()
        {
            var step = Step.Create("step", async context =>
            {
                await Task.Delay(TimeSpan.FromSeconds(0.1));
                return(Response.Ok(sizeBytes: 100));
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("simple_scenario", step)
                           .WithoutWarmUp()
                           .WithLoadSimulations(Simulation.KeepConstant(1, TimeSpan.FromMinutes(1)));

            var influxConfig = InfluxDbSinkConfig.Create("http://localhost:8086", dbName: "default");
            var influxDb     = new InfluxDBSink(influxConfig);

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithTestSuite("reporting")
            .WithTestName("influx_test")
            .WithReportingSinks(
                reportingSinks: new[] { influxDb },
                sendStatsInterval: TimeSpan.FromSeconds(10)
                )
            .Run();
        }
Exemple #7
0
        public static void Run()
        {
            var data = new[] { 1, 2, 3, 4, 5 }.ShuffleData();
            //var data = FeedData.FromJson<User>("./DataFeed/users-feed-data.json");
            //var data = FeedData.FromCsv<User>("./DataFeed/users-feed-data.csv");

            var feed = Feed.CreateCircular("numbers", data);

            // lazy
            //var feed = Feed.CreateCircular("numbers", getData: () => data);

            //var feed = Feed.CreateConstant("numbers", data);
            //var feed = Feed.CreateRandom("numbers", data);

            var step = Step.Create("step", feed, async context =>
            {
                await Task.Delay(Seconds(1));

                context.Logger.Debug("Data from feed: {FeedItem}", context.FeedItem);
                return(Response.Ok());
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("data_feed_scenario", step)
                           .WithLoadSimulations(Simulation.KeepConstant(1, TimeSpan.FromSeconds(1)));

            NBomberRunner
            .RegisterScenarios(scenario)
            .Run();
        }
 public static Scenario Build()
 {
     return(ScenarioBuilder
            .CreateScenario("Dapper connection pooling tests", BuildStep())
            .WithWarmUpDuration(WarmUpDuration)
            .WithLoadSimulations(BuildLoadSimulations()));
 }
Exemple #9
0
        public static Scenario BuildScenario()
        {
            var db = new MongoClient().GetDatabase("Test");

            Task initDb(CancellationToken token)
            {
                var testData = Enumerable.Range(0, 2000)
                               .Select(i => new User {
                    Name = $"Test User {i}", Age = i, IsActive = true
                })
                               .ToList();

                db.DropCollection("Users", token);
                return(db.GetCollection <User>("Users")
                       .InsertManyAsync(testData, cancellationToken: token));
            }

            var usersCollection = db.GetCollection <User>("Users");

            var step1 = Step.CreateAction("read IsActive = true and TOP 500", ConnectionPool.None, async context =>
            {
                await usersCollection.Find(u => u.IsActive == true)
                .Limit(500)
                .ToListAsync(context.CancellationToken);
                return(Response.Ok());
            });

            return(ScenarioBuilder.CreateScenario("test_mongo", step1)
                   .WithTestInit(initDb));
        }
Exemple #10
0
        public static Scenario BuildScenario()
        {
            HttpRequestMessage CreateHttpRequest()
            {
                var msg = new HttpRequestMessage();

                msg.RequestUri = new Uri("https://www.youtube.com/");
                msg.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
                msg.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
                return(msg);
            }

            var httpClient = new HttpClient();

            var step1 = Step.CreateAction("GET html", ConnectionPool.None, async context =>
            {
                var request = CreateHttpRequest();

                var response = await httpClient.SendAsync(request, context.CancellationToken);

                var responseSize = response.Content.Headers.ContentLength.HasValue
                    ? Convert.ToInt32(response.Content.Headers.ContentLength.Value)
                    : 0;

                return(response.IsSuccessStatusCode
                    ? Response.Ok(sizeBytes: responseSize)
                    : Response.Fail());
            });

            return(ScenarioBuilder.CreateScenario("test_youtube", step1));
        }
Exemple #11
0
        public static void Run()
        {
            // in this example we use NBomber.Http package which simplifies writing HTTP requests
            // you can find more here: https://github.com/PragmaticFlow/NBomber.Http

            var step = HttpStep.Create("http pull", context =>
                                       Http.CreateRequest("GET", "https://nbomber.com")
                                       .WithHeader("Accept", "text/html")
                                       //.WithHeader("Cookie", "cookie1=value1; cookie2=value2")
                                       //.WithBody(new StringContent("{ some JSON }", Encoding.UTF8, "application/json"))
                                       //.WithCheck(response => Task.FromResult(response.IsSuccessStatusCode))
                                       );

            var scenario = ScenarioBuilder.CreateScenario("test_nbomber", new[] { step })
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           .WithLoadSimulations(new[]
            {
                Simulation.InjectScenariosPerSec(copiesCount: 100, during: TimeSpan.FromSeconds(30))
            });

            var pingPluginConfig = PingPluginConfig.Create(new[] { "nbomber.com" });
            var pingPlugin       = new PingPlugin(pingPluginConfig);

            NBomberRunner
            .RegisterScenarios(new[] { scenario })
            .WithPlugins(new[] { pingPlugin })
            .RunInConsole();
        }
Exemple #12
0
        public static void Run()
        {
            var httpFactory = HttpClientFactory.Create();

            var step = Step.Create("fetch_html_page",
                                   clientFactory: httpFactory,
                                   execute: async context =>
            {
                var response = await context.Client.GetAsync("https://nbomber.com", context.CancellationToken);

                return(response.IsSuccessStatusCode
                    ? Response.Ok(statusCode: (int)response.StatusCode)
                    : Response.Fail(statusCode: (int)response.StatusCode));
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("nbomber_web_site", step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(5))
                           .WithLoadSimulations(new[]
            {
                Simulation.KeepConstant(copies: 1, during: TimeSpan.FromSeconds(30))
            });

            var pingPluginConfig = PingPluginConfig.CreateDefault(new[] { "nbomber.com" });
            var pingPlugin       = new PingPlugin(pingPluginConfig);

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithWorkerPlugins(pingPlugin)
            .WithTestSuite("http")
            .WithTestName("tracing_test")
            .WithLoggerConfig(() => new LoggerConfiguration().MinimumLevel.Verbose())     // set log to verbose
            .Run();
        }
Exemple #13
0
        static Scenario BuildScenario()
        {
            HttpRequestMessage CreateHttpRequest()
            {
                var msg = new HttpRequestMessage();

                msg.RequestUri = new Uri("https://github.com/PragmaticFlow/NBomber");
                msg.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
                msg.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
                return(msg);
            }

            var httpClient = new HttpClient();

            var step1 = Step.CreatePull("GET html", async _ =>
            {
                var request  = CreateHttpRequest();
                var response = await httpClient.SendAsync(request);
                return(response.IsSuccessStatusCode
                    ? Response.Ok()
                    : Response.Fail(response.StatusCode.ToString()));
            });

            return(ScenarioBuilder.CreateScenario("test github", step1)
                   .WithConcurrentCopies(100)
                   .WithDuration(TimeSpan.FromSeconds(10)));
        }
Exemple #14
0
        public async Task Test()
        {
            if (RpsTest == 0)
            {
                return;
            }

            var token = await CreateUserAndObtainToken(GenerateUsername());

            var step = Step.Create(GetTestName(),
                                   HttpClientFactory.Create(),
                                   context =>
            {
                var request = Http.CreateRequest("GET", $"{Url}/web/api/tasks?from=2021-10-31T23:00:00.000Z")
                              .WithHeader("accept", "application/json")
                              .WithHeader("authorization", $"Bearer {token}");

                return(Http.Send(request, context));
            }, timeout: TimeSpan.FromSeconds(Timeout));

            var scenario = ScenarioBuilder
                           .CreateScenario(GetTestName(), step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(5))
                           .WithLoadSimulations(
                Simulation.RampPerSec(RpsWarmUp, TimeSpan.FromSeconds(TimeWarmUp)),
                Simulation.RampPerSec(RpsTest, TimeSpan.FromSeconds(TimeRamp)),
                Simulation.InjectPerSec(RpsTest, TimeSpan.FromSeconds(TimeTest))
                // Simulation.InjectPerSecRandom(RpsMin, RpsMax, TimeSpan.FromSeconds(Time))
                );

            var result = await RunScenario(scenario);

            VerifyResults(result);
        }
Exemple #15
0
        public static void Run()
        {
            var step = Step.Create("step", async context =>
            {
                await Task.Delay(Seconds(0.1));

                context.Logger.Debug(
                    "step received CustomSettings.TestField '{TestField}'",
                    _customSettings.TestField
                    );

                return(Response.Ok()); // this value will be passed as response for the next step
            });

            var customPause = Step.CreatePause(() => _customSettings.PauseMs);

            var scenario = ScenarioBuilder
                           .CreateScenario("my_scenario", step, customPause)
                           .WithInit(ScenarioInit);

            NBomberRunner
            .RegisterScenarios(scenario)
            .LoadConfig("./HelloWorld/config.json")
            .Run();
        }
Exemple #16
0
        public void get_person()
        {
            const string url         = "https://localhost:5001";
            const string stepName    = "init";
            const int    duration    = 10;
            const int    expectedRps = 100;
            var          endpoint    = $"{url}/api/person/?id=3fa85f64-5717-4562-b3fc-2c963f66afa6";

            var step = HttpStep.Create(stepName, ctx =>
                                       Task.FromResult(Http.CreateRequest("GET", endpoint)
                                                       .WithCheck(response => Task.FromResult(response.IsSuccessStatusCode))));

            var assertions = new[]
            {
                Assertion.ForStep(stepName, s => s.RPS >= expectedRps),
                Assertion.ForStep(stepName, s => s.OkCount >= expectedRps * duration)
            };

            var scenario = ScenarioBuilder.CreateScenario("GET single person", new[] { step })
                           .WithConcurrentCopies(1)
                           .WithOutWarmUp()
                           .WithDuration(TimeSpan.FromSeconds(duration))
                           .WithAssertions(assertions);

            NBomberRunner.RegisterScenarios(scenario)
            .RunTest();
        }
Exemple #17
0
        public static void Run()
        {
            var db = new MongoClient().GetDatabase("Test");
            var usersCollection = db.GetCollection <User>("Users");

            var step = Step.Create("query_users", async context =>
            {
                await usersCollection.Find(u => u.IsActive)
                .Limit(500)
                .ToListAsync(context.CancellationToken);

                return(Response.Ok());
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("mongo_scenario", step)
                           .WithInit(ScenarioInit)
                           .WithLoadSimulations(new []
            {
                Simulation.KeepConstant(copies: 100, during: TimeSpan.FromSeconds(30))
            });

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithTestSuite("mongo")
            .WithTestName("simple_query_test")
            .Run();
        }
        public void get_game_event_sources()
        {
            //Arrange
            const string url         = "http://localhost:7001";
            const string stepName    = "init";
            const int    duration    = 3;
            const int    expectedRps = 100; //100 RPS
            var          endpoint    = $"{url}/game-event-sources";

            var step = HttpStep.Create(stepName, ctx =>
                                       Task.FromResult(Http.CreateRequest("GET", endpoint)
                                                       .WithCheck(response => Task.FromResult(response.IsSuccessStatusCode))));

            //Assert
            var assertions = new[]
            {
                Assertion.ForStep(stepName, s => s.RPS >= expectedRps), //we expected 100 rps but we serve 530 rps and this step will pass
                Assertion.ForStep(stepName, s => s.OkCount >= expectedRps * duration)
            };

            //Act
            var scenario = ScenarioBuilder.CreateScenario("GET game-event-sources", new[] { step })
                           .WithConcurrentCopies(1)
                           .WithOutWarmUp()
                           .WithDuration(TimeSpan.FromSeconds(duration))
                           .WithAssertions(assertions);

            NBomberRunner.RegisterScenarios(scenario)
            .RunTest();
        }
        public static void Run()
        {
            var httpFactory = HttpClientFactory.Create();

            var step1 = Step.Create("step 1", clientFactory: httpFactory, execute: async context =>
            {
                var request  = Http.CreateRequest("GET", "https://gitter.im");
                var response = await Http.Send(request, context);
                return(response);
            });

            var step2 = Step.Create("step 2", clientFactory: httpFactory, execute: async context =>
            {
                var step1Response = context.GetPreviousStepResponse <HttpResponseMessage>();
                var headers       = step1Response.Headers;
                var body          = await step1Response.Content.ReadAsStringAsync();

                var request  = Http.CreateRequest("GET", "https://gitter.im");
                var response = await Http.Send(request, context);
                return(response);
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("test_gitter", step1, step2)
                           .WithoutWarmUp()
                           .WithLoadSimulations(Simulation.InjectPerSec(100, TimeSpan.FromSeconds(30)));

            NBomberRunner
            .RegisterScenarios(scenario)
            .Run();
        }
Exemple #20
0
        public static void Run()
        {
            // it's a very basic HTTP example, don't use it for production testing
            // for production purposes use NBomber.Http which use performance optimizations
            // you can find more here: https://github.com/PragmaticFlow/NBomber.Http

            var httpClient = new HttpClient();

            var step = Step.Create("GET_gitter_html", async context =>
            {
                var response = await httpClient.GetAsync(
                    "https://gitter.im",
                    context.CancellationToken);

                return(response.IsSuccessStatusCode
                    ? Response.Ok(sizeBytes: (int)response.Content.Headers.ContentLength.Value)
                    : Response.Fail());
            });

            var scenario = ScenarioBuilder.CreateScenario("test_gitter", step)
                           .WithConcurrentCopies(100);

            NBomberRunner.RegisterScenarios(scenario)
            .RunInConsole();
        }
        public static void Run()
        {
            var step = HttpStep.Create("fetch_html_page", context =>
                                       Http.CreateRequest("GET", "https://nbomber.com")
                                       .WithHeader("Accept", "text/html")
                                       );

            var scenario = ScenarioBuilder
                           .CreateScenario("nbomber_web_site", step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(5))
                           .WithLoadSimulations(new[]
            {
                Simulation.KeepConstant(copies: 1, during: TimeSpan.FromSeconds(30))
            });

            var pingPluginConfig = PingPluginConfig.CreateDefault(new[] { "nbomber.com" });
            var pingPlugin       = new PingPlugin(pingPluginConfig);

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithPlugins(pingPlugin)
            .WithTestSuite("http")
            .WithTestName("tracing_test")
            .WithLoggerConfig(() => new LoggerConfiguration().MinimumLevel.Verbose())     // set log to verbose
            .Run();
        }
        public static void Run()
        {
            var step = Step.Create("step", async context =>
            {
                await Task.Delay(TimeSpan.FromSeconds(1));

                // this message will be saved to elastic search
                context.Logger.Debug("hello from NBomber");

                return(Response.Ok());
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("scenario", step)
                           .WithoutWarmUp()
                           .WithLoadSimulations(new[]
            {
                Simulation.KeepConstant(copies: 1, during: TimeSpan.FromSeconds(30))
            });

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithTestSuite("logging")
            .WithTestName("elastic_search")
            .LoadInfraConfig("./Logging/infra-config.json")
            .Run();
        }
Exemple #23
0
        public static Scenario BuildUsersFilterScenario(Configuration conf)
        {
            var positions            = new PositionsApi(conf).Get().Records;
            var getFilteredUsersStep = Step.CreateAction("Get filtered Users", ConnectionPool.None, async x =>
            {
                var positionsCount = new Random().Next(1, 5);
                var positionsToPut = positions.GetRange(0, positionsCount);
                var minAgeFilter   = new Random().Next(20, 60);
                var maxAgeFilter   = new Random().Next(minAgeFilter, 60);
                var minExpFilter   = new Random().Next(1, 20);
                var maxExpFilter   = new Random().Next(minExpFilter, 20);
                var filteredUsers  = await new UsersApi(conf).GetFilteredUsersAsyncWithHttpInfo(new RequestUsersModel
                {
                    WorkingExperience = new MinMaxValueRequestModel
                    {
                        MinValue = minExpFilter,
                        MaxValue = maxExpFilter
                    },
                    Age = new MinMaxValueRequestModel
                    {
                        MinValue = minAgeFilter,
                        MaxValue = maxAgeFilter
                    },
                    Positions = positionsToPut.Select(i => i.Id).ToList()
                });

                return(filteredUsers.StatusCode == 200 ? Response.Ok() : Response.Fail());
            });

            return(ScenarioBuilder.CreateScenario("Get Filtered Users Scenario", getFilteredUsersStep));
        }
        public static void Run()
        {
            var httpFactory = HttpClientFactory.Create();

            var step = Step.Create("fetch_html_page",
                                   clientFactory: httpFactory,
                                   execute: async context =>
            {
                var response = await context.Client.GetAsync("https://nbomber.com", context.CancellationToken);

                return(response.IsSuccessStatusCode
                    ? Response.Ok(statusCode: (int)response.StatusCode)
                    : Response.Fail(statusCode: (int)response.StatusCode));
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("simple_http", step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(5))
                           .WithLoadSimulations(new[]
            {
                Simulation.InjectPerSec(rate: 100, during: TimeSpan.FromSeconds(30))
            });

            var pingPluginConfig = PingPluginConfig.CreateDefault(new[] { "nbomber.com" });
            var pingPlugin       = new PingPlugin(pingPluginConfig);

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithWorkerPlugins(pingPlugin)
            .Run();
        }
Exemple #25
0
        static Scenario BuildScenario()
        {
            var server         = new FakePushServer();
            var updatesChannel = GlobalUpdatesChannel.Instance;

            var step1 = Step.CreatePull("publish", async req =>
            {
                var clientId = req.CorrelationId;
                var message  = $"Hi Server from client: {clientId}";

                server.Publish(clientId, message);
                return(Response.Ok());
            });

            var step2 = Step.CreatePush("update from server");

            server.Notify += (s, pushNotification) =>
            {
                updatesChannel.ReceivedUpdate(
                    correlationId: pushNotification.ClientId,
                    pushStepName: step2.Name,
                    update: Response.Ok(pushNotification.Message)
                    );
            };

            return(ScenarioBuilder.CreateScenario("PushScenario", step1, step2)
                   .WithConcurrentCopies(1)
                   .WithDuration(TimeSpan.FromSeconds(3)));
        }
Exemple #26
0
        public static void Run()
        {
            var step1 = Step.Create("step_1", async context =>
            {
                // you can do any logic here: go to http, websocket etc

                await Task.Delay(Seconds(0.1));
                return(Response.Ok(42)); // this value will be passed as response for the next step
            });

            var pause = Step.CreatePause(Milliseconds(100));

            var step2 = Step.Create("step_2", async context =>
            {
                var value = context.GetPreviousStepResponse <int>(); // 42
                return(Response.Ok());
            });

            // here you create scenario and define (default) step order
            // you also can define them in opposite direction, like [step2; step1]
            // or even repeat [step1; step1; step1; step2]
            var scenario = ScenarioBuilder
                           .CreateScenario("hello_world_scenario", step1, pause, step2)
                           .WithoutWarmUp()
                           .WithLoadSimulations(
                Simulation.KeepConstant(copies: 1, during: TimeSpan.FromSeconds(30))
                );

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithTestSuite("example")
            .WithTestName("hello_world_test")
            .Run();
        }
Exemple #27
0
    public ScenarioGraph(ScenarioBuilder sb)
    {
        parent     = sb;
        link_href  = new string[8];
        link_descr = new string[8];
        text       = GameObject.Find("questTask").GetComponent <Text>();
        image      = GameObject.Find("rightImage").GetComponent <RawImage>();

        try {
            xmlfile  = (TextAsset)Resources.Load(xmlname, typeof(TextAsset));
            scenario = new XmlDocument();
            scenario.LoadXml(xmlfile.text);
        }
        catch {
            CatchNotify("Failed to load scenario file"); return;
        }

        try {
            float engineVersion;
            scenarioTag   = scenario.GetElementsByTagName("scenario");
            engineVersion = float.Parse(scenarioTag.Item(0).Attributes.GetNamedItem("kraina_version").InnerText, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
            if (engineVersion > 1)
            {
                CatchNotify("Vrong scenario engine version (kraina_version: " + engineVersion + ")"); return;
            }
            startLocation = scenarioTag.Item(0).Attributes.GetNamedItem("start_location").InnerText;
            dataList      = scenario.GetElementsByTagName("item");
        }
        catch {
            CatchNotify("Failed to parsre scenario file"); return;
        }
    }
Exemple #28
0
        public static void Run()
        {
            var step = HttpStep.Create("fetch_html_page", context =>
                                       Http.CreateRequest("GET", "https://nbomber.com")
                                       .WithHeader("Accept", "text/html")
                                       );

            var scenario = ScenarioBuilder
                           .CreateScenario("nbomber_web_site", step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(5))
                           .WithLoadSimulations(new[]
            {
                Simulation.InjectPerSec(rate: 100, during: TimeSpan.FromSeconds(30))
            });

            var pingPluginConfig = PingPluginConfig.CreateDefault(new[] { "nbomber.com" });
            var pingPlugin       = new PingPlugin(pingPluginConfig);

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithWorkerPlugins(pingPlugin)
            .WithTestSuite("http")
            .WithTestName("simple_test")
            .Run();
        }
Exemple #29
0
        public async void ExploreSolution_GetAllTours_LoadTest()
        {
            string baseUrl        = "https://exploresolutionapi.azurewebsites.net";
            string loginUrl       = baseUrl + "/api/Authentication/request";
            string getAllToursUrl = baseUrl + "/api/tours/getAll";

            IStep loginStep = Auth(loginUrl);

            var getAllTours = HttpStep.Create("getAllTours", async(context) =>
            {
                var responseContent = context.Data as HttpResponseMessage;
                var authToken       = await responseContent.Content.ReadAsStringAsync();
                return(Http.CreateRequest("GET", getAllToursUrl)
                       .WithHeader("Authorization", $"Bearer {authToken}")
                       .WithCheck(async response =>
                {
                    return response.IsSuccessStatusCode ? Response.Ok() : Response.Fail();
                }));
            });


            var scenario = ScenarioBuilder.CreateScenario("Get All Tours", new[] { loginStep, getAllTours })
                           .WithoutWarmUp()
                           .WithLoadSimulations(new[]
            {
                Simulation.KeepConstant(1, TimeSpan.FromMinutes(1))
            });

            var nodeStats = NBomberRunner.RegisterScenarios(scenario).Run();
        }
Exemple #30
0
        public async void ExploreSolution_GetAllReservations_LoadTest()
        {
            string   baseUrl        = "https://exploresolutionapi.azurewebsites.net";
            string   loginUrl       = baseUrl + "/api/Authentication/request";
            string   getAllToursUrl = baseUrl + "/api/reservations/GetAllReservations";
            TimeSpan warmUp         = TimeSpan.FromMinutes(1);

            IStep loginStep = Auth(loginUrl);

            var getAllReservations = HttpStep.Create("getReservations", async(context) =>
            {
                var responseContent = context.Data as HttpResponseMessage;
                var authToken       = await responseContent.Content.ReadAsStringAsync();
                return(Http.CreateRequest("GET", getAllToursUrl)
                       .WithHeader("Authorization", $"Bearer {authToken}"));
                //.WithCheck(async response =>
                //{
                //    return response.IsSuccessStatusCode ? Response.Ok() : Response.Fail();
                //});
            });

            var influxConfig = InfluxDbSinkConfig.Create("https://westeurope-1.azure.cloud2.influxdata.com", dbName: "*****@*****.**");
            var influxDb     = new InfluxDBSink(influxConfig);

            var scenario = ScenarioBuilder.CreateScenario("Get All Reservations", new[] { loginStep, getAllReservations })
                           .WithWarmUpDuration(warmUp)
                           .WithLoadSimulations(new[]
            {
                Simulation.RampPerSec(10, TimeSpan.FromMinutes(1))
            });

            var nodeStats = NBomberRunner.RegisterScenarios(scenario).Run();
        }
        protected override ScenarioBuilder CreateScenarioBuilder()
        {
            var scenarioBuilder = new ScenarioBuilder();

            scenarioBuilder.Configuration
                           .UseSqlEventStore(c => c.UseConnectionString(EventStore.ConnectionString))
                           .UseSqlStorageForScheduledCommands(c => c.UseConnectionString(TestDatabases.CommandScheduler.ConnectionString))
                           .UseDependency(_ => ReadModelDbContext());

            return scenarioBuilder;
        }
        protected override ScenarioBuilder CreateScenarioBuilder()
        {
            CommandSchedulerDbContext.NameOrConnectionString =
                @"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=ItsCqrsTestsCommandScheduler";

            var scenarioBuilder = new ScenarioBuilder()
                .UseSqlEventStore()
                .UseSqlCommandScheduler();

            return scenarioBuilder;
        }
        public async Task In_memory_command_scheduling_is_enabled_by_default()
        {
            using (VirtualClock.Start())
            {
                // TODO: (In_memory_command_scheduling_is_enabled_by_default) 
                var scenario = new ScenarioBuilder().Prepare();

                await scenario.SaveAsync(new CustomerAccount()
                                        .Apply(new ChangeEmailAddress(Any.Email()))
                                        .Apply(new SendMarketingEmailOn(Clock.Now().AddDays(1))));

                VirtualClock.Current.AdvanceBy(TimeSpan.FromDays(1.0000001));

                var account = await scenario.GetLatestAsync<CustomerAccount>();

                account.Events().Last().Should().BeOfType<SentMarketingEmail>();
            }
        }
Exemple #34
0
 public void background(string keyword, string name, string description, int line)
 {
     this.isInExample = false;
     this.featureElementState.SetBackgroundActive();
     this.backgroundBuilder = new ScenarioBuilder();
     this.backgroundBuilder.SetName(name);
     this.backgroundBuilder.SetDescription(description);
 }
Exemple #35
0
        private void CaptureAndStoreRemainingElements()
        {
			if (this.isInExample && this.exampleBuilder != null)
			{
				this.scenarioOutlineBuilder.AddExample(this.exampleBuilder.GetResult());
			    this.exampleBuilder = null;
			}
			
            if (this.featureElementState.IsBackgroundActive)
            {
                this.backgroundBuilder.AddStep(this.stepBuilder.GetResult());
                this.theFeature.AddBackground(this.backgroundBuilder.GetResult());
            }
            else if (this.featureElementState.IsScenarioActive)
            {
                if (this.stepBuilder != null) this.scenarioBuilder.AddStep(this.stepBuilder.GetResult());
                this.theFeature.AddFeatureElement(this.scenarioBuilder.GetResult());
            }
            else if (this.featureElementState.IsScenarioOutlineActive)
            {
                if (this.stepBuilder != null) this.scenarioOutlineBuilder.AddStep(this.stepBuilder.GetResult());
                this.theFeature.AddFeatureElement(this.scenarioOutlineBuilder.GetResult());
            }

            this.stepBuilder = null;
            this.scenarioBuilder = null;
            this.scenarioOutlineBuilder = null;
            this.backgroundBuilder = null;
        }
Exemple #36
0
        public void scenario(string keyword, string name, string description, int line)
        {
            this.CaptureAndStoreRemainingElements();

            this.isInExample = false;
            this.featureElementState.SetScenarioActive();
            this.scenarioBuilder = new ScenarioBuilder();
            this.scenarioBuilder.SetName(name);
            this.scenarioBuilder.SetDescription(description);
            this.scenarioBuilder.AddTags(this.scenarioTags);
            this.scenarioTags.Clear();
        }