pariksha

package module
v0.0.0-...-4521c65 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

README

go-pariksha 🧪

Go Report Card Go Version

go-pariksha is a lightweight and expressive testing + benchmarking toolkit for Go, tailored to HTTP API test cases using the Gin web framework.

Inspired by the Sanskrit word Pariksha (परीक्षा), meaning "test" or "examination", this framework is built to help developers write cleaner, faster, and more structured test code with minimal boilerplate.


✨ Features

  • ✅ Declarative API test case structure
  • 🔁 Reusable setup for HTTP requests and contexts
  • 🧪 Native support for *testing.T and *testing.B
  • ⚙️ Built-in integration with httptest and gin.Context
  • 🚀 Designed for speed, clarity, and code reuse

📦 Installation

go get github.com/DevNavix/go-pariksha

Documentation

Index

Constants

View Source
const (
	LogResponse = false // To print api response we should enable this flag
)

Variables

View Source
var (
	// Add common contexts required in api testing.
	CommonContext = map[string]any{
		"user_name": "Navjot sharma",
	}
	// Add common headers required in api test cases.
	CommonHeaders = map[string]string{
		"Content-Type": "application/json",
	}

	// Formats in which profiling results will be saved.
	// Options: "png", "pdf". Add both to enable both outputs.
	ProfilingOutputFormats = []string{"png"} //ex: []string{"png"} or []string{"pdf"} or []string{"png", "pdf"}
)
View Source
var EnabledProfilingTypes = []string{}

Uncomment the profiling types you want to enable and pass them to the profiling setup function in your application. Ensure that the profiling library you are using supports the selected types.

Functions

func BenchmarkExample

func BenchmarkExample(b *testing.B)

-------------- Example usage of RunBenchmark Or profiling ----------

func GenerateGraph

func GenerateGraph(profilePath, outputPath, format string)

GenerateGraph uses the Go pprof tool to generate a visualization of the profiling data. It takes the path to a .prof file, the desired output path, and the output format ("png" or "pdf").

func GetBsonIdFromUUId

func GetBsonIdFromUUId(uuidStr string) (binData string)

GetBsonIdFromUUId converts a UUID string into a MongoDB BinData representation. The function removes dashes from the UUID string, decodes it into bytes, encodes the bytes into a Base64 string, and formats it as a BinData string.

  • uuidStr: A string representing the UUID in standard format (e.g., "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
  • binData: A string formatted as "BinData(0, '<Base64EncodedBytes>')", or an empty string if an error occurs during decoding.

func GetStringUUidFromBsonId

func GetStringUUidFromBsonId(binData string) (uuidStr string, err error)

To converts a MongoDB BinData representation back into a UUID string format. The function decodes the Base64-encoded bytes from the BinData string and formats them as a UUID string.

  • binData: A string formatted as "BinData(0, '<Base64EncodedBytes>')".
  • uuidStr: A string representing the UUID in standard format (e.g., "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"), or an empty string if an error occurs.

func MakeDirIfNotExists

func MakeDirIfNotExists(path string)

To make a new directory, if directory not exists in the path.

func RunAPITest

func RunAPITest(tests []APITestCase)

RunAPITest is a helper function to execute a series of API test cases. It iterates over a slice of APITestCase and runs each test case using the provided testing framework.

  • tests: A slice of APITestCase, where each test case contains the logic and metadata for an individual API test.

Each test case is executed in its own subtest, identified by the Name field of the APITestCase. The RunSingle method of each test case is invoked to perform the actual test logic.

func TestExampleAPI

func TestExampleAPI(t *testing.T)

-------------- Example usage of RunAPITest ----------

func WriteProfileAndExport

func WriteProfileAndExport(profileType, dir string)

WriteProfileAndExport captures a runtime profile (like "heap", "goroutine", etc.) writes it to a temporary .prof file, and generates output files (e.g., PNG or PDF)

Types

type APITestCase

type APITestCase struct {
	Name         string
	Method       string
	URL          string
	HandlerFunc  gin.HandlerFunc
	RequestBody  string
	PathParams   map[string]string
	Headers      map[string]string
	ExpectedCode int
	ContextKeys  map[string]any
	T            *testing.T
	B            *testing.B
	FunctionName string
}

func (*APITestCase) DefAPITestFields

func (test *APITestCase) DefAPITestFields()

Initializes APITestCase with fields common to all test cases.

func (*APITestCase) ExecuteHandler

func (tc *APITestCase) ExecuteHandler() *httptest.ResponseRecorder

To sets up the Gin test context, builds the HTTP request from the APITestCase fields, executes the handler function, and returns the response recorder. This is used for testing or benchmarking HTTP handler behavior.

func (APITestCase) GetProfileDir

func (tc APITestCase) GetProfileDir() (profileDir string)

GetProfileDir returns the directory path where profiling files should be stored

func (*APITestCase) RunBenchmark

func (tc *APITestCase) RunBenchmark()

To executes a benchmark test for the API test case. It marks the function as a helper for better error reporting and runs the benchmark using the testing.B framework. The benchmark repeatedly calls the ExecuteHandler method for the number of iterations specified by the testing.B instance.

This method is designed to be used in conjunction with the Go testing package's benchmarking tools.

func (APITestCase) RunSingle

func (tc APITestCase) RunSingle()

RunSingle executes a single API test case by simulating an HTTP request and validating the response against expected values.

func (APITestCase) RunWithProfiling

func (tc APITestCase) RunWithProfiling()

RunWithProfiling executes the API test case with profiling enabled. This method is useful for analyzing the performance of the test case by collecting profiling data during its execution.

func (APITestCase) SetAPITestPathParams

func (tc APITestCase) SetAPITestPathParams() (params gin.Params)

If your Endpoint includes a path parameter, e.g., "/users/123", and your handler expects it as "/users/:id", you must set it manually.

type RespController

type RespController struct {
	Code      int    `json:"code"`
	ApiStatus int    `json:"api_status"`
	Message   string `json:"message"`
	Data      any    `json:"data,omitempty"`
	MetaData  any    `json:"meta_data,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL