apirunner

package module
v0.0.0-...-368a3f2 Latest Latest
Warning

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

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

README

API Runner

Go Report Card

A lightweight test runner for testing http APIs. Define test cases as json and execute them against any server (local or over the network).

Written in Go. Built by the Warrant team.

Usage

Install
go get github.com/thirdmasonry/apirunner
Define API tests as json

Sample test file:

{
    "ignoredFields": [
        "internalId"
    ],
    "tests": [
        {
            "name": "createUser",
            "request": {
                "method": "POST",
                "url": "/users",
                "body": {
                    "email": "someemail@gmail.com"
                }
            },
            "expectedResponse": {
                "statusCode": 200,
                "body": {
                    "userId": "{{ createUser.userId }}",
                    "email": "someemail@gmail.com"
                }
            }
        },
        {
            "name": "getUserById",
            "request": {
                "method": "GET",
                "url": "/users/{{ createUser.userId }}"
            },
            "expectedResponse": {
                "statusCode": 200,
                "body": {
                    "userId": "{{ createUser.userId }}",
                    "email": "someemail@gmail.com"
                }
            }
        },
        {
            "name": "deleteUser",
            "request": {
                "method": "DELETE",
                "url": "/users/{{ createUser.userId }}"
            },
            "expectedResponse": {
                "statusCode": 200
            }
        }
    ]
}
Execute tests
import (
	"github.com/thirdmasonry/apirunner"
)

// Execute all tests in 'mytestfile.json' and print results
func main() {
    runner, err := apirunner.NewRunner(apirunner.Config{
        TestFileName:  "mytestfile.json",
        BaseUrl:       "http://localhost:8000",
        CustomHeaders: nil,
    })
    if err != nil {
        panic(err)
    }
    runner.Execute()
}

Features

  • Supports all HTTP operations (GET, POST, PUT, DELETE etc.)
  • Deep comparison of json responses (objects and arrays)
  • Inject custom headers via config (useful for passing auth tokens)
  • ignoredFields to ignore specific attributes during comparison (ex. non-deterministic ids, timestamps)
  • Memoization of response attributes to support request chaining. For example, this test references an id of a resource created by a previous request:
{
    "name": "updateResourceTest",
    "request": {
        "method": "PUT",
        "url": "/resources/{{ createResourceTest.Id }}",
        "body": {
            "email": "someupdatedemail@gmail.com"
        }
    },
    "expectedResponse": {
        "statusCode": 200,
        "body": {
            "id": "{{ createResourceTest.Id }}",
            "email": "someupdatedemail@gmail.com"
        }
    }
}

Development

PRs welcome! Clone and develop locally:

git clone git@github.com:warrant-dev/apirunner.git
cd apirunner
go test

About Warrant

Warrant provides APIs and infrastructure for implementing authorization and access control.

Documentation

Index

Constants

View Source
const (
	SkippedString = "\033[1;33mSKIPPED (%s)\033[0m"
	PassedString  = "\033[1;32mPASSED (%s)\033[0m"
	FailedString  = "\033[1;31mFAILED (%s)\033[0m"
	ErrorString   = "\033[1;31m%s\033[0m"
)

Variables

This section is empty.

Functions

func Run

func Run(runConfigFilename string, testDir string, testFilenameMatchRegex *regexp.Regexp) (bool, error)

Run executes all test files in 'testDir'. Returns true if all tests pass, false otherwise (including on err)

Types

type ExpectedResponse

type ExpectedResponse struct {
	StatusCode int               `json:"statusCode"`
	Body       interface{}       `json:"body"`
	Headers    map[string]string `json:"headers"`
}

Expected test case response

type HttpClient

type HttpClient interface {
	Do(req *http.Request) (*http.Response, error)
}

Mock-able HttpClient interface

type Request

type Request struct {
	Method  string            `json:"method"`
	BaseUrl string            `json:"baseUrl"`
	Url     string            `json:"url"`
	Body    interface{}       `json:"body"`
	Headers map[string]string `json:"headers"`
}

Request information for a single test case

type RunConfig

type RunConfig struct {
	BaseUrl       string            `json:"baseUrl"`
	CustomHeaders map[string]string `json:"headers"`
	HttpClient    HttpClient
}

type TestResult

type TestResult struct {
	Passed   bool
	Skipped  bool
	Name     string
	Errors   []string
	Duration time.Duration
}

Result for an executed test case

func Failed

func Failed(name string, errors []string, duration time.Duration) TestResult

func Passed

func Passed(name string, duration time.Duration) TestResult

func Skipped

func Skipped(name string) TestResult

func (TestResult) Result

func (result TestResult) Result() string

func (TestResult) ResultNoDetail

func (result TestResult) ResultNoDetail() string

type TestSpec

type TestSpec struct {
	Name             string           `json:"name"`
	Skip             bool             `json:"skip"`
	Request          Request          `json:"request"`
	ExpectedResponse ExpectedResponse `json:"expectedResponse"`
}

Spec defining a single test case

type TestSuite

type TestSuite struct {
	// contains filtered or unexported fields
}

A collection of tests defined within one test file

type TestSuiteResult

type TestSuiteResult struct {
	Passed       []TestResult
	Failed       []TestResult
	Skipped      []TestResult
	TestFilename string
	TotalTests   int
}

Results for an executed TestSuite

func ExecuteSuite

func ExecuteSuite(runConfig RunConfig, testFilename string, logFailureDetails bool) (TestSuiteResult, error)

ExecuteSuite executes a test suite and prints + returns the results

type TestSuiteSpec

type TestSuiteSpec struct {
	Skip          bool       `json:"skip"`
	IgnoredFields []string   `json:"ignoredFields"`
	BaseUrl       string     `json:"baseUrl"`
	Tests         []TestSpec `json:"tests"`
}

Spec defining the tests in a suite

Directories

Path Synopsis
cmd
apirunner command

Jump to

Keyboard shortcuts

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