• Stars
    star
    136
  • Rank 267,630 (Top 6 %)
  • Language
    Go
  • License
    MIT License
  • Created about 6 years ago
  • Updated about 2 years ago

Reviews

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

Repository Details

✔️ tf is a microframework for parameterized testing of functions and HTTP in Go.

tf

tf is a microframework for parametrized testing of functions and HTTP in Go.

Functions

It offers a simple and intuitive syntax for tests by wrapping the function:

// Remainder returns the quotient and remainder from dividing two integers.
func Remainder(a, b int) (int, int) {
    return a / b, a % b
}

func TestRemainder(t *testing.T) {
    Remainder := tf.Function(t, Remainder)

    Remainder(10, 3).Returns(3, 1)
    Remainder(10, 2).Returns(5, 0)
    Remainder(17, 7).Returns(2, 3)
}

Assertions are performed with testify. If an assertion fails it will point to the correct line so you do not need to explicitly label tests.

The above test will output (in verbose mode):

=== RUN   TestRemainder
--- PASS: TestRemainder (0.00s)
=== RUN   TestRemainder/Remainder#1
--- PASS: TestRemainder/Remainder#1 (0.00s)
=== RUN   TestRemainder/Remainder#2
--- PASS: TestRemainder/Remainder#2 (0.00s)
=== RUN   TestRemainder/Remainder#3
--- PASS: TestRemainder/Remainder#3 (0.00s)
PASS

Grouping

Use NamedFunction to specify a custom name for the function/group:

func TestNamedSum(t *testing.T) {
	Sum := tf.NamedFunction(t, "Sum1", Item.Add)

	Sum(Item{1.3, 4.5}, 3.4).Returns(9.2)
	Sum(Item{1.3, 4.6}, 3.5).Returns(9.4)

	Sum = tf.NamedFunction(t, "Sum2", Item.Add)

	Sum(Item{1.3, 14.5}, 3.4).Returns(19.2)
	Sum(Item{21.3, 4.6}, 3.5).Returns(29.4)
}

Struct Functions

You can test struct functions by providing the struct value as the first parameter followed by any function arguments, if any.

type Item struct {
	a, b float64
}

func (i Item) Add(c float64) float64 {
	return i.a + i.b + c
}

func TestItem_Add(t *testing.T) {
	Sum := tf.Function(t, Item.Add)

	Sum(Item{1.3, 4.5}, 3.4).Returns(9.2)
}

HTTP Testing

Client

Super easy HTTP testing by using the ServeHTTP function. This means that you do not have to run the server and it is compatible with all HTTP libraries and frameworks but has all the functionality of the server itself.

The simplest example is to use the default muxer in the http package:

http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, World!")
})

And now we can write some tests:

func TestHTTPRouter(t *testing.T) {
	run := tf.ServeHTTP(t, http.DefaultServeMux.ServeHTTP)

	run(&tf.HTTPTest{
		Path:         "/hello",
		Status:       http.StatusOK,
		ResponseBody: strings.NewReader("Hello, World!"),
	})

	run(&tf.HTTPTest{
		Path:   "/world",
		Status: http.StatusNotFound,
	})
}

It is compatible with all HTTP frameworks because they must all expose a ServeHTTP which is the entry point for the request router/handler.

There are many more options for HTTPTest. Some HTTP tests require multiple operations, you can use MultiHTTPTest for this:

run(&tf.MultiHTTPTest{
	Steps: []*tf.HTTPTest{
		{
			Path:        "/save",
			Method:      http.MethodPut,
			RequestBody: strings.NewReader(`{"foo":"bar"}`),
			Status:      http.StatusCreated,
		},
		{
			Path:         "/fetch",
			Method:       http.MethodGet,
			Status:       http.StatusOK,
			ResponseBody: strings.NewReader(`{"foo":"bar"}`),
		},
	},
})

Each step will only proceed if the previous step was successful.

Server

Sometimes you need to mock HTTP servers where the only option is to provide a URL endpoint through to your test. That is, when you do not have direct access to the router, or it's impractical to inject the behavior.

For case this you can use a HTTPServer:

// 0 means to use a random port, or you can provide your own.
server := tf.StartHTTPServer(0).
	AddHandlers(map[string]http.HandlerFunc{
		"/hi": func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte(`hello`))
		},
		"/easy": tf.HTTPJSONResponse(200, []int{1, 2, 3}),
	})

// Always remember to tear down the resources when the test ends.
defer server.Shutdown()

// Your test code here...
server.Endpoint() // http://localhost:61223

Using a real HTTP server has some benefits:

  1. It's isolated. That means it does not interfere in anyway with the global HTTP server.

  2. It can be used in parallel. You can either share the same HTTPServer across many tests (such as in TestMain), or create one for each test in parallel. Providing 0 for the port (as in the example above) will ensure that it always selects an unused random port.

  3. It mutable. After creating and starting the HTTPServer you can add/remove handlers. This is useful when most tests need a base logic, but some cases need to return special under specific scenarios.

You can create your own handlers, of course, but there are a few common ones that also ship with tf:

  • HTTPEmptyResponse(statusCode int)
  • HTTPStringResponse(statusCode int, body string)
  • HTTPJSONResponse(statusCode int, body interface{})

Environment Variables

SetEnv sets an environment variable and returns a reset function to ensure the environment is always returned to it's previous state:

resetEnv := tf.SetEnv(t, "HOME", "/somewhere/else")
defer resetEnv()

If you would like to set multiple environment variables, you can use SetEnvs in the same way:

resetEnv := tf.SetEnvs(t, map[string]string{
    "HOME":  "/somewhere/else",
    "DEBUG": "on",
})
defer resetEnv()

More Repositories

1

c2go

⚖️ A tool for transpiling C to Go.
Go
1,954
star
2

pie

🍕 Enjoy a slice! A utility library for dealing with slices and maps that focuses on type safety and performance.
Go
1,655
star
3

orderedmap

🔃 An ordered map in Go with amortized O(1) for Set, Get, Delete and Len.
Go
614
star
4

sshtunnel

🚇 Ultra simple SSH tunnelling for Go programs.
Go
253
star
5

vsql

✌️ Single-file or PostgreSQL-server compatible transactional SQL database written in pure V.
V
236
star
6

dingo

🐺 Easy, fast and type-safe dependency injection for Go.
Go
185
star
7

redismock

🕋 Mocking Redis in unit tests in Go.
Go
139
star
8

pepper

🌶️ Create reactive frontends without ever writing frontend code.
Go
110
star
9

phpserialize

📑 PHP serialize() and unserialize() for Go
Go
108
star
10

mbzdb

🎵 Port of the MusicBrainz database to run on other RDBMSs with replication (previously named MB_MySQL.)
Perl
88
star
11

gedcom

👪 A Go library and CLI tools for encoding, decoding, traversing, merging, comparing, querying and publishing GEDCOM files.
Go
72
star
12

ghost

👻 Locate and fix overly complex lines of code in Go.
Go
53
star
13

concise

✅ Concise is test framework for using plain English and minimal code, built on PHPUnit.
PHP
47
star
14

CollectionFactory

🏭 Translation between native collections in Objective-C and serialized formats like JSON.
Objective-C
41
star
15

sqltest

📝 A comprehensive suite of SQL tests for testing the conformance of databases.
Python
39
star
16

bento

🍱 bento is an English-based automation language designed to be used by non-technical people.
Go
32
star
17

redis-usage

👁️ A non-blocking way to count the number of keys or size of Redis key prefixes
Go
30
star
18

vlang-sublime

Sublime Text support for the V programming language
Python
29
star
19

reflect

🪞 Runtime reflection for V (vlang)
V
27
star
20

ok

🆗 - a strongly-duck-typed language.
Go
17
star
21

mocksqs

📤 In-memory implementation of SQS ideal for unit testing.
Go
12
star
22

sqlite3x

100% compatible sqlite3 fork with more features
C
10
star
23

gedcompare

Compare GEDCOM files
Python
9
star
24

go-named-params

Named parameters for Go functions
Go
9
star
25

testify-stats

🔢 testify: print test and assertions statistics at the end of the test suite
Go
7
star
26

independentreserve

💸 PHP API for independentreserve.com
PHP
6
star
27

tesseract

🔳 tesseract is a SQL object database with Redis as the backend, think of it like a document store that you run SQL statements against.
Python
6
star
28

GoogleMusicClient

🎶 Google Music Client in Objective-C
Objective-C
6
star
29

tui

🎨 Simple Go library for building complex text user interfaces
Go
5
star
30

wikitranslate

Easier translation of Wikipedia pages with CAT tools.
Go
5
star
31

multiselector

Multi Selector for Paw
JavaScript
4
star
32

iterator

Iterator builders for PHP
PHP
4
star
33

postgresql-partitioning

🖖 Automatic tools for managing partitions
4
star
34

switch-check

Validate switch statements contain all enum values.
Go
4
star
35

jsonrpc

💬 Simple JSON-RPC server for Go
Go
3
star
36

vscode-ok

Language highlighting for the ok programming language in VSCode
2
star
37

tracklist-editor

A tool for editing track lists
JavaScript
2
star
38

sql2mql

☕ Pure coffeescript SQL to MongoDB statement parser.
CoffeeScript
2
star
39

eagle

🦅 Eagle is a highly parallel column-oriented embedded SQL database engine.
C
2
star
40

chartbrainz

The unofficial way to view charts from MusicBrainz.
Vue
2
star
41

Z

🇿Java to native C compiler.
Java
2
star
42

Hoard

🐿️ A PSR-compliant caching library for holding objects in nested pools with scripting ability.
PHP
2
star
43

Sentinel

Non-blocking Java web server.
Java
2
star
44

dandy

🔬 The handy, dandy test generation tool for Go.
Go
2
star
45

play.getok.dev

🕹️ play.getok.dev
HTML
1
star
46

Pluralizer

Objective-C Library/Cocoa Pod for Simple String Pluralization
Objective-C
1
star
47

maven

⚚ maven programming language
C++
1
star
48

csv

Reading and writing CSV files in OK.
1
star
49

delta

🔺 The fastest scripting language on the planet based on PHP (pre-alpha)
C
1
star
50

construe

Language conversion and maintaining tool.
CoffeeScript
1
star
51

toy

🧸 A toy language
JavaScript
1
star
52

EagleDB

🐦 Concept column-oriented MVCC SQL daemon.
Java
1
star
53

intuit-quickbooks

The PHP SDK for QuickBooks v3 is set of PHP classes that make it easier to call QuickBooks APIs.
PHP
1
star
54

independentreserve-python

Python API for independentreserve.com
1
star
55

codekata.io

Online and realtime Kata for TDD
PHP
1
star
56

rateyourmusic-todo

Discussion and queue for entities that need editing help
1
star