Code Monkey home page Code Monkey logo

go-testing's Introduction

Collection of testing methodics for Golang

  • Repository created to collect different methodics of writing and using tests with Golang language.

Tools

List tests in package/directory

Unit tests

func Foo() error {}

func TestFoo(t *testing.T) {
  err := Foo()
  assert.NoError(t, err)
})
}
  • testing (std)
func Foo() {}

func TestFoo(t *testing.T) {
  t.Run("Foo", func(t *testing.T) {
    Foo()
})
}

Fuzzing

Mocks(generally)

func TestFoo(t *testing.T) {
  ctrl := gomock.NewController(t)
  defer ctrl.Finish()

  m := NewMockFoo(ctrl)

  // Does not make any assertions. Executes the anonymous functions and returns
  // its result when Bar is invoked with 99.
  m.
    EXPECT().
    Bar(gomock.Eq(99)).
    DoAndReturn(func(_ int) int {
      time.Sleep(1*time.Second)
      return 101
    }).
    AnyTimes()

  // Does not make any assertions. Returns 103 when Bar is invoked with 101.
  m.
    EXPECT().
    Bar(gomock.Eq(101)).
    Return(103).
    AnyTimes()

  SUT(m)
}

Integration tests

Fuzzing tests

func FuzzReverse(f *testing.F) {
    testcases := []string{"Hello, world", " ", "!12345"}
    for _, tc := range testcases {
        f.Add(tc)  // Use f.Add to provide a seed corpus
    }
    f.Fuzz(func(t *testing.T, orig string) {
        rev := Reverse(orig)
        doubleRev := Reverse(rev)
        if orig != doubleRev {
            t.Errorf("Before: %q, after: %q", orig, doubleRev)
        }
        if utf8.ValidString(orig) && !utf8.ValidString(rev) {
            t.Errorf("Reverse produced invalid UTF-8 string %q", rev)
        }
    })
}

Benchmark tests

func BenchmarkRandInt(b *testing.B) {
    for i := 0; i < b.N; i++ {
        rand.Int()
    }
}

Mocking

Vault

package main

import (
    "net"
    "testing"

    "github.com/hashicorp/vault/api"
    "github.com/hashicorp/vault/http"
    "github.com/hashicorp/vault/vault"
)

func TestVaultStuff(t *testing.T) {
    ln, client := createTestVault(t)
    defer ln.Close()

    // Pass the client to the code under test.
    myFunction(client)
}

func createTestVault(t *testing.T) (net.Listener, *api.Client) {
    t.Helper()

    // Create an in-memory, unsealed core (the "backend", if you will).
    core, keyShares, rootToken := vault.TestCoreUnsealed(t)
    _ = keyShares

    // Start an HTTP server for the core.
    ln, addr := http.TestServer(t, core)

    // Create a client that talks to the server, initially authenticating with
    // the root token.
    conf := api.DefaultConfig()
    conf.Address = addr

    client, err := api.NewClient(conf)
    if err != nil {
        t.Fatal(err)
    }
    client.SetToken(rootToken)

    // Setup required secrets, policies, etc.
    _, err = client.Logical().Write("secret/foo", map[string]interface{}{
        "secret": "bar",
    })
    if err != nil {
        t.Fatal(err)
    }

    return ln, client
}

Docker

Redis

PostgreSQL

K8s

Logging

  • use assert.NotNil to check that logs generated correctly

API

package main

import (
   "net/http"
   "net/http/httptest"
   "testing"

   "github.com/gorilla/mux"
)

func Test_bookmarkIndex(t *testing.T) {
   r := mux.NewRouter()
   r.Handle("/v1/bookmark", bookmarkIndex())
   ts := httptest.NewServer(r)
   defer ts.Close()
   res, err := http.Get(ts.URL + "/v1/bookmark")
   if err != nil {
      t.Errorf("Expected nil, received %s", err.Error())
   }
   if res.StatusCode != http.StatusOK {
      t.Errorf("Expected %d, received %d", http.StatusOK, res.StatusCode)
   }
}

func Test_bookmarkFind(t *testing.T) {
   r := mux.NewRouter()
   r.Handle("/v1/bookmark/{id}", bookmarkFind())
   ts := httptest.NewServer(r)
   defer ts.Close()
   t.Run("not found", func(t *testing.T) {
      res, err := http.Get(ts.URL + "/v1/bookmark/1")
      if err != nil {
         t.Errorf("Expected nil, received %s", err.Error())
      }
      if res.StatusCode != http.StatusNotFound {
         t.Errorf("Expected %d, received %d", http.StatusNotFound, res.StatusCode)
      }
   })
   t.Run("found", func(t *testing.T) {
      res, err := http.Get(ts.URL + "/v1/bookmark/2")
      if err != nil {
         t.Errorf("Expected nil, received %s", err.Error())
      }
      if res.StatusCode != http.StatusOK {
         t.Errorf("Expected %d, received %d", http.StatusOK, res.StatusCode)
      }
   })
}

Pubsub

Kafka

DNS

go-testing's People

Contributors

gonnafaraway avatar

Stargazers

 avatar xhd2015 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.