Exemplo n.º 1
0
        public static void Run()
        {
            var data = FeedData.FromSeq(new[] { 1, 2, 3, 4, 5 }).ShuffleData();
            //var data = FeedData.FromSeq(getItems: () => 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);
            //var feed = Feed.CreateConstant("numbers", data);
            //var feed = Feed.CreateRandom("numbers", data);

            var step = Step.Create("step", feed, async context =>
            {
                await Task.Delay(TimeSpan.FromSeconds(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();
        }
Exemplo n.º 2
0
        public static void Run()
        {
            var data = FeedData.FromSeq(new[] { 1, 2, 3, 4, 5 }).ShuffleData();
            //var data = FeedData.FromJson<User>("users_feed_data.json");
            //var data = FeedData.FromCsv<User>("users_feed_data.csv");

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

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

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

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

            NBomberRunner.RegisterScenarios(scenario)
            .RunInConsole();
        }
Exemplo n.º 3
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();
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            IFeed <RequestInfo> urlsDataFeed = Feed.CreateConstant("Requests", FeedData.FromSeq(relativeUrlsToTest));

            IStep relativeUrlsHttpRequestStep = HttpStep.Create(
                name: $"Fetch random Ebriza data intensive URLs",
                feed: urlsDataFeed,
                ctx =>
            {
                string cookies = httpClientHandler.CookieContainer.GetCookieHeader(new Uri($"{webProtocol}{webDomain}"));
                NBomber.Http.HttpRequest result
                    = Http.CreateRequest(ctx.FeedItem.Method, $"{webProtocol}{webDomain}{ctx.FeedItem.RelativeUrl}")
                      .WithHeader("Cookie", cookies)
                      .WithCheck(async res => res.IsSuccessStatusCode && res.RequestMessage.RequestUri.ToString().Contains(ctx.FeedItem.RelativeUrl, StringComparison.InvariantCultureIgnoreCase) ? Response.Ok() : Response.Fail(res.StatusCode.ToString()))
                    ;
                if (ctx.FeedItem.Body != null)
                {
                    result = result.WithBody(new StringContent(JsonConvert.SerializeObject(ctx.FeedItem.Body), Encoding.UTF8, ctx.FeedItem.ContentType));
                }
                return(result);
            }, completionOption: HttpCompletionOption.ResponseContentRead
                );

            NBomber.Contracts.Scenario userPerSecondScenario
                = ScenarioBuilder
                  .CreateScenario(name: $"Load Testing Scenario for {webDomain} with {usersPerSecondToSimulate} users per second", relativeUrlsHttpRequestStep)
                  .WithWarmUpDuration(defaultWarmupDuration)
                  .WithInit(async ctx =>
            {
                using (HttpResponseMessage response
                           = await http.PostAsync(
                                 $"{webProtocol}{webDomain}/Login/Login",
                                 new StringContent(
                                     JsonConvert.SerializeObject(
                                         new
                {
                    CompanyHandle = companyHandle,
                    UserName = username,
                    Password = password,
                }
                                         ),
                                     Encoding.UTF8,
                                     "application/json"
                                     )
                                 )
                           )
                {
                    response.EnsureSuccessStatusCode();
                };
            })
                  .WithClean(ctx =>
            {
                http.CancelPendingRequests();
                httpClientHandler.Dispose();
                http.Dispose();
                return(System.Threading.Tasks.Task.CompletedTask);
            })
                  .WithLoadSimulations(new NBomber.Contracts.LoadSimulation[] {
                Simulation.InjectPerSec(rate: usersPerSecondToSimulate, during: defaultSimulationDuration),    //RATE scenarios per second, for a timespan of DURING seconds)
            });

            PingPluginConfig pingPluginConfig = PingPluginConfig.CreateDefault(new string[] { webDomain });
            PingPlugin       pingPlugin       = new PingPlugin(pingPluginConfig);

            NBomberRunner
            .RegisterScenarios(userPerSecondScenario)
            .WithTestSuite("Ebriza Load Testing")
            .WithTestName($"Load test {webDomain}")
            .WithWorkerPlugins(pingPlugin)
            .Run();
        }
Exemplo n.º 5
0
        public void Run()
        {
            var data     = FeedData.FromSeq(new[] { 1, 2, 3, 4, 5 });
            var dataFeed = Feed.CreateRandom("random_feed", data);

            var webSocketConnectionPool =
                ConnectionPoolArgs.Create(
                    name: "web_socket_pool",
                    getConnectionCount: () => 10,
                    openConnection: async(number, token) =>
            {
                await Task.Delay(1_000);
                return(new FakeSocketClient {
                    Id = number
                });
            },
                    closeConnection: (connection, token) =>
            {
                Task.Delay(1_000).Wait();
                return(Task.CompletedTask);
            });

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

                // context.CorrelationId - every copy of scenario has correlation id
                // context.Connection    - fake websocket connection taken from pool
                // context.FeedItem      - item taken from data feed
                // context.Logger
                // context.StopScenario("hello_world_scenario", reason = "")
                // context.StopTest(reason = "")

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

                // return Response.Ok(42, sizeBytes: 100, latencyMs: 100); - you can specify response size and custom latency
                // return Response.Fail();                                 - in case of fail, the next step will be skipped
            });

            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 })
                           .WithTestInit(TestInit)
                           .WithTestClean(TestClean)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           // .WithoutWarmUp() - disable warm up
                           .WithLoadSimulations(new []
            {
                Simulation.RampConcurrentScenarios(copiesCount: 20, during: TimeSpan.FromSeconds(20)),
                Simulation.KeepConcurrentScenarios(copiesCount: 20, during: TimeSpan.FromMinutes(1)),
                // Simulation.RampScenariosPerSec(copiesCount: 10, during: TimeSpan.FromSeconds(20)),
                // Simulation.InjectScenariosPerSec(copiesCount: 10, during: TimeSpan.FromMinutes(1))
            });

            NBomberRunner
            .RegisterScenarios(new[] { scenario })
            //.LoadConfigJson("config.json")            // nbomber config for test settings only
            //.LoadInfraConfigJson("infra_config.json") // infra config for infra settings only
            //.LoadConfigYaml("config.yaml")            // you can use yaml instead of json (https://github.com/PragmaticFlow/NBomber/blob/dev/tests/NBomber.IntegrationTests/Configuration/test_config.yaml)
            //.LoadInfraConfigYaml("infra_config.yaml")
            .RunInConsole();
        }