예제 #1
0
        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();
        }
예제 #2
0
        public void AddNew()
        {
            //Arrange
            AddNewCarRequest addNewCarRequest = new AddNewCarRequest("BMW", 1999);
            string           json             = JsonSerializer.Serialize(addNewCarRequest);
            StringContent    content          = new StringContent(json, Encoding.UTF8, "application/json");

            var step = HttpStep.Create("addNew", ctx =>
                                       Task.FromResult(Http.CreateRequest("POST", endpoint)
                                                       .WithBody(content)
                                                       ));

            var scenario = ScenarioBuilder.CreateScenario("Add", step)
                           .WithoutWarmUp()
                           .WithLoadSimulations(Simulation.KeepConstant(2, TimeSpan.FromSeconds(30)));

            //Act
            NodeStats nodeStats = NBomberRunner.RegisterScenarios(scenario).Run();

            //Assert
            nodeStats.OkCount.Should().Be(nodeStats.RequestCount);
            StepStats stepStats = nodeStats.ScenarioStats[0].StepStats[0];

            stepStats.RPS.Should().BeGreaterOrEqualTo(1500);
        }
예제 #3
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();
        }
예제 #4
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.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 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();
        }
예제 #6
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();
        }
예제 #7
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();
        }
        public void Post_with_Get_load_test()
        {
            const string request = @"{
                                        ""firstName"": ""load"",
                                        ""lastName"": ""test"",
                                        ""gender"": ""M"",
                                        ""birthDate"": ""1980-11-11""
                                    }";

            var post = CreateStep("/", "POST", request.ToStringContent());

            var get = HttpStep.Create("get emp", async ctx =>
            {
                var response = ctx.GetPreviousStepResponse <HttpResponseMessage>();
                var content  = await response.Content.ReadAsStringAsync();
                var emp      = content.Deserialize <EmployeeDto>();
                Trace.WriteLine($"The previous step created employee with Id = {emp.Id}");

                var getUrl = response.Headers.Location;

                return(Http.CreateRequest("GET", getUrl.ToString())
                       .WithHeader("Authorization", "ApiKey ABC-xyz")
                       .WithCheck(response => Task.FromResult(response.GetCheckResult())));
            });

            ExecuteLoadTests(post, get);
        }
예제 #9
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();
        }
예제 #10
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();
        }
예제 #11
0
        protected static Scenario CreateGetScenario(string nameScenatio, string uri)
        {
            var step = HttpStep.Create("Request step", context => Http.CreateRequest("GET", Constants.MovieService.Url + uri));

            return(ScenarioBuilder
                   .CreateScenario(nameScenatio, new[] { step })
                   .WithConcurrentCopies(10)
                   .WithDuration(TimeSpan.FromSeconds(10)));
        }
예제 #12
0
        public static Scenario Create()
        {
            var step = HttpStep.Create("pull home page", (context) =>
                                       Http.CreateRequest("GET", "https://nbomber.com")
                                       .WithHeader("Accept", "text/html")
                                       );

            return(ScenarioBuilder.CreateScenario("simple http scenario", new[] { step }));
        }
예제 #13
0
        public static void Run()
        {
            var userFeed = Feed.CreateRandom(
                name: "userFeed",
                provider: FeedData.FromJson <UserId>("./HttpTests/Configs/user-feed.json")
                );

            var getUser = HttpStep.Create("get_user", userFeed, context =>
            {
                var userId = context.FeedItem;
                var url    = $"https://jsonplaceholder.typicode.com/users?id={userId}";

                return(Http.CreateRequest("GET", url)
                       .WithCheck(async response =>
                {
                    var json = await response.Content.ReadAsStringAsync();

                    // parse JSON
                    var users = JsonConvert.DeserializeObject <UserResponse[]>(json);

                    return users?.Length == 1
                            ? Response.Ok(users.First()) // we pass user object response to the next step
                            : Response.Fail("not found user");
                }));
            });

            // this 'getPosts' will be executed only if 'getUser' finished OK.
            var getPosts = HttpStep.Create("get_posts", context =>
            {
                var user = context.GetPreviousStepResponse <UserResponse>();
                var url  = $"https://jsonplaceholder.typicode.com/posts?userId={user.Id}";

                return(Http.CreateRequest("GET", url)
                       .WithCheck(async response =>
                {
                    var json = await response.Content.ReadAsStringAsync();

                    // parse JSON
                    var posts = JsonConvert.DeserializeObject <PostResponse[]>(json);

                    return posts?.Length > 0
                            ? Response.Ok()
                            : Response.Fail($"not found posts for user: {user.Id}");
                }));
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("rest_api", getUser, getPosts);

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithWorkerPlugins(new PingPlugin())
            .LoadConfig("./HttpTests/Configs/config.json")
            .LoadInfraConfig("./HttpTests/Configs/infra-config.json")
            .Run();
        }
        private IStep GetStep(string url, string method, HttpContent body)
        {
            var stepName = $"{method} '{url}'";

            return(HttpStep.Create(stepName, ctx =>
                                   Http.CreateRequest(method, url)
                                   .WithHeader("Authorization", "ApiKey ABC-xyz")
                                   .WithBody(body)
                                   .WithCheck(response => Task.FromResult(response.IsSuccessStatusCode))
                                   ));
        }
예제 #15
0
        public static void Run()
        {
            var step = HttpStep.Create("simple step", (context) =>
                                       Http.CreateRequest("GET", "https://gitter.im")
                                       .WithHeader("Accept", "text/html")
                                       );

            var scenario = ScenarioBuilder.CreateScenario("test_gitter", new[] { step });

            NBomberRunner.RegisterScenarios(scenario)
            .LoadTestConfig("test_config.json")
            .RunInConsole();
        }
예제 #16
0
        protected NodeStats RunScenario(string name, Func <HttpRequest> request, int parallelCopies = 100,
                                        TimeSpan?period = null)
        {
            var step     = HttpStep.Create("init", ctx => Task.FromResult(request()));
            var scenario = ScenarioBuilder.CreateScenario(name, step)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(3))
                           .WithLoadSimulations(LoadSimulation.NewKeepConstant(parallelCopies, period ?? TimeSpan.FromSeconds(10)));

            var stats     = NBomberRunner.RegisterScenarios(scenario).Run();
            var jsonStats = JsonSerializer.Serialize(stats);

            Output.WriteLine(jsonStats);

            return(stats);
        }
예제 #17
0
        private Scenario Build(string method, object[] @params = null)
        {
            var request = new JsonRpcRequest(method, @params);
            var json    = System.Text.Json.JsonSerializer.Serialize(request);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var step    = HttpStep.Create(method, ctx =>
                                          Task.FromResult(Http.CreateRequest("POST", _url)
                                                          .WithHeader("content-type", "application/json")
                                                          .WithBody(content)
                                                          .WithCheck(response => Task.FromResult(response.IsSuccessStatusCode))));

            return(ScenarioBuilder.CreateScenario($"Nethermind -> {method}()", step)
                   .WithConcurrentCopies(100)
                   .WithDuration(TimeSpan.FromSeconds(10)));
        }
예제 #18
0
        static void Main(string[] args)
        {
            var influxDb = new InfluxDBSink(url: "http://localhost:8086", dbName: "NBomberDb");

            var step = HttpStep.Create("simple step", (context) =>
                                       Http.CreateRequest("GET", "https://nbomber.com")
                                       );

            var scenario = ScenarioBuilder.CreateScenario("test_nbomber", new[] { step })
                           .WithConcurrentCopies(100)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           .WithDuration(TimeSpan.FromMinutes(3));

            NBomberRunner.RegisterScenarios(scenario)
            .WithReportingSinks(new[] { influxDb }, TimeSpan.FromSeconds(20))
            .RunInConsole();
        }
예제 #19
0
        public static void Run()
        {
            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 })
                           .WithConcurrentCopies(100)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           .WithDuration(TimeSpan.FromSeconds(20));

            NBomberRunner.RegisterScenarios(scenario)
            .RunInConsole();
        }
예제 #20
0
        public static void Run(string configPath)
        {
            var step = HttpStep.Create("simple step", (context) =>
                                       Http.CreateRequest("GET", "https://gitter.im")
                                       .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_gitter", step);

            NBomberRunner.RegisterScenarios(scenario)
            .LoadConfig(configPath)
            //.LoadConfig("agent_config.json")
            //.LoadConfig("coordinator_config.json")
            .RunInConsole();
        }
예제 #21
0
        public static void Run()
        {
            var influxDb = new InfluxDBSink(url: "http://localhost:8086", dbName: "default");

            var step = HttpStep.Create("simple step", context =>
                                       Http.CreateRequest("GET", "https://nbomber.com")
                                       .WithHeader("Accept", "text/html")
                                       );

            var scenario = ScenarioBuilder.CreateScenario("test_nbomber", new[] { step })
                           .WithConcurrentCopies(50)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           .WithDuration(TimeSpan.FromSeconds(180));

            NBomberRunner.RegisterScenarios(scenario)
            .WithReportingSinks(new[] { influxDb }, sendStatsInterval: TimeSpan.FromSeconds(20))
            .RunInConsole();
        }
예제 #22
0
        public static void Run()
        {
            var influxDb = new InfluxDBSink(url: "http://localhost:8086", dbName: "default");

            var step = HttpStep.Create("simple step", (context) =>
                                       Http.CreateRequest("GET", "https://gitter.im")
                                       .WithHeader("Accept", "text/html")
                                       );

            var scenario = ScenarioBuilder.CreateScenario("test_gitter", step)
                           .WithConcurrentCopies(50)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           .WithDuration(TimeSpan.FromSeconds(180));

            NBomberRunner.RegisterScenarios(scenario)
            .SaveStatisticsTo(influxDb)
            .RunInConsole();
        }
        public static void Run()
        {
            var step = HttpStep.Create("simple step", (context) =>
                                       Http.CreateRequest("GET", "https://nbomber.com")
                                       .WithHeader("Accept", "text/html")
                                       // .WithBody(new StringContent("{ some JSON }"))
                                       // .WithCheck(async (response) =>
                                       //     response.IsSuccessStatusCode
                                       //         ? Response.Ok()
                                       //         : Response.Fail()
                                       // )
                                       );

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

            NBomberRunner
            .RegisterScenarios(scenario)
            .LoadConfig("test_config.json")
            .Run();
        }
예제 #24
0
        public void Test()
        {
            var step = HttpStep.Create("request",
                                       context => Http.CreateRequest("GET", "http://localhost:5000/api/remote")
                                       .WithHeader("Content-Type", "application/json"));

            var pause = Step.Create("pause", async context =>
            {
                var r = new Random();
                await Task.Delay(r.Next(100, 30000));
                return(Response.Ok());
            });

            var scenario = ScenarioBuilder.CreateScenario("test load", step, pause)
                           .WithConcurrentCopies(1000)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           .WithDuration(TimeSpan.FromSeconds(300));

            NBomberRunner.RegisterScenarios(scenario).RunTest();
        }
예제 #25
0
        public static void Run()
        {
            var step1 = HttpStep.Create("step 1", (context) =>
                                        Http.CreateRequest("GET", "https://gitter.im"));

            var step2 = HttpStep.Create("step 2", async(context) =>
            {
                var step1Response = context.GetPreviousStepResponse();
                var headers       = step1Response.Headers;
                var body          = await step1Response.Content.ReadAsStringAsync();

                return(Http.CreateRequest("GET", "https://gitter.im"));
            });

            var scenario = ScenarioBuilder.CreateScenario("test_gitter", new[] { step1, step2 });

            NBomberRunner.RegisterScenarios(scenario)
            .LoadTestConfig("test_config.json")
            .RunInConsole();
        }
예제 #26
0
        protected IStep CreateStep(string action, string method, HttpContent body)
        {
            var url      = $"{BaseUrl}/{ResourceUrl}{action}";
            var stepName = $"{method} '{url}'";

            return(HttpStep.Create(stepName, ctx =>
                                   Http.CreateRequest(method, url)
                                   .WithHeader("Authorization", "ApiKey ABC-xyz")
                                   .WithBody(body)
                                   .WithCheck(async response =>
            {
                Trace.WriteLine($"Response status: {response.StatusCode}");
                if (!response.IsSuccessStatusCode)
                {
                    Trace.TraceError(await response.Content.ReadAsStringAsync());
                }
                return response.IsSuccessStatusCode;
            })
                                   ));
        }
예제 #27
0
        private static IStep Auth(string loginUrl)
        {
            var loginStep = HttpStep.Create("login", context =>
                                            Http.CreateRequest("POST", loginUrl)
                                            //.WithBody(new StringContent(@"{ ""username"" : ""user"", ""password"": ""pass"" }"))
                                            //.WithHeader("Content-Type", "application/json")
                                            .WithBody(new StringContent(JsonConvert.SerializeObject(new LoginModel {
                Username = "******", Password = "******"
            }), Encoding.UTF8, "application/json"))
                                            .WithCheck(async response =>
            {
                return(response.IsSuccessStatusCode ? Response.Ok() : Response.Fail());
            })
                                            .WithCheck(async response =>
            {
                string token = await response.Content.ReadAsStringAsync();
                return(token != string.Empty ? Response.Ok() : Response.Fail());
            }));

            return(loginStep);
        }
예제 #28
0
        public static void Run()
        {
            var step1 = HttpStep.Create("step 1", (context) =>
                                        Http.CreateRequest("GET", "https://gitter.im"));

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

                return(Http.CreateRequest("GET", "https://gitter.im"));
            });

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

            NBomberRunner
            .RegisterScenarios(scenario)
            .LoadConfig("test_config.json")
            .Run();
        }
예제 #29
0
        public static void Run()
        {
            var userFeed = Feed.CreateRandom(
                name: "userFeed",
                provider: FeedData.FromSeq(new[] { "1", "2", "3", "4", "5" })
                );

            var getUser = HttpStep.Create("get_user", userFeed, context =>
            {
                var userId = context.FeedItem;
                var url    = $"https://jsonplaceholder.typicode.com/users?id={userId}";

                return(Http.CreateRequest("GET", url)
                       .WithCheck(async response =>
                {
                    var json = await response.Content.ReadAsStringAsync();

                    // parse JSON
                    var users = JsonConvert.DeserializeObject <UserResponse[]>(json);

                    return users?.Length == 1
                            ? Response.Ok(users.First()) // we pass user object response to the next step
                            : Response.Fail($"not found user: {userId}");
                }));
            });

            // this 'getPosts' will be executed only if 'getUser' finished OK.
            var getPosts = HttpStep.Create("get_posts", context =>
            {
                var user = context.GetPreviousStepResponse <UserResponse>();
                var url  = $"https://jsonplaceholder.typicode.com/posts?userId={user.Id}";

                return(Http.CreateRequest("GET", url)
                       .WithCheck(async response =>
                {
                    var json = await response.Content.ReadAsStringAsync();

                    // parse JSON
                    var posts = JsonConvert.DeserializeObject <PostResponse[]>(json);

                    return posts?.Length > 0
                            ? Response.Ok()
                            : Response.Fail($"not found posts for user: {user.Id}");
                }));
            });

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

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

            NBomberRunner
            .RegisterScenarios(scenario)
            .WithPlugins(pingPlugin)
            .WithTestSuite("http")
            .WithTestName("advanced_test")
            .Run();
        }
예제 #30
0
        public static void Run()

        {
            string usid                            = "ba99fcf6-bc5a-4713-ad5d-6f0ca3e952b3";
            var    GetAcceptances                  = $"https://btcnadly.centralus.cloudapp.azure.com/svc/legal-document-check/api/legaldocumentcheck/api/legaldocumentcheck/{usid}/acceptlatest";
            var    IsAcceptanceRequired            = $"https://btcnadly.centralus.cloudapp.azure.com/svc/legal-document-check//api/legaldocumentcheck/{usid}/isacceptancerequired?appBrand=bmw&clientVersion=8.0&locale=en-us&platform=ios&region=na";
            var    GetLatestDocuments              = $"https://btcnadly.centralus.cloudapp.azure.com/svc/legal-document-check/api/legaldocumentcheck/latestdocument/cd_pp/bmw/ios/na?clientVersion=8.0&locale=en-us;";
            var    GetLatestDocumentServiceManager = $"https://btcnadly.centralus.cloudapp.azure.com/svc/legal-document-check/api/legaldocumentcheck/latestservicemanagerdocuments?appBrand=bmw&clientVersion=8.0&locale=en-us&platform=ios&region=na";
            var    GetLatestDocument               = $"https://btcnadly.centralus.cloudapp.azure.com/svc/legal-document-check/api/legaldocumentcheck/latestdocument/cd_pp/bmw/ios/na?clientVersion=8.0&locale=bg-bg";
            var    GetViewLatestDocument           = $"https://btcnadly.centralus.cloudapp.azure.com/svc/legal-document-check/api/legaldocumentcheck/viewlatestdocument/cd_pp/bmw/ios/na?clientVersion=8.0&locale=bg-bg";
            var    AcceptLatest                    = $"https://btcnadly.centralus.cloudapp.azure.com/svc/legal-document-check/api/legaldocumentcheck/{usid}/acceptlatest";


            //var getAcceptance = HttpStep.Create("GetAcceptances NA DLY", (context) =>
            //        Http.CreateRequest("GET", GetAcceptances)
            //            .WithHeader("Accept", "text/html")
            //            .WithHeader("x-functions-key", "SZGsMU/rbFRf/a8LgoZk0TU6ycB3WxwgjaVFIYchDCW0AaKstzjXJA==")
            //);
            var isAcceptanceRequired = HttpStep.Create("IsAcceptanceRequired NA DLY", (context) =>
                                                       Http.CreateRequest("GET", IsAcceptanceRequired)
                                                       .WithHeader("Accept", "text/html")
                                                       .WithHeader("x-functions-key", "SZGsMU/rbFRf/a8LgoZk0TU6ycB3WxwgjaVFIYchDCW0AaKstzjXJA==")
                                                       );

            var getLatestDocuments = HttpStep.Create("GetLatestDocuments NA DLY", (context) =>
                                                     Http.CreateRequest("GET", GetLatestDocuments)
                                                     .WithHeader("Accept", "text/html")
                                                     .WithHeader("x-functions-key", "SZGsMU/rbFRf/a8LgoZk0TU6ycB3WxwgjaVFIYchDCW0AaKstzjXJA==")
                                                     );

            var getLatestDocumentServiceManager = HttpStep.Create("GetLatestDocumentServiceManager NA DLY", (context) =>
                                                                  Http.CreateRequest("GET", GetLatestDocumentServiceManager)
                                                                  .WithHeader("Accept", "text/html")
                                                                  .WithHeader("x-functions-key", "SZGsMU/rbFRf/a8LgoZk0TU6ycB3WxwgjaVFIYchDCW0AaKstzjXJA==")
                                                                  );

            var getLatestDocument = HttpStep.Create("GetLatestDocument NA DLY", (context) =>
                                                    Http.CreateRequest("GET", GetLatestDocument)
                                                    .WithHeader("Accept", "text/html")
                                                    .WithHeader("x-functions-key", "SZGsMU/rbFRf/a8LgoZk0TU6ycB3WxwgjaVFIYchDCW0AaKstzjXJA==")
                                                    );
            var viewLatestDocument = HttpStep.Create("GetViewLatestDocument NA DLY", (context) =>
                                                     Http.CreateRequest("GET", "GetViewLatestDocument")
                                                     .WithHeader("Accept", "text/html")
                                                     .WithHeader("x-functions-key", "SZGsMU/rbFRf/a8LgoZk0TU6ycB3WxwgjaVFIYchDCW0AaKstzjXJA==")
                                                     );

            var body             = "{\"conditions\":[\"a\", \"b\"],\"clientVersion\":\"8.0\",\"region\":\"NA\",\"locale\":\"en_US\",\"platform\":\"ios\",\"appbrand\":\"bmw\"}";
            var acceptLatestStep = HttpStep.Create("AcceptLatest", (context) =>
                                                   Http.CreateRequest("POST", "AcceptLatest")
                                                   .WithHeader("Content-Type", "application/json")
                                                   .WithHeader("Authorization", "gcdmToken")
                                                   .WithHeader("User-Agent", "userAgentHeader")
                                                   .WithHeader("x-functions-key", "SZGsMU/rbFRf/a8LgoZk0TU6ycB3WxwgjaVFIYchDCW0AaKstzjXJA==")
                                                   .WithBody(new StringContent(body, Encoding.UTF8, "application/json"))
                                                   .WithCheck(response => Task.FromResult(response.IsSuccessStatusCode))
                                                   );

            var scenario_1 = ScenarioBuilder.CreateScenario("500", new NBomber.Contracts.IStep[] { isAcceptanceRequired, getLatestDocuments, getLatestDocumentServiceManager, viewLatestDocument, acceptLatestStep })
                             .WithConcurrentCopies(500)
                             .WithWarmUpDuration(TimeSpan.FromSeconds(0))
                             .WithDuration(TimeSpan.FromSeconds(120));

            NBomberRunner.RegisterScenarios(scenario_1)
            //.LoadConfig("config.json")
            .RunInConsole();
        }