├── loader ├── testdata │ ├── textfile │ └── suite1.json ├── jsonloader.go └── jsonloader_test.go ├── go.mod ├── go.sum ├── version ├── version.go └── version_test.go ├── .travis.yml ├── .gitignore ├── Dockerfile ├── runner ├── internal │ └── report │ │ ├── report.go │ │ └── report_test.go ├── runner.go └── runner_test.go ├── scripts └── changelog ├── .github └── workflows │ ├── releaser.yml │ └── go.yml ├── examples └── example-smoketestsuite.json ├── .goreleaser.yaml ├── Makefile ├── core └── contracts.go ├── cmd └── smoker │ └── smoker.go ├── cmdoptions ├── options.go └── options_test.go ├── requester ├── requester.go └── requester_test.go ├── README.md └── LICENSE /loader/testdata/textfile: -------------------------------------------------------------------------------- 1 | hello 2 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/amad/smoker 2 | 3 | go 1.13 4 | 5 | require github.com/google/uuid v1.1.1 6 | -------------------------------------------------------------------------------- /loader/testdata/suite1.json: -------------------------------------------------------------------------------- 1 | { 2 | "tests": [ 3 | { 4 | "name": "test case 1", 5 | "url": "https://github.com/amad/smoker" 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= 2 | github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 3 | -------------------------------------------------------------------------------- /version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | // Version represents the build version. 4 | var version = "0.0.0" 5 | 6 | // String returns the complete version string. 7 | func String() string { 8 | return version 9 | } 10 | -------------------------------------------------------------------------------- /version/version_test.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestString(t *testing.T) { 8 | if String() != version { 9 | t.Fatalf("Version.String() invalid format\nexpected: %s\nreceived: %s", version, String()) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 3 | - "1.13" 4 | 5 | before_install: 6 | - go get -t -v ./... 7 | 8 | script: 9 | - go vet ./... 10 | - go test -race -v -coverprofile=coverage.txt -covermode=atomic ./... 11 | 12 | after_success: 13 | - bash <(curl -s https://codecov.io/bash) 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | vendor/ 16 | 17 | bin/ 18 | dist/ 19 | /CHANGELOG.md 20 | -------------------------------------------------------------------------------- /loader/jsonloader.go: -------------------------------------------------------------------------------- 1 | package loader 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | 8 | "github.com/amad/smoker/core" 9 | ) 10 | 11 | // LoadTestsuite loads testsuite from a JSON file. 12 | func LoadTestsuite(filename string) (*core.Testsuite, error) { 13 | var testsuite core.Testsuite 14 | 15 | contents, err := ioutil.ReadFile(filename) 16 | if err != nil { 17 | return &testsuite, fmt.Errorf("unable to open config file: %w", err) 18 | } 19 | 20 | err = json.Unmarshal(contents, &testsuite) 21 | if err != nil { 22 | return &testsuite, fmt.Errorf("unable to parse config file: %w", err) 23 | } 24 | 25 | return &testsuite, nil 26 | } 27 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.14-alpine as go-builder 2 | 3 | LABEL maintainer="Ahmad Samiei" 4 | 5 | ENV GOPATH /go 6 | ENV CGO_ENABLED 0 7 | ENV GO111MODULE on 8 | ENV GOPROXY https://proxy.golang.org 9 | 10 | RUN \ 11 | apk add --no-cache git && \ 12 | git clone https://github.com/amad/smoker && cd smoker && \ 13 | go install -v -ldflags "-s -w -X github.com/amad/smoker/version.version=$(git describe --abbrev=0)" ./cmd/smoker 14 | 15 | FROM alpine:3.10 16 | 17 | COPY --from=go-builder /go/bin/smoker /usr/bin/smoker 18 | 19 | RUN \ 20 | chmod +x /usr/bin/smoker 21 | 22 | VOLUME ["/data"] 23 | 24 | ENTRYPOINT ["/usr/bin/smoker"] 25 | 26 | CMD ["/usr/bin/smoker"] 27 | -------------------------------------------------------------------------------- /runner/internal/report/report.go: -------------------------------------------------------------------------------- 1 | package report 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | // The TestReport holds results of a test case. 9 | type TestReport struct { 10 | Index int 11 | Name string 12 | Status bool 13 | Err error 14 | Duration time.Duration 15 | } 16 | 17 | // String method returns the test result as string. 18 | func (r *TestReport) String() string { 19 | if !r.Passed() { 20 | return fmt.Sprintf("FAIL: testcase #%d \"%s\" %s (%.2fs)", r.Index, r.Name, r.Err, r.Duration.Seconds()) 21 | } 22 | 23 | return fmt.Sprintf("PASS: testcase #%d \"%s\" (%.2fs)", r.Index, r.Name, r.Duration.Seconds()) 24 | } 25 | 26 | // Passed method checks if test result was successful. 27 | func (r *TestReport) Passed() bool { 28 | return r.Status 29 | } 30 | -------------------------------------------------------------------------------- /scripts/changelog: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | current_tag="${GITHUB_REF#refs/tags/}" 5 | start_ref="HEAD" 6 | 7 | # Find the previous release on the same branch, skipping prereleases if the 8 | # current tag is a full release 9 | previous_tag="" 10 | while [[ -z $previous_tag || ( $previous_tag == *-* && $current_tag != *-* ) ]]; do 11 | previous_tag="$(git describe --tags "$start_ref"^ --abbrev=0)" 12 | start_ref="$previous_tag" 13 | done 14 | 15 | git log "$previous_tag".. --reverse --merges --oneline --grep='Merge pull request #' | \ 16 | while read -r sha title; do 17 | pr_num="$(grep -o '#[[:digit:]]\+' <<<"$title")" 18 | pr_desc="$(git show -s --format=%b "$sha" | sed -n '1,/^$/p' | tr $'\n' ' ')" 19 | printf "* %s %s\n\n" "$pr_desc" "$pr_num" 20 | done 21 | -------------------------------------------------------------------------------- /.github/workflows/releaser.yml: -------------------------------------------------------------------------------- 1 | name: goreleaser 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | 8 | jobs: 9 | goreleaser: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v2 14 | - name: Set up Go 15 | uses: actions/setup-go@v1 16 | with: 17 | go-version: 1.13.x 18 | - name: Generate changelog 19 | run: | 20 | git fetch --unshallow 21 | scripts/changelog | tee CHANGELOG.md 22 | - name: Run GoReleaser 23 | uses: goreleaser/goreleaser-action@v1 24 | with: 25 | version: latest 26 | args: release --rm-dist --release-notes=CHANGELOG.md 27 | key: ${{ secrets.YOUR_PRIVATE_KEY }} 28 | env: 29 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 30 | -------------------------------------------------------------------------------- /examples/example-smoketestsuite.json: -------------------------------------------------------------------------------- 1 | { 2 | "tests": [ 3 | { 4 | "name": "Github.com is live", 5 | "url": "https://github.com" 6 | }, 7 | { 8 | "name": "Github.com about shows copyright notice", 9 | "url": "https://github.com/about", 10 | "assertions": { 11 | "body": [ 12 | "© [0-9]{4} GitHub, Inc\\." 13 | ] 14 | } 15 | }, 16 | { 17 | "name": "Github repos API does not accept POST request", 18 | "url": "https://api.github.com/repos/amad/smoker", 19 | "method": "post", 20 | "headers": { 21 | "Accept": "application/json" 22 | }, 23 | "assertions": { 24 | "statusCode": 404 25 | } 26 | }, 27 | { 28 | "name": "Github fetch user. This fails without valid token", 29 | "url": "https://api.github.com/user", 30 | "method": "post", 31 | "headers": { 32 | "Authorization": "token GITHUB_TOKEN_PLACEHOLDER" 33 | } 34 | } 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /.goreleaser.yaml: -------------------------------------------------------------------------------- 1 | project_name: smoker 2 | 3 | before: 4 | hooks: 5 | - go mod tidy 6 | - go mod download 7 | 8 | release: 9 | github: 10 | owner: amad 11 | name: smoker 12 | prerelease: auto 13 | 14 | builds: 15 | - <<: &build_defaults 16 | binary: smoker 17 | main: ./cmd/smoker/smoker.go 18 | ldflags: 19 | - -s -w -X github.com/amad/smoker/version.version={{ .Tag }} 20 | id: macos 21 | goos: [darwin] 22 | goarch: [amd64] 23 | - <<: *build_defaults 24 | id: linux 25 | goos: [linux] 26 | goarch: [386, amd64, arm64] 27 | 28 | archives: 29 | - id: nix 30 | builds: [macos, linux] 31 | <<: &archive_defaults 32 | name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" 33 | wrap_in_directory: true 34 | replacements: 35 | darwin: macOS 36 | format: tar.gz 37 | 38 | changelog: 39 | sort: asc 40 | filters: 41 | exclude: 42 | - '^docs:' 43 | - '^test:' 44 | - '^build:' 45 | -------------------------------------------------------------------------------- /runner/internal/report/report_test.go: -------------------------------------------------------------------------------- 1 | package report_test 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | "time" 7 | 8 | "github.com/amad/smoker/runner/internal/report" 9 | ) 10 | 11 | func TestReport(t *testing.T) { 12 | t.Parallel() 13 | 14 | tt := []struct { 15 | name string 16 | report *report.TestReport 17 | expectedStatus bool 18 | expectedString string 19 | }{ 20 | {"passed", &report.TestReport{1, "a", true, nil, time.Duration(1) * time.Second}, true, "PASS: testcase #1 \"a\" (1.00s)"}, 21 | {"failed", &report.TestReport{2, "b", false, errors.New("reason"), time.Duration(2) * time.Second}, false, "FAIL: testcase #2 \"b\" reason (2.00s)"}, 22 | } 23 | 24 | for _, tc := range tt { 25 | t.Run(tc.name, func(t *testing.T) { 26 | if tc.report.Passed() != tc.expectedStatus { 27 | t.Fatalf("Status does not match\nexpected: %t\nreceived: %t", tc.expectedStatus, tc.report.Passed()) 28 | } 29 | 30 | if tc.expectedString != tc.report.String() { 31 | t.Fatalf("Report string does not match\nexpected: %s\nreceived: %s", tc.expectedString, tc.report.String()) 32 | } 33 | }) 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | BUILD_NUMBER=$(shell git rev-parse --short HEAD) 2 | 3 | setup: 4 | go mod download 5 | docker pull golangci/golangci-lint:latest-alpine 6 | .PHONY: setup 7 | 8 | build: 9 | go build -v -o smoker ./cmd/smoker 10 | .PHONY: build 11 | 12 | clean: 13 | rm -f smoker 14 | rm -f bin/smoker* 15 | rm -f dist/smoker* 16 | mkdir -p bin 17 | mkdir -p dist 18 | .PHONY: clean 19 | 20 | lint: 21 | go vet ./... 22 | staticcheck ./... 23 | docker run --rm -v ${PWD}:/app -w /app golangci/golangci-lint:latest-alpine golangci-lint run 24 | .PHONY: lint 25 | 26 | test: 27 | go test -race -v -covermode=atomic ./... 28 | .PHONY: test 29 | 30 | coverage: 31 | go test -race -v -coverprofile=coverage.txt -covermode=atomic ./... 32 | go tool cover -html=coverage.txt 33 | .PHONY: coverage 34 | 35 | release: clean 36 | GOOS=darwin GOARCH=amd64 go build -o "bin/smoker_darwin_amd64" ./cmd/smoker 37 | GOOS=darwin GOARCH=386 go build -o "bin/smoker_darwin_386" ./cmd/smoker 38 | GOOS=linux GOARCH=amd64 go build -o "bin/smoker_linux_amd64" ./cmd/smoker 39 | GOOS=linux GOARCH=386 go build -o "bin/smoker_linux_386" ./cmd/smoker 40 | tar -zvcf dist/smoker-$(BUILD_NUMBER).tar.gz bin/smoker* 41 | .PHONY: release 42 | 43 | dockerbuild: 44 | docker build --tag smoker:$(git describe --abbrev=0) . 45 | .PHONY: dockerbuild 46 | -------------------------------------------------------------------------------- /core/contracts.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | // Runner defines interface of a test runner. 4 | type Runner interface { 5 | Run(requester Requester, testsuite *Testsuite) (noFailure bool, err error) 6 | Stop() 7 | } 8 | 9 | // Requester defines interface of testcase handler. 10 | type Requester interface { 11 | Request(tc TestCase) (bool, error) 12 | } 13 | 14 | // TestResult defines interface to check if test has passed and 15 | // to get string report. 16 | type TestResult interface { 17 | Passed() bool 18 | String() string 19 | } 20 | 21 | // Testsuite hold all fields realted to testsuite and all testcases. 22 | type Testsuite struct { 23 | Tests []TestCase `json:"tests"` 24 | } 25 | 26 | // TestCase specifies one test case. 27 | type TestCase struct { 28 | Name string `json:"name"` 29 | URL string `json:"url"` 30 | Method string `json:"method"` 31 | Headers map[string]string `json:"headers"` 32 | Body string `json:"body"` 33 | Assertions Assertions `json:"assertions"` 34 | } 35 | 36 | // Assertions describes expectations on each test case. 37 | type Assertions struct { 38 | StatusCode int `json:"statusCode"` 39 | Body []string `json:"body"` 40 | Headers map[string]string `json:"headers"` 41 | } 42 | -------------------------------------------------------------------------------- /cmd/smoker/smoker.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "os" 7 | "os/signal" 8 | "syscall" 9 | 10 | "github.com/amad/smoker/cmdoptions" 11 | "github.com/amad/smoker/loader" 12 | "github.com/amad/smoker/requester" 13 | "github.com/amad/smoker/runner" 14 | "github.com/amad/smoker/version" 15 | ) 16 | 17 | func main() { 18 | var err error 19 | 20 | flags, err := cmdoptions.InstallFlags(version.String(), os.Stdout) 21 | exitIfError(err) 22 | 23 | testsuite, err := loader.LoadTestsuite(flags.TestsuiteFile) 24 | exitIfError(err) 25 | 26 | runner := runner.NewRunner(flags.Workers, flags.Timeout, flags.StopOnFailure, os.Stdout, os.Stderr) 27 | requester := requester.NewRequester(flags.Timeout, fmt.Sprintf("smoker/%s", version.String())) 28 | 29 | sigsChan := make(chan os.Signal) 30 | signal.Notify(sigsChan, syscall.SIGINT, syscall.SIGTERM) 31 | go func() { 32 | <-sigsChan 33 | 34 | runner.Stop() 35 | 36 | exitWithError(errors.New("Interrupted")) 37 | }() 38 | 39 | ok, err := runner.Run(requester, testsuite) 40 | exitIfError(err) 41 | 42 | fmt.Println("Done") 43 | 44 | if !ok { 45 | os.Exit(1) 46 | } 47 | } 48 | 49 | func exitIfError(err error) { 50 | if err == nil { 51 | return 52 | } 53 | 54 | exitWithError(err) 55 | } 56 | 57 | func exitWithError(e error) { 58 | os.Stderr.WriteString(fmt.Sprintf("ERROR: %s\n", e.Error())) 59 | os.Exit(1) 60 | } 61 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | 2 | name: Tests 3 | on: [push, pull_request] 4 | jobs: 5 | build: 6 | strategy: 7 | fail-fast: false 8 | matrix: 9 | go-version: [1.13.x] 10 | os: [ubuntu-latest] 11 | runs-on: ${{ matrix.os }} 12 | 13 | steps: 14 | - name: Set up Go 15 | uses: actions/setup-go@v1 16 | with: 17 | go-version: ${{ matrix.go-version }} 18 | 19 | - name: Checkout code 20 | uses: actions/checkout@v2 21 | 22 | - name: Verify dependencies 23 | run: go mod verify 24 | 25 | - name: nancy 26 | uses: sonatype-nexus-community/nancy-github-action@master 27 | with: 28 | target: go.sum 29 | 30 | - name: Lint 31 | run: go vet ./... 32 | 33 | - name: golangci-lint 34 | env: 35 | GOROOT: /go 36 | run: | 37 | docker pull golangci/golangci-lint:latest-alpine 38 | docker run --rm -v ${PWD}:/app -w /app golangci/golangci-lint:latest-alpine golangci-lint run 39 | 40 | - name: Tests 41 | run: go test -race -cover -coverprofile=coverage.txt -covermode=atomic -cpu 1,2 -bench . -benchmem ./... > test.log 42 | 43 | - name: Show log 44 | if: always() 45 | run: cat test.log 46 | 47 | - name: Codecov 48 | uses: codecov/codecov-action@v1 49 | with: 50 | token: ${{ secrets.CODECOV_TOKEN }} 51 | file: ./coverage.txt 52 | yml: ./.codecov.yml 53 | 54 | - name: Build 55 | run: go build -v -o smoker ./cmd/smoker 56 | -------------------------------------------------------------------------------- /loader/jsonloader_test.go: -------------------------------------------------------------------------------- 1 | package loader_test 2 | 3 | import ( 4 | "reflect" 5 | "strings" 6 | "testing" 7 | 8 | "github.com/amad/smoker/core" 9 | "github.com/amad/smoker/loader" 10 | ) 11 | 12 | // LoadTestsuite loads testsuite from a JSON file 13 | func TestLoadTestsuite(t *testing.T) { 14 | t.Parallel() 15 | 16 | tt := []struct { 17 | name string 18 | filename string 19 | expectRes *core.Testsuite 20 | expectErr string 21 | }{ 22 | {"load a testsuite", "./testdata/suite1.json", &core.Testsuite{Tests: []core.TestCase{{Name: "test case 1", URL: "https://github.com/amad/smoker"}}}, ""}, 23 | {"should error on invalid file type", "./testdata/textfile", &core.Testsuite{}, "unable to parse config file"}, 24 | {"should error on wrong path", "./testdata/notfound.json", &core.Testsuite{}, "unable to open config file"}, 25 | } 26 | 27 | for _, tc := range tt { 28 | t.Run(tc.name, func(t *testing.T) { 29 | res, err := loader.LoadTestsuite(tc.filename) 30 | 31 | if err != nil { 32 | if tc.expectErr == "" { 33 | t.Fatalf("Unexpected error\nexpected: \nreceived: %s", err.Error()) 34 | } 35 | 36 | if ok := strings.Contains(err.Error(), tc.expectErr); !ok { 37 | t.Fatalf("Expected error does not match\nexpected: %s\nreceived: %s", tc.expectErr, err.Error()) 38 | } 39 | 40 | return 41 | } 42 | 43 | if tc.expectErr != "" { 44 | t.Fatalf("Expected to throw error\nexpected: %s\nreceived: ", tc.expectErr) 45 | } 46 | 47 | if !reflect.DeepEqual(tc.expectRes, res) { 48 | t.Fatalf("Response does not match\nexpected: %+v\nreceived: %+v", *tc.expectRes, *res) 49 | } 50 | }) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /cmdoptions/options.go: -------------------------------------------------------------------------------- 1 | package cmdoptions 2 | 3 | import ( 4 | "errors" 5 | "flag" 6 | "io" 7 | "os" 8 | "time" 9 | ) 10 | 11 | // InputOptions holds input arguments. 12 | type InputOptions struct { 13 | // TestsuiteFile is path of the testsuite JSON file. 14 | TestsuiteFile string 15 | // Workers represents number of concurrent workers. 16 | Workers int 17 | // Timeout is the maximum duration for each HTTP request. 18 | Timeout time.Duration 19 | // StopOnFailure force exits on first error or failure. 20 | StopOnFailure bool 21 | } 22 | 23 | var usage = ` 24 | Usage: smoker [options...] 25 | 26 | Example: 27 | smoker -testsuite smoketestsuite-api.json 28 | smoker -testsuite smoketestsuite-web.json -workers 4 -timeout 5 -stop-on-failure 29 | 30 | Options: 31 | -testsuite Testsuite file in JSON format to read test cases. 32 | -workers Number of workers to send requests concurrently. (accepts integer value >= 1. Default is 1. 0 is not allowed) 33 | -timeout Set timeout per request in seconds. (accepts integer value >= 1. Default is 10. 0 is not allowed) 34 | -stop-on-failure Stop execution upon first error or failure. 35 | -version Prints the version and exits. 36 | 37 | Visit: https://github.com/amad/smoker 38 | ` 39 | 40 | var versionFlag bool 41 | 42 | // InstallFlags adds CLI flags and validates user input. 43 | func InstallFlags(version string, stdout io.StringWriter) (*InputOptions, error) { 44 | var flags InputOptions 45 | 46 | addOptions(&flags, stdout) 47 | 48 | if versionFlag { 49 | stdout.WriteString(version + "\n") 50 | os.Exit(0) 51 | } 52 | 53 | if flags.TestsuiteFile == "" { 54 | return &flags, errors.New("-testsuite is required") 55 | } 56 | 57 | if flags.Workers < 1 { 58 | return &flags, errors.New("-workers only accept a number >= 1") 59 | } 60 | 61 | if flags.Timeout < 1 { 62 | return &flags, errors.New("-timeout only accept a number >= 1") 63 | } 64 | 65 | return &flags, nil 66 | } 67 | 68 | func addOptions(flags *InputOptions, stdout io.StringWriter) { 69 | var timeout int 70 | 71 | flag.IntVar(&flags.Workers, "workers", 1, "") 72 | flag.IntVar(&timeout, "timeout", 10, "") 73 | flag.BoolVar(&versionFlag, "version", false, "") 74 | flag.StringVar(&flags.TestsuiteFile, "testsuite", "", "") 75 | flag.BoolVar(&flags.StopOnFailure, "stop-on-failure", false, "") 76 | 77 | flag.Usage = func() { 78 | stdout.WriteString(usage) 79 | os.Exit(0) 80 | } 81 | 82 | flag.Parse() 83 | 84 | flags.Timeout = time.Duration(timeout) * time.Second 85 | } 86 | -------------------------------------------------------------------------------- /cmdoptions/options_test.go: -------------------------------------------------------------------------------- 1 | package cmdoptions 2 | 3 | import ( 4 | "bytes" 5 | "flag" 6 | "os" 7 | "os/exec" 8 | "strings" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | func TestInstallFlags(t *testing.T) { 14 | t.Parallel() 15 | 16 | tt := []struct { 17 | name string 18 | args []string 19 | options *InputOptions 20 | expectErr string 21 | }{ 22 | {"flagset1", []string{"app", "-testsuite", "test"}, &InputOptions{"test", 1, time.Duration(10) * time.Second, false}, ""}, 23 | {"flagset2", []string{"app", "-testsuite", "test", "-workers", "2", "-timeout", "5", "-stop-on-failure"}, &InputOptions{"test", 2, time.Duration(5) * time.Second, true}, ""}, 24 | {"no_args", []string{"app", ""}, nil, "-testsuite is required"}, 25 | {"no_testsuite", []string{"app", "-stop-on-failure", "0"}, nil, "-testsuite is required"}, 26 | {"invalid_workers", []string{"app", "-workers", "0", "-testsuite", "test"}, nil, "-workers only accept a number >= 1"}, 27 | {"invalid_timeout", []string{"app", "-timeout", "0", "-testsuite", "test"}, nil, "-timeout only accept a number >= 1"}, 28 | } 29 | 30 | for _, tc := range tt { 31 | t.Run(tc.name, func(t *testing.T) { 32 | flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError) 33 | 34 | var buffer bytes.Buffer 35 | 36 | originalArgs := os.Args 37 | 38 | os.Args = tc.args 39 | options, err := InstallFlags("version", &buffer) 40 | 41 | os.Args = originalArgs 42 | 43 | if err != nil { 44 | if tc.expectErr == "" { 45 | t.Fatalf("Unexpected error\nexpected: \nreceived: %s", err.Error()) 46 | } 47 | 48 | if tc.expectErr != err.Error() { 49 | t.Fatalf("Expected error does not match\nexpected: %s\nreceived: %s", tc.expectErr, err.Error()) 50 | } 51 | 52 | return 53 | } 54 | 55 | if tc.expectErr != "" { 56 | t.Fatalf("Expected to throw error\nexpected: %s\nreceived: ", tc.expectErr) 57 | } 58 | 59 | if tc.options != nil { 60 | if *tc.options != *options { 61 | t.Fatalf("Options do not match\nexpected: %+v\nreceived: %+v", tc.options, options) 62 | } 63 | } 64 | }) 65 | } 66 | } 67 | 68 | func TestOutput(t *testing.T) { 69 | tt := []struct { 70 | name string 71 | args []string 72 | expectedOutputContain string 73 | }{ 74 | {"version_flag", []string{"app", "-version"}, "version"}, 75 | {"help_flag", []string{"app", "-help"}, "Usage"}, 76 | } 77 | 78 | for _, tc := range tt { 79 | t.Run(tc.name, func(t *testing.T) { 80 | flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError) 81 | 82 | if os.Getenv("EXIT_TEST") == "1" { 83 | oldArgs := os.Args 84 | os.Args = tc.args 85 | 86 | _, _ = InstallFlags("version", os.Stdout) 87 | 88 | os.Args = oldArgs 89 | 90 | return 91 | } 92 | 93 | cmd := exec.Command(os.Args[0], "-test.run=TestOutput/"+tc.name) 94 | cmd.Env = append(os.Environ(), "EXIT_TEST=1") 95 | output, _ := cmd.CombinedOutput() 96 | 97 | if e := strings.Contains(string(output[:]), tc.expectedOutputContain); !e { 98 | t.Fatalf("Output does not contain: %s\nreceived: %s", tc.expectedOutputContain, string(output[:])) 99 | } 100 | }) 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /requester/requester.go: -------------------------------------------------------------------------------- 1 | package requester 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "net/http" 9 | "net/textproto" 10 | "regexp" 11 | "strings" 12 | "time" 13 | 14 | "github.com/amad/smoker/core" 15 | "github.com/google/uuid" 16 | ) 17 | 18 | // NewRequester creates and returns new a Requester. 19 | func NewRequester(timeout time.Duration, userAgent string) *Requester { 20 | client := &http.Client{ 21 | Timeout: timeout, 22 | } 23 | 24 | return &Requester{ 25 | client: client, 26 | userAgent: userAgent, 27 | } 28 | } 29 | 30 | // Requester handles HTTP requests. 31 | type Requester struct { 32 | client *http.Client 33 | userAgent string 34 | } 35 | 36 | // Request method uses HTTP package to send request and verifies if the 37 | // response matches test case expectations. 38 | func (r *Requester) Request(tc core.TestCase) (bool, error) { 39 | if tc.Name == "" { 40 | return false, errors.New("does not have name field") 41 | } 42 | 43 | if tc.URL == "" { 44 | return false, errors.New("does not have url field") 45 | } 46 | 47 | if tc.Method != "" { 48 | tc.Method = strings.ToUpper(tc.Method) 49 | } else { 50 | tc.Method = http.MethodGet 51 | } 52 | 53 | if tc.Assertions.StatusCode == 0 { 54 | tc.Assertions.StatusCode = http.StatusOK 55 | } 56 | 57 | req, err := http.NewRequest(tc.Method, tc.URL, nil) 58 | if err != nil { 59 | return false, fmt.Errorf("could not create request: %w", err) 60 | } 61 | 62 | id := uuid.New().String() 63 | req.Header.Set("Request-Id", id) 64 | req.Header.Set("User-Agent", r.userAgent) 65 | 66 | for name, value := range tc.Headers { 67 | req.Header.Set(name, value) 68 | } 69 | 70 | if tc.Body != "" { 71 | req.Body = ioutil.NopCloser(bytes.NewReader([]byte(tc.Body))) 72 | } 73 | 74 | res, err := r.client.Do(req) 75 | if err != nil { 76 | return false, fmt.Errorf("request failed: %w", err) 77 | } 78 | defer res.Body.Close() 79 | 80 | if res.StatusCode != tc.Assertions.StatusCode { 81 | return false, fmt.Errorf("expected status-code: %d received: %d", tc.Assertions.StatusCode, res.StatusCode) 82 | } 83 | 84 | if len(tc.Assertions.Body) != 0 { 85 | body, err := ioutil.ReadAll(res.Body) 86 | if err != nil { 87 | return false, fmt.Errorf("unable to read the response body with with error: %w", err) 88 | } 89 | 90 | bodyStr := string(body) 91 | 92 | for _, matchInBody := range tc.Assertions.Body { 93 | res, err := regexp.MatchString(matchInBody, bodyStr) 94 | if err != nil || !res { 95 | return false, fmt.Errorf("can not match /%s/ in response body", matchInBody) 96 | } 97 | } 98 | } 99 | 100 | if len(tc.Assertions.Headers) != 0 { 101 | for expectedHeaderName, expectedHeaderValue := range tc.Assertions.Headers { 102 | canonicalHeaderName := textproto.CanonicalMIMEHeaderKey(expectedHeaderName) 103 | 104 | headerValue, foundHeader := res.Header[canonicalHeaderName] 105 | 106 | if !foundHeader { 107 | return false, fmt.Errorf("unable to find response header %s", canonicalHeaderName) 108 | } 109 | 110 | if strings.EqualFold(expectedHeaderValue, headerValue[0]) { 111 | continue 112 | } 113 | 114 | matched, err := regexp.MatchString(expectedHeaderValue, headerValue[0]) 115 | if err != nil || !matched { 116 | return false, fmt.Errorf("expected response header %s:%s received %s:%s", canonicalHeaderName, expectedHeaderValue, canonicalHeaderName, headerValue[0]) 117 | } 118 | } 119 | } 120 | 121 | return true, nil 122 | } 123 | -------------------------------------------------------------------------------- /runner/runner.go: -------------------------------------------------------------------------------- 1 | package runner 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "log" 9 | "sync" 10 | "time" 11 | 12 | "github.com/amad/smoker/core" 13 | "github.com/amad/smoker/runner/internal/report" 14 | ) 15 | 16 | // NewRunner creates and returns a new Runner. 17 | func NewRunner(workers int, timeout time.Duration, stopOnFailure bool, stdout io.StringWriter, stderr io.StringWriter) *Runner { 18 | reports := []core.TestResult{} 19 | 20 | ctx, cancelFunc := context.WithCancel(context.Background()) 21 | 22 | return &Runner{ 23 | workers: workers, 24 | timeout: timeout, 25 | stopOnFailure: stopOnFailure, 26 | stdout: stdout, 27 | stderr: stderr, 28 | reports: reports, 29 | ctx: ctx, 30 | cancelFunc: cancelFunc, 31 | } 32 | } 33 | 34 | // Runner is a type to manage and run tests and provide logs. 35 | type Runner struct { 36 | workers int 37 | timeout time.Duration 38 | stopOnFailure bool 39 | stdout, stderr io.StringWriter 40 | reports []core.TestResult 41 | ctx context.Context 42 | cancelFunc context.CancelFunc 43 | } 44 | 45 | // Run smoke test on a testsuite and provides results. 46 | func (r *Runner) Run(requester core.Requester, testsuite *core.Testsuite) (bool, error) { 47 | if len(testsuite.Tests) < 1 { 48 | return false, errors.New("no testcase found in this testsuite") 49 | } 50 | 51 | r.printfOut("Tests: %d total", len(testsuite.Tests)) 52 | r.printfOut("Workers: %d total", r.workers) 53 | r.printfOut("Timeout: %s", r.timeout.String()) 54 | r.printfOut("Stop on failure: %t\n", r.stopOnFailure) 55 | 56 | start := time.Now() 57 | 58 | var wg sync.WaitGroup 59 | reportsChan := make(chan core.TestResult, len(testsuite.Tests)) 60 | poolChan := make(chan struct{}, r.getPoolsize(testsuite)) 61 | 62 | r.printfOut("Waiting for results\n") 63 | go r.reportWriter(&wg, reportsChan) 64 | 65 | for i, tc := range testsuite.Tests { 66 | poolChan <- struct{}{} 67 | 68 | if r.isClosing() { 69 | break 70 | } 71 | 72 | wg.Add(2) // delta=2 to sync worker and reportWriter. 73 | go r.worker(&wg, requester, i+1, tc, poolChan, reportsChan) 74 | } 75 | 76 | wg.Wait() 77 | 78 | close(reportsChan) 79 | close(poolChan) 80 | defer r.cancelFunc() 81 | 82 | r.printfOut("\nElapsed: %.2fs", time.Since(start).Seconds()) 83 | 84 | for _, rp := range r.reports { 85 | if !rp.Passed() { 86 | return false, nil 87 | } 88 | } 89 | 90 | return true, nil 91 | } 92 | 93 | func (r *Runner) worker(wg *sync.WaitGroup, requester core.Requester, idx int, tc core.TestCase, pool <-chan struct{}, reportsChan chan<- core.TestResult) { 94 | defer wg.Done() 95 | 96 | s := time.Now() 97 | res, err := requester.Request(tc) 98 | 99 | reportsChan <- &report.TestReport{ 100 | Index: idx, 101 | Name: tc.Name, 102 | Status: res, 103 | Err: err, 104 | Duration: time.Since(s), 105 | } 106 | 107 | if !res { 108 | r.shouldStopOnFailure() 109 | } 110 | 111 | <-pool 112 | } 113 | 114 | // Stop pauses off the runner. 115 | // used for signal handling or when stop on failure is enabled. 116 | func (r *Runner) Stop() { 117 | r.cancelFunc() 118 | } 119 | 120 | func (r *Runner) isClosing() bool { 121 | if err := r.ctx.Err(); err != nil { 122 | return true 123 | } 124 | 125 | return false 126 | } 127 | 128 | func (r *Runner) shouldStopOnFailure() { 129 | if r.stopOnFailure { 130 | r.Stop() 131 | } 132 | } 133 | 134 | func (r *Runner) reportWriter(wg *sync.WaitGroup, reportsChan <-chan core.TestResult) { 135 | for report := range reportsChan { 136 | r.reports = append(r.reports, report) 137 | 138 | if report.Passed() { 139 | r.printfOut(report.String()) 140 | } else { 141 | r.printfErrOut(report.String()) 142 | } 143 | 144 | wg.Done() 145 | } 146 | } 147 | 148 | func (r *Runner) getPoolsize(ts *core.Testsuite) int { 149 | if r.workers >= len(ts.Tests) { 150 | return len(ts.Tests) 151 | } 152 | 153 | return r.workers 154 | } 155 | 156 | func (r *Runner) printfOut(msg string, params ...interface{}) { 157 | _, err := r.stdout.WriteString(fmt.Sprintf(msg, params...) + "\n") 158 | if err != nil { 159 | log.Fatal(err) 160 | } 161 | } 162 | 163 | func (r *Runner) printfErrOut(msg string, params ...interface{}) { 164 | _, err := r.stderr.WriteString(fmt.Sprintf(msg, params...) + "\n") 165 | if err != nil { 166 | log.Fatal(err) 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /runner/runner_test.go: -------------------------------------------------------------------------------- 1 | package runner 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "testing" 7 | "time" 8 | 9 | "github.com/amad/smoker/core" 10 | ) 11 | 12 | func TestNewRunner(t *testing.T) { 13 | t.Parallel() 14 | 15 | var workers = 5 16 | var buffer *bytes.Buffer 17 | 18 | NewRunner(workers, time.Second, false, buffer, buffer) 19 | } 20 | 21 | func newTestRunner(workers int, timeout int, stopOnFailure bool) *Runner { 22 | var buffer bytes.Buffer 23 | 24 | return NewRunner(workers, time.Duration(timeout)*time.Second, stopOnFailure, &buffer, &buffer) 25 | } 26 | 27 | func TestPrintfOutAndPrintfErrOut(t *testing.T) { 28 | expectedOutput := "test msg\n" 29 | expectedErrOutput := "test error\n" 30 | 31 | var stdout bytes.Buffer 32 | var stderr bytes.Buffer 33 | r := NewRunner(1, time.Second, false, &stdout, &stderr) 34 | 35 | r.printfErrOut("test %s", "error") 36 | r.printfOut("test %s", "msg") 37 | 38 | if stdout.String() != expectedOutput { 39 | t.Fatalf("stdout output does not match\nexpected: %s\nreceived: %s", expectedOutput, stdout.String()) 40 | } 41 | 42 | if stderr.String() != expectedErrOutput { 43 | t.Fatalf("stderr output does not match\nexpected: %s\nreceived: %s", expectedErrOutput, stderr.String()) 44 | } 45 | } 46 | 47 | func TestGetPoolsize(t *testing.T) { 48 | tt := []struct { 49 | name string 50 | numWorkers int 51 | numTestcases int 52 | expectPoolSize int 53 | }{ 54 | {"one worker", 1, 5, 1}, 55 | {"pool size is determined by num of workers", 2, 5, 2}, 56 | {"pool size can not be higher than test cases", 5, 3, 3}, 57 | } 58 | 59 | for _, tc := range tt { 60 | t.Run(tc.name, func(t *testing.T) { 61 | var buffer bytes.Buffer 62 | r := NewRunner(tc.numWorkers, time.Second, false, &buffer, &buffer) 63 | ts := &core.Testsuite{} 64 | for n := 0; n < tc.numTestcases; n++ { 65 | ts.Tests = append(ts.Tests, core.TestCase{}) 66 | } 67 | 68 | poolSize := r.getPoolsize(ts) 69 | 70 | if poolSize != tc.expectPoolSize { 71 | t.Fatalf("getPoolsize error\n expected: %d\nreceived: %d", tc.expectPoolSize, poolSize) 72 | } 73 | }) 74 | } 75 | } 76 | 77 | type testRequester struct{} 78 | 79 | func (r *testRequester) Request(tc core.TestCase) (bool, error) { 80 | if tc.Name == "fail" { 81 | return false, errors.New("testRequester fake failure") 82 | } 83 | 84 | return true, nil 85 | } 86 | 87 | func TestRunnerWithEmptySuite(t *testing.T) { 88 | requester := &testRequester{} 89 | runner := newTestRunner(1, 1, false) 90 | 91 | _, err := runner.Run(requester, &core.Testsuite{}) 92 | if err == nil { 93 | t.Fatal("Expected to throw error when testsuite is empty") 94 | } 95 | } 96 | 97 | func TestRunner(t *testing.T) { 98 | tt := []struct { 99 | name string 100 | testsuite *core.Testsuite 101 | stopOnFailure bool 102 | expectPassedCount int 103 | expectFailedCount int 104 | }{ 105 | { 106 | "all cases pass", 107 | &core.Testsuite{Tests: []core.TestCase{{}, {}, {}}}, 108 | false, 109 | 3, 110 | 0, 111 | }, 112 | { 113 | "one case should fail", 114 | &core.Testsuite{Tests: []core.TestCase{{Name: "fail"}, {}, {}}}, 115 | false, 116 | 2, 117 | 1, 118 | }, 119 | { 120 | "all cases fail", 121 | &core.Testsuite{Tests: []core.TestCase{{Name: "fail"}, {Name: "fail"}, {Name: "fail"}}}, 122 | false, 123 | 0, 124 | 3, 125 | }, 126 | { 127 | "stop on failure", 128 | &core.Testsuite{Tests: []core.TestCase{{Name: "fail"}, {}, {}}}, 129 | true, 130 | 0, 131 | 1, 132 | }, 133 | } 134 | 135 | for _, tc := range tt { 136 | t.Run(tc.name, func(t *testing.T) { 137 | requester := &testRequester{} 138 | runner := newTestRunner(1, 1, tc.stopOnFailure) 139 | 140 | ok, _ := runner.Run(requester, tc.testsuite) 141 | 142 | if tc.expectFailedCount > 0 && ok { 143 | t.Fatalf("Expected report to have failed test cases") 144 | } 145 | 146 | if buffer := runner.stdout.(*bytes.Buffer); buffer.String() == "" { 147 | t.Fatalf("Runner is not writing output") 148 | } 149 | 150 | expectReport(t, &runner.reports, tc.expectPassedCount, tc.expectFailedCount) 151 | }) 152 | } 153 | } 154 | 155 | func expectReport(t *testing.T, reports *[]core.TestResult, expectPassedCount int, expectFailedCount int) { 156 | var cp = 0 157 | var cf = 0 158 | for _, report := range *reports { 159 | if report.Passed() { 160 | cp = cp + 1 161 | } else { 162 | cf = cf + 1 163 | } 164 | } 165 | 166 | if cp != expectPassedCount { 167 | t.Fatalf("Expected report to have %d passed tests, got %d", expectPassedCount, cp) 168 | } 169 | 170 | if cf != expectFailedCount { 171 | t.Fatalf("Expected report to have %d failed tests, got %d", expectFailedCount, cf) 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Smoker 2 | 3 | ![Tests](https://github.com/amad/smoker/workflows/Tests/badge.svg?branch=master) 4 | [![Build Status](https://travis-ci.org/amad/smoker.svg?branch=master)](https://travis-ci.org/amad/smoker) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/amad/smoker)](https://goreportcard.com/report/github.com/amad/smoker) 6 | [![codecov](https://codecov.io/gh/amad/smoker/branch/master/graph/badge.svg)](https://codecov.io/gh/amad/smoker) 7 | [![License: MPL2.0](https://img.shields.io/badge/license-MPL2.0-brightgreen.svg)](https://opensource.org/licenses/MPL-2.0) 8 | [![Releases](https://img.shields.io/github/v/release/amad/smoker.svg?include_prereleases)](https://github.com/amad/smoker/releases) 9 | 10 | Fast smoke-testing tool for APIs and WEB with concurrency support. 11 | 12 | Describe test cases in JSON format. Each test case can define URL, HTTP method, request headers, and request body. Smoker makes assertions base on the response status-code and response body. 13 | 14 | ## Installation 15 | 16 | ### From source 17 | 18 | ```bash 19 | go get github.com/amad/smoker/cmd/smoker 20 | ``` 21 | 22 | ### Docker 23 | 24 | ```bash 25 | docker pull stunt/smoker:latest 26 | ``` 27 | 28 | ### Download pre-compiled 29 | 30 | ```bash 31 | # Find latest version: https://github.com/amad/smoker/releases 32 | curl -o smoker.tar.gz -L https://github.com/amad/smoker/releases/download/v0.3.0/smoker_0.3.0_linux_amd64.tar.gz 33 | tar -zxvf smoker.tar.gz --strip-components 1 34 | chmod +x ./smoker 35 | ./smoker -version 36 | ``` 37 | 38 | ### Requirements 39 | 40 | - Go 1.13 41 | 42 | ## Usage 43 | 44 | Run smoke-api.json testsuite file: 45 | 46 | ```bash 47 | smoker -testsuite smoke-api.json 48 | ``` 49 | 50 | Using docker image: 51 | 52 | ```bash 53 | docker run --rm -v $(PWD):/data stunt/smoker -testsuite /data/smoke-api.json 54 | ``` 55 | 56 | Run with 15 workers and set global timeout to 5 seconds: 57 | 58 | ```bash 59 | smoker -testsuite smoke-api.json -workers 15 -timeout 5 60 | ``` 61 | 62 | Run with `-stop-on-failure` flag to stop execution if any test-case fails: 63 | 64 | ```bash 65 | smoker -testsuite smoke-api.json -stop-on-failure 66 | ``` 67 | 68 | ```txt 69 | Usage: smoker [options...] 70 | 71 | Example: 72 | smoker -testsuite api.json 73 | smoker -testsuite web.json -workers 10 -timeout 5 -stop-on-failure 74 | 75 | Options: 76 | -testsuite Testsuite file in JSON format to read test cases. 77 | -workers Number of workers to send requests concurrently. (accepts integer value >= 1. Default is 1. 0 is not allowed) 78 | -timeout Set timeout per request in seconds. (accepts integer value >= 1. Default is 10. 0 is not allowed) 79 | -stop-on-failure Stop execution upon first error or failure. 80 | -version Prints the version and exits. 81 | ``` 82 | 83 | ## How to describe test cases 84 | 85 | A testsuite is a JSON file with the following structure. It accept an array of test cases, and you can have hundreds of test cases on each testsuite file. There is no limit on number of test cases per testsuite file. 86 | 87 | ```txt 88 | { 89 | "tests": [ 90 | // test cases here 91 | ] 92 | } 93 | ``` 94 | 95 | A test case can have all the following parameters to give you more control on what you want to test. But, most of these fields are optional. You can find more examples below. 96 | 97 | ```json 98 | { 99 | "tests": [ 100 | { 101 | "name": "A test case with all parameters", 102 | "url": "https://api.github.com", 103 | "method": "post", 104 | "body": "{\"test\":1}", 105 | "headers": { 106 | "content-type": "application/json" 107 | }, 108 | "assertions": { 109 | "statusCode": 200, 110 | "body": [ 111 | "github", 112 | "[a-z]" 113 | ], 114 | "headers": { 115 | "Content-Type": "application/json" 116 | } 117 | } 118 | } 119 | ] 120 | } 121 | ``` 122 | 123 | Minimum requirement for a test case is to have a `name` field, and a `url` field. All the other fields are optional. 124 | The default request method is `GET` and the default assertion is to match `200` HTTP status code. 125 | 126 | ```json 127 | { 128 | "tests": [ 129 | { 130 | "name": "Assert github.com/amad/smoker returns 200", 131 | "url": "https://github.com/amad/smoker" 132 | }, 133 | { 134 | "name": "Assert Github is OK", 135 | "url": "https://github.com" 136 | } 137 | ] 138 | } 139 | ``` 140 | 141 | You can optionally set the HTTP method, request body, and request headers as well. All these fields are optional. 142 | 143 | Example: 144 | 145 | ```json 146 | { 147 | "tests": [ 148 | { 149 | "name": "Send a POST request with header and body", 150 | "url": "https://api.github.com", 151 | "method": "post", 152 | "body": "{\"test\":1}", 153 | "headers": { 154 | "content-type": "application/json" 155 | } 156 | } 157 | ] 158 | } 159 | ``` 160 | 161 | You can make assertion on HTTP status code, and also assert whether the response contains any match of the provided regular expression or simple string. You can also make assertion on response header. 162 | 163 | Test case fails if the HTTP status code does not match, Or any of the assertion in body do not match. 164 | 165 | The `assertions.statusCode` field accepts a HTTP status code to check. The default value for this field is `200`. 166 | 167 | The `assertions.body` field accepts an array of strings that can contain simple string or regex. When this field isn't provided, Smoker does not make any assertions on response body. 168 | 169 | The `assertions.header` field accepts a map of strings. When this field isn't provided, Smoker does not make any assertions on response header. You can use regular expression to match header value. But, you must provide full header name. 170 | 171 | Example: 172 | 173 | ```json 174 | { 175 | "tests": [ 176 | { 177 | "name": "Multiple assertions on response body and one assertion on status code", 178 | "url": "https://github.com/amad/NotFoundRepo", 179 | "assertions": { 180 | "statusCode": 404, 181 | "body": [ 182 | "Github", 183 | "Page not found", 184 | "[a-z]" 185 | ], 186 | "headers": { 187 | "Content-Type": "application/json", 188 | "X-Requestid": "*" 189 | } 190 | } 191 | } 192 | ] 193 | } 194 | ``` 195 | -------------------------------------------------------------------------------- /requester/requester_test.go: -------------------------------------------------------------------------------- 1 | package requester 2 | 3 | import ( 4 | "bytes" 5 | "io/ioutil" 6 | "net/http" 7 | "strings" 8 | "testing" 9 | "time" 10 | 11 | "github.com/amad/smoker/core" 12 | ) 13 | 14 | var expectedUserAgent = "test-user-agent" 15 | var expectedTimeout = time.Second 16 | 17 | func TestNewRequester(t *testing.T) { 18 | t.Parallel() 19 | 20 | r := NewRequester(expectedTimeout, expectedUserAgent) 21 | 22 | if r.userAgent != expectedUserAgent { 23 | t.Fatalf("Expected to set correct user agent %s but received %s", expectedUserAgent, r.userAgent) 24 | } 25 | 26 | if r.client.Timeout != expectedTimeout { 27 | t.Fatalf("Expected to set timeout %d but received %d", expectedTimeout, r.client.Timeout) 28 | } 29 | } 30 | 31 | func TestRequest(t *testing.T) { 32 | t.Parallel() 33 | 34 | tt := []struct { 35 | name string 36 | tc core.TestCase 37 | mockStatusCode int 38 | mockResBody string 39 | mockResHeader map[string]string 40 | expectErr string 41 | }{ 42 | { 43 | name: "OK", 44 | tc: core.TestCase{ 45 | Name: "test", 46 | URL: "example.com", 47 | Method: "get", 48 | Headers: map[string]string{"Content-Type": "application/json"}, 49 | Body: "OK", 50 | Assertions: core.Assertions{ 51 | StatusCode: 200, 52 | Body: []string{"OK"}, 53 | }, 54 | }, 55 | mockStatusCode: 200, 56 | mockResBody: "OK", 57 | expectErr: "", 58 | }, 59 | { 60 | name: "name is required", 61 | tc: core.TestCase{ 62 | Name: "", 63 | }, 64 | mockStatusCode: 200, 65 | mockResBody: "OK", 66 | expectErr: "does not have name field", 67 | }, 68 | { 69 | name: "url is required", 70 | tc: core.TestCase{ 71 | Name: "test", 72 | }, 73 | mockStatusCode: 200, 74 | mockResBody: "OK", 75 | expectErr: "does not have url field", 76 | }, 77 | { 78 | name: "default method is get", 79 | tc: core.TestCase{ 80 | Name: "test", 81 | URL: "example.com", 82 | }, 83 | mockStatusCode: 200, 84 | }, 85 | { 86 | name: "errors when does not match status code", 87 | tc: core.TestCase{ 88 | Name: "test", 89 | URL: "example.com", 90 | }, 91 | mockStatusCode: 500, 92 | expectErr: "expected status-code: 200 received: 500", 93 | }, 94 | { 95 | name: "errors when does not match body", 96 | tc: core.TestCase{ 97 | Name: "test", 98 | URL: "example.com", 99 | Assertions: core.Assertions{ 100 | Body: []string{"OK"}, 101 | }, 102 | }, 103 | mockStatusCode: 200, 104 | mockResBody: "something else", 105 | expectErr: "can not match /OK/ in response body", 106 | }, 107 | { 108 | name: "can match body with regex", 109 | tc: core.TestCase{ 110 | Name: "test", 111 | URL: "example.com", 112 | Assertions: core.Assertions{ 113 | Body: []string{"^[0-9]{3}-[0-9]{5}$"}, 114 | }, 115 | }, 116 | mockStatusCode: 200, 117 | mockResBody: "123-45678", 118 | }, 119 | { 120 | name: "errors when can not match header", 121 | tc: core.TestCase{ 122 | Name: "test", 123 | URL: "example.com", 124 | Assertions: core.Assertions{ 125 | Headers: map[string]string{"Content-Type": "application/json"}, 126 | }, 127 | }, 128 | mockStatusCode: 200, 129 | mockResHeader: map[string]string{"Content-Type": "text/html"}, 130 | expectErr: "expected response header Content-Type:application/json received Content-Type:text/html", 131 | }, 132 | { 133 | name: "errors when expected header not found", 134 | tc: core.TestCase{ 135 | Name: "test", 136 | URL: "example.com", 137 | Assertions: core.Assertions{ 138 | Headers: map[string]string{"Content-Type": "application/json"}, 139 | }, 140 | }, 141 | mockStatusCode: 200, 142 | expectErr: "unable to find response header Content-Type", 143 | }, 144 | { 145 | name: "can match header", 146 | tc: core.TestCase{ 147 | Name: "test", 148 | URL: "example.com", 149 | Assertions: core.Assertions{ 150 | Headers: map[string]string{"access-control-allow-origin": "*", "content-length": "[0-9]+"}, 151 | }, 152 | }, 153 | mockStatusCode: 200, 154 | mockResHeader: map[string]string{"access-control-allow-origin": "*", "content-length": "23432"}, 155 | }, 156 | } 157 | 158 | for _, item := range tt { 159 | t.Run(item.tc.Name, func(t *testing.T) { 160 | mockClient := newTestClient(func(req *http.Request) *http.Response { 161 | if item.tc.Method != "" && req.Method != strings.ToUpper(item.tc.Method) { 162 | t.Fatalf("Request method does not match\nexpected: %s\nreceived: %s", strings.ToUpper(item.tc.Method), req.Method) 163 | } else if item.tc.Method == "" && req.Method != "GET" { 164 | t.Fatalf("Request method does not match\nexpected: %s\nreceived: %s", "GET", req.Method) 165 | } 166 | 167 | if req.URL.String() != item.tc.URL { 168 | t.Fatalf("Request URL does not match\nexpected: %s\nreceived: %s", item.tc.URL, req.URL.String()) 169 | } 170 | 171 | if item.tc.Body != "" { 172 | if b, _ := ioutil.ReadAll(req.Body); string(b) != item.tc.Body { 173 | t.Fatalf("Request body does not match\nexpected: %s\nreceived: %s", item.tc.Body, string(b)) 174 | } 175 | } 176 | 177 | if userAgent, ok := req.Header["User-Agent"]; true { 178 | if !ok { 179 | t.Fatal("Expected to send User-Agent header but got ") 180 | } 181 | 182 | if userAgent[0] != expectedUserAgent { 183 | t.Fatalf("Header User-Agent does not match\nexpected: %s\nreceived: %s", expectedUserAgent, userAgent[0]) 184 | } 185 | } 186 | 187 | if _, ok := req.Header["Request-Id"]; !ok { 188 | t.Fatal("Expected to send Request-Id header but got ") 189 | } 190 | 191 | for headerName, headerValue := range item.tc.Headers { 192 | if val, ok := req.Header[headerName]; !ok || headerValue != val[0] { 193 | t.Fatalf("Header %s does not match\nexpected: %s\nreceived: %s", headerName, headerValue, val[0]) 194 | } 195 | } 196 | 197 | resHeader := make(http.Header) 198 | 199 | for hn, hv := range item.mockResHeader { 200 | resHeader.Add(hn, hv) 201 | } 202 | 203 | return &http.Response{ 204 | StatusCode: item.mockStatusCode, 205 | Body: ioutil.NopCloser(bytes.NewBufferString(item.mockResBody)), 206 | Header: resHeader, 207 | } 208 | }) 209 | requester := &Requester{ 210 | mockClient, 211 | expectedUserAgent, 212 | } 213 | 214 | _, err := requester.Request(item.tc) 215 | 216 | if err != nil { 217 | if item.expectErr == "" { 218 | t.Fatalf("Unexpected error\nexpected: \nreceived: %s", err.Error()) 219 | } 220 | 221 | if ok := strings.Contains(err.Error(), item.expectErr); !ok { 222 | t.Fatalf("Expected error does not match\nexpected: %s\nreceived: %s", item.expectErr, err.Error()) 223 | } 224 | 225 | return 226 | } 227 | 228 | if item.expectErr != "" { 229 | t.Fatalf("Expected to throw error\nexpected: %s\nreceived: ", item.expectErr) 230 | } 231 | }) 232 | } 233 | } 234 | 235 | type roundTripFunc func(r *http.Request) *http.Response 236 | 237 | func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { 238 | return f(r), nil 239 | } 240 | 241 | func newTestClient(fn roundTripFunc) *http.Client { 242 | return &http.Client{ 243 | Transport: roundTripFunc(fn), 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | --------------------------------------------------------------------------------