• Stars
    star
    250
  • Rank 162,397 (Top 4 %)
  • Language
    Go
  • License
    MIT License
  • Created over 5 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

http integration test framework

go-hit

Actions Status Coverage Status PkgGoDev GoDoc go-report go1.15

hit is an http integration test framework written in golang.

It is designed to be flexible as possible, but to keep a simple to use interface for developers.

So lets get started!

go get -u github.com/Eun/go-hit

package main

import (
    "net/http"
    . "github.com/Eun/go-hit"
)

func main() {
    MustDo(
        Description("Post to httpbin.org"),
        Get("https://httpbin.org/post"),
        Expect().Status().Equal(http.StatusMethodNotAllowed),
        Expect().Body().String().Contains("Method Not Allowed"),
    )
}

Or use the Test() function:

package main_test
import (
    "testing"
    "net/http"
    . "github.com/Eun/go-hit"
)

func TestHttpBin(t *testing.T) {
    Test(t,
        Description("Post to httpbin.org"),
        Get("https://httpbin.org/post"),
        Expect().Status().Equal(http.StatusMethodNotAllowed),
        Expect().Body().String().Contains("Method Not Allowed"),
    )
}

Expect, Expect, Expect, ....

MustDo(
    Get("https://httpbin.org/post"),
    Expect().Status().Equal(http.StatusMethodNotAllowed),
    Expect().Headers("Content-Type").NotEmpty(),
    Expect().Body().String().Contains("Method Not Allowed"),
)

Sending Data

MustDo(
    Post("https://httpbin.org/post"),
    Send().Body().String("Hello HttpBin"),
    Expect().Status().Equal(http.StatusOK),
    Expect().Body().String().Contains("Hello HttpBin"), 
)

Sending And Expecting JSON

MustDo(
    Post("https://httpbin.org/post"),
    Send().Headers("Content-Type").Add("application/json"),
    Send().Body().JSON(map[string][]string{"Foo": []string{"Bar", "Baz"}}),
    Expect().Status().Equal(http.StatusOK),
    Expect().Body().JSON().JQ(".json.Foo[1]").Equal("Baz"),
)

Storing Data From The Response

var name string
var roles []string
MustDo(
    Post("https://httpbin.org/post"),
    Send().Headers("Content-Type").Add("application/json"),
    Send().Body().JSON(map[string]interface{}{"Name": "Joe", "Roles": []string{"Admin", "Developer"}}),
    Expect().Status().Equal(http.StatusOK),
    Store().Response().Body().JSON().JQ(".json.Name").In(&name),
    Store().Response().Body().JSON().JQ(".json.Roles").In(&roles),
)
fmt.Printf("%s has %d roles\n", name, len(roles))

Problems? Debug!

MustDo(
    Post("https://httpbin.org/post"),
    Debug(),
    Debug().Response().Body(),
)

Handling Errors

It is possible to handle errors in a custom way.

func login(username, password string) error {
    err := Do(
         Get("https://httpbin.org/basic-auth/joe/secret"),
         Send().Headers("Authorization").Add("Basic " + base64.StdEncoding.EncodeToString([]byte(username + ":" + password))),
         Expect().Status().Equal(http.StatusOK),
    )
    var hitError *Error
    if errors.As(err, &hitError) {
        if hitError.FailingStepIs(Expect().Status().Equal(http.StatusOK)) {
            return errors.New("login failed")
        }
    }
    return err
}

Build the request url manually

MustDo(
    Request().Method(http.MethodPost),
    Request().URL().Scheme("https"),
    Request().URL().Host("httpbin.org"),
    Request().URL().Path("/post"),
    Request().URL().Query("page").Add(1),
    Expect().Status().Equal(200),
    Send().Body().String("Hello World"),
    Expect().Body().String().Contains("Hello"),
)

Twisted!

Although the following is hard to read it is possible to do!

MustDo(
    Post("https://httpbin.org/post"),
    Expect().Status().Equal(200),
    Send().Body().String("Hello World"),
    Expect().Body().String().Contains("Hello"),
)

Custom Send And Expects

MustDo(
    Get("https://httpbin.org/get"),
    Send().Custom(func(hit Hit) error {
        hit.Request().Body().SetStringf("Hello %s", "World")
        return nil
    }),
    Expect().Custom(func(hit Hit) error {
        if len(hit.Response().Body().MustString()) <= 0 {
            return errors.New("expected the body to be not empty")
        }
        return nil
    }),
    Custom(AfterExpectStep, func(Hit) error {
        fmt.Println("everything done")
        return nil
    }),
)

Templates / Multiuse

template := CombineSteps(
    Post("https://httpbin.org/post"),
    Send().Headers("Content-Type").Add("application/json"),
    Expect().Headers("Content-Type").Equal("application/json"),
)
MustDo(
    template,
    Send().Body().JSON("Hello World"),
)

MustDo(
    template,
    Send().Body().JSON("Hello Universe"),
)

Clean Previous Steps

Sometimes it is necessary to remove some steps that were added before.

template := CombineSteps(
    Get("https://httpbin.org/basic-auth/joe/secret"),
    Expect().Status().Equal(http.StatusOK),
)
MustDo(
    Description("login with correct credentials"),
    template,
    Send().Headers("Authorization").Add("Basic " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))),
)

Test(t,
    Description("login with incorrect credentials"),
    template,
    Clear().Expect().Status(),
    Expect().Status().Equal(http.StatusUnauthorized),
    Send().Headers("Authorization").Add("Basic " + base64.StdEncoding.EncodeToString([]byte("joe:joe"))),
)

More examples can be found in the examples directory

Changelog

0.5.0

  • Rehaul the api, make things more explicit
  • Fix some issues
  • Store() functionality
  • Generate Clear() paths
  • Infinite JQ() functionality
  • Test README.md and documentation parts

0.4.0

  • Fixed a double run bug in CombineSteps (#3)
  • Better Clear functionality, you can now clear any previous step by prepending Clear(), eg.
    Do(
        Get("https://example.com"),
        Expect().Body("Hello World"),
        Clear().Expect(),                        // remove all previous Expect() steps
        // Clear().Expect().Body("Hello World"), // remove only the Expect().Body("Hello World") step
    )
    
    // also works for CombineSteps
    Do(
        Post("https://example.com"),        
        CombineSteps(
            Send().Body().String("Hello World"),
            Expect().Body("Hello World"),
        ),
        Clear().Expect(),
    )
  • Simplified Expect().Header() use, no more Expect().Headers(), everything can now be done in the Expect().Header() function.
  • More documentation and examples
  • hit.Do and hit.MustDo for inline steps.
  • Removal of inline steps (use hit.Do and hit.MustDo)
    Do(
        Get("https://example.com"),
        Expect().Custon(func (hit Hit) {
            // Expect("Hello World") is invalid now
            // you must use MustDo() or Do()
            hit.MustDo(
                Expect("Hello World"),
            )
        }),
    )
  • hit.InsertSteps to insert steps during runtime

More Repositories

1

DisableMonitor

Easily disable or enable a monitor on your Mac.
1,349
star
2

MoveToDesktop

Move windows using hotkeys or the system menu
C++
1,050
star
3

icmpmon

A simple ICMP monitor with web interface.
JavaScript
33
star
4

yaegi-template

Use yaegi as a template engine.
Go
32
star
5

goremovelines

Remove leading / trailing blank lines in Go functions, structs, if, switches, blocks.
Go
25
star
6

go-convert

Convert a value into another type
Go
22
star
7

sshkeys

Get all ssh public keys of a ssh server
Go
21
star
8

govizz

Go
19
star
9

gdriver

A golang implementation to access google drive by using traditional file-folder-path pattern.
Go
12
star
10

logtimer

Enhance your output with a timer / date
Go
11
star
11

http-server-action

An action that spawns an http server to serve files.
JavaScript
11
star
12

http-response

A sample on howto notify a work status in tradional (non javascript) golang web app
Go
9
star
13

2slack

Send a message to slack
Go
8
star
14

coredns-ipecho

ipecho is an coredns plugin, it answers ip subdomain queries with the ip itself.
Go
7
star
15

RememberIME

Automatically change and remember the IME setting (App/Activity based).
Java
7
star
16

minigo

A mini golang interpreter
Go
7
star
17

frwd

Just another nearly zero configuration ngrok ssh alternative.
Shell
6
star
18

nss_http

Name Service Switch Service that uses an http JSON backend.
C
6
star
19

SM_ServerWebView

SourceMod Plugin that provides an Webinterface
SourcePawn
6
star
20

makeconsole

Make a console picture as a service.
Go
6
star
21

CustomTasks

CustomTasks Plugin for Sublime Text
Python
6
star
22

watermark

watermark an image with a specific text
HTML
5
star
23

atom.watch

An approach to display a beautiful atom clock in the browser.
Vue
5
star
24

CefSharp-Example

This is an preconfigured project to start right off using chromium in C#
C#
5
star
25

merge-with-label

A github bot for merging & updating pull requests with a label.
Go
5
star
26

go-prioselect

golangs select with a priority order.
Go
4
star
27

deb-awscli2

aws cli v2 apt repository
Shell
4
star
28

gomultifmt

Run multiple golang formatters in one command
Go
4
star
29

GPSNotification

Brings the JellyBean GPS Notification back.
Java
4
star
30

Intel-Pentium-Instruction-Set-Reference

HTML
4
star
31

mapprint

Printf for maps and structs
Go
4
star
32

hasura-where

TypeScript
3
star
33

eventbus

A Multiconsumer/multiproducer bus.
Go
3
star
34

cwolsrv

Run custom commands on wake on lan magic packets.
Go
3
star
35

go-doppelgangerreader

read a io.Reader multiple times
Go
3
star
36

CWebSocket

CWebSocket is a small Class that can make HTTP requests, without third party libaries.
C++
3
star
37

ProcessTree

Shows a Process Tree on Mac
Objective-C
3
star
38

LegalNoticeCreator

Allows you to show a notice before login on Windows machines.
CSS
3
star
39

TFSMonkey

C#
3
star
40

go-testdoc

Go
3
star
41

InitialVolume

Set an initial volume for android devices after boot.
Java
3
star
42

KioskLauncher

launch a windows application, maximize it and as soon as it stops do something else
Go
2
star
43

go-parser

Go
2
star
44

go-bin-template

A template for a golang repository with a binary output. It comes with linter, testing and automatic releasing
Go
2
star
45

IBANCalculator

Calculate IBAN
CSS
2
star
46

bubbleviews

Go
2
star
47

go-pgx-cursor-iterator

A golang package for fetching big chunks of rows from a postgres database using a cursor.
Go
2
star
48

go-mod-details

JavaScript
2
star
49

DeleteGApps

Script to delete all Google Apps from your android device.
Shell
2
star
50

StartBluetooth

Enable or Disable bluetooth for android devices after boot.
Java
2
star
51

scrm

JavaScript
2
star
52

oauthenticator

Go
2
star
53

gcal-to-ics

Go
2
star
54

NoDoubleClick

Your Mouse is broken? Click fires sometimes as Doubleclick? No Problem, use this to prevent unusual Dobuleclicks.
C++
2
star
55

microhelpers

Go
1
star
56

go-test-buckets

Split your go tests into buckets.
Go
1
star
57

github-comment

Go
1
star
58

PopupYouTube

JavaScript
1
star
59

go-timebox

timebox a go function
Go
1
star
60

mitmproxy-vagrant

Shell
1
star
61

ecp

copies files with checksum on the fly
C
1
star
62

SparseFile

Create Sparse Files
C++
1
star
63

coredns-unifi-names

Go
1
star
64

docker-purge

Go
1
star
65

loginexample

loginexample is an example of go-gen-api
Go
1
star
66

oobmultipartreader

Construct a multipart reader from other streams
Go
1
star
67

node.atom.watch

JavaScript
1
star
68

ftppass

A ftp server that prints out the username and password of all connected users
Go
1
star
69

go-batch-iterator

iterator to sequentially iterate over datasources utilizing a batch approach
Go
1
star
70

minWatch.js

Minimal module to watch javascript object for changes.
JavaScript
1
star
71

docker-ubuntu-20-04-ssh-x11

Dockerfile
1
star
72

htpdate

Go
1
star
73

go-gen-graphql

Go
1
star
74

cybercook

A cheap imitation of CyberChef.
HTML
1
star
75

gcloud-ssh

A interactive way to connect to your Google Cloud VM instances
Go
1
star
76

serrors

Go
1
star
77

Android-Template-with-Xamarin.Forms

Sample project for Visual Studio 2017 using Android and Xamarin.Forms
C#
1
star
78

go-feistel

Go
1
star