Monday, 23 January 2023

API load testing using k6

 Grafana k6 is an open-source load testing tool. K6 allows you to test the reliability and performance of your APIs and catch performance regressions and problems earlier.

By reading this article, you will learn how to perform load testing on RESTful APIs using K6.

Setup
K6 has a standalone installer/package for Linux, macOS, and Windows and also supports a docker container.

Windows
For Windows users, please use the Choco (chocolatey package manager) or Winget (Window package manager, which default comes with Windows OS).
To install open a command prompt and run the command as

Alternatively, you can download and run the latest official installer.

If you are using Visual Studio Code, you can use the extension “k6 for Visual Studio Code” to execute your script directly from visual studio code.

Linux
For Linux Users, use the command below to install the k6.

MacOS
For MacOS users, install K6 using the Homebrew package installer.

For Window users, After installing the k6 package open a command prompt and type k6. If you get below output then you are ready.

Test Lifecycle
K6 test lifecycle has four stages and each stage runs in the same order.

  1. init context: The init context runs once per VU and is generally used for tasks such as, loading local files, importing modules, declaring lifecycle functions etc. It is required.

2. setup function: setup function runs once in the entire lifecycle of the test and is generally used for data setups for tests. It is optional.

3. default function: default function depicts the test scenario, in short this is your test method. It is required.

4. teardown function: Like setup, teardown function also runs once in the entire lifecycle and is generally used for cleanup or postprocessing data stuff. It is optional.

If the Setup function ends abnormally (e.g throws an error), the teardown() function isn’t called. Consider adding logic to the setup() function to handle errors and ensure proper cleanup.

Now let's write a test for REST API. For my tests here, I’m using Httpx library which is available here: https://jslib.k6.io/httpx/0.0.1/index.js

HTTP Get Request
Create your first script to test a Get REST request. To do this create a js file, for example k6-testscripts.js

Now let’s run the below script in the command prompt to execute the script:

If all is well, the result of the above scripts would be as:

The above result says, the Get request took 427.15ms (http_req_duration) to complete, and took 34.97ms to connect (http_req_connecting) for one HTTP request. (http_reqs).

Now the same Get request will continuously for 30 seconds and 30 VUs.

In my case, the above command results:

Based on the above results, a total of 319 requests (http_reqs) have been made and out of 319 requests, response time checks failed for 30 requests as it took more than 1000ms but all succeeded successfully as far as success response concerns.

HTTP Post request
For post request the test scripts would be as:

Complete Result output summary
Here are the complete lists of summaries generated from your request execution.

  1. checks: rate of successful checks percentage from total no. of checks, it also includes the no. of checks passed and failed.
  2. data_received: the amount of data received.
  3. data_sent: the amount of data sent.
  4. errors: rate of error percentage for failure checks.
  5. http_req_blocked : average time spent waiting for TCP connection
  6. http_req_connecting : average time spent establishing a TCP connection
  7. http_req_duration: average total time for the request. It’s calculated based on http_req_sending + http_req_waiting + http_req_receiving.
  8. http_req_failed: percentage of failed requests. in our case 0 (0.00%) failed out of 319 requests.
  9. http_req_receiving : average time spent on data receiving
  10. http_req_sending: average time spent on data sending
  11. http_req_tls_handshaking : average time spent on TLS handshaking
  12. http_req_waiting: average time spent on waiting for a response from the remote host
  13. http_reqs : total number of requests
  14. iteration_duration: average time it took to execute the default function for each iteration.
  15. iterations: total no. of iterations to execute default function (test method)
  16. vus: number of virtual users. It is also represented as VU.
  17. vus_max: maximum no. of virtual users allocated for the test execution.

httpx library
To know more about the httpx library to for other HTTP request as Put, Patch, Delete etc, please refer the doc here: https://k6.io/docs/javascript-api/jslib/httpx/post/

Hope you enjoyed the content, follow me for more like this, and please don’t forget to LIKE it. Happy programming.

Sunday, 11 December 2022

Generic Attributes in C#11

 

In C# 11 comes with .Net 7, Attribute is enhanced to use with generic type. This feature provides a convenient way for attributes to avoid System.Type constructor parameter (the old way).

Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime. Attributes are used to impose conditions or to increase the efficiency of a piece of code.

Being a programmer I love this. Here I will try to explain to you how to define Attributes with generic types. To understand the enhancement, let's see how we used to do the Attributes with type in C# 10 or before.

For example, we will create an Asp.Net core web API project template with the target framework net7.0 so the same project will be using the demonstration of old and new syntax.

Here I will be creating an Action Filter called LoggingFilter and will be logging some info before and after the execution of an action.

The above code is straightforward. So now we add this to the service collection.

To use this action filter with an Action method we will use Microsoft.AspNetCore.Mvc.ServiceFilter attribute which is using the old syntax which takes System.Type as a parameter for the constructor and the definition of ServiceFilterAttribute.

Next, we will use the action filter with the Get action method of the WeatherForecastController generated from the template.

Now you run the application and execute the GetWeatherForecast endpoint from the swagger app, you will see the information log in the output window as

Cool, Everything works great but How about Microsoft would have made the ServiceFilterAttribute generic and avoid the type parameter in the constructor? Well, we will do it and will write better code than Microsoft. :) Just kidding. Actually, this is the enhancement done in C#11, thanks to Microsoft for that.

To redefine the ServiceFilterAttribute using the Generic Attribute feature, let’s see the ServiceFilterAttribute code which is available under Microsoft.AspNetCore.Mvc namespace:

As per the above Microsoft code here, ServiceFilter takes Type as a parameter in the constructor which we pass as typeof(LoggingFilter) in the action method. So now we will recreate the ServiceFilterAttribute by defining a generic attribute and the syntax would be as:

public class MyServiceFilterAttribute<T> : Attribute

and the code as:

Wow, no more type parameters and a very convenient way of making the attribute class generic.

Again if you run the application, the logs will be displayed in the output window as with the earlier code.

No difference in functionality but a huge difference in terms of better code.

Here is the full code used for this example:
https://github.com/binodmahto/FunProjects/tree/main/CSharp11WebAPIDemo

To know more about C#11 new features please read through:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11

Hope you enjoyed the content, follow me for more like this, and please don’t forget to LIKE it. Happy programming.