Objx - Go package for dealing with maps, slices, JSON and other data.
Get started:
- Install Objx with [one line of code](#installation), or [update it with another](#staying-up-to-date)
- Check out the API Documentation http://godoc.org/github.com/stretchr/objx
## Overview
Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes a powerful `Get` method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc.
### Pattern
Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy. Call one of the `objx.` functions to create your `objx.Map` to get going:
m, err := objx.FromJSON(json)
NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, the rest will be optimistic and try to figure things out without panicking.
Use `Get` to access the value you're interested in. You can use dot and array
notation too:
m.Get("places[0].latlng")
Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type.
if m.Get("code").IsStr() { // Your code... }
Or you can just assume the type, and use one of the strong type methods to extract the real value:
m.Get("code").Int()
If there's no value there (or if it's the wrong type) then a default value will be returned, or you can be explicit about the default value.
Get("code").Int(-1)
If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, manipulating and selecting that data. You can find out more by exploring the index below.
### Reading data
A simple example of how to use Objx:
// Use MustFromJSON to make an objx.Map from some JSON
m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)
// Get the details
name := m.Get("name").Str()
age := m.Get("age").Int()
// Get their nickname (or use their name if they don't have one)
nickname := m.Get("nickname").Str(name)
### Ranging
Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For example, to `range` the data, do what you would expect:
m := objx.MustFromJSON(json)
for key, value := range m {
// Your code...
}
## Installation
To install Objx, use go get:
go get github.com/stretchr/objx
### Staying up to date
To update Objx to the latest version, run:
go get -u github.com/stretchr/objx
### Supported go versions
We support the lastest three major Go versions, which are 1.9, 1.10 and 1.11 at the moment.
## Contributing
Please feel free to submit issues, fork the repository and send pull requests!
The `assert` package provides some helpful methods that allow you to write better test code in Go.
* Prints friendly, easy to read failure descriptions
* Allows for very readable code
* Optionally annotate each assertion with a message
See it in action:
```go
packageyours
import(
"testing"
"github.com/stretchr/testify/assert"
)
funcTestSomething(t*testing.T){
// assert equality
assert.Equal(t,123,123,"they should be equal")
// assert inequality
assert.NotEqual(t,123,456,"they should not be equal")
// assert for nil (good for errors)
assert.Nil(t,object)
// assert for not nil (good when you expect something)
ifassert.NotNil(t,object){
// now we know that object isn't nil, we are safe to make
// further assertions without causing any errors
assert.Equal(t,"Something",object.Value)
}
}
```
* Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities.
* Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions.
if you assert many times, use the below:
```go
packageyours
import(
"testing"
"github.com/stretchr/testify/assert"
)
funcTestSomething(t*testing.T){
assert:=assert.New(t)
// assert equality
assert.Equal(123,123,"they should be equal")
// assert inequality
assert.NotEqual(123,456,"they should not be equal")
// assert for nil (good for errors)
assert.Nil(object)
// assert for not nil (good when you expect something)
ifassert.NotNil(object){
// now we know that object isn't nil, we are safe to make
The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.
An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened:
```go
packageyours
import(
"testing"
"github.com/stretchr/testify/mock"
)
/*
Test objects
*/
// MyMockedObject is a mocked object that implements an interface
// that describes an object that the code I am testing relies on.
typeMyMockedObjectstruct{
mock.Mock
}
// DoSomething is a method on MyMockedObject that implements some interface
// and just records the activity, and returns what the Mock object tells it to.
//
// In the real object, this method would do something useful, but since this
// is a mocked object - we're just going to stub it out.
//
// NOTE: This method is not being tested here, code that uses this object is.
For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock).
You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker.
The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.
An example suite is shown below:
```go
// Basic imports
import(
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
// Define the suite, and absorb the built-in basic suite
// functionality from testify - including a T() method which
// returns the current testing context
typeExampleTestSuitestruct{
suite.Suite
VariableThatShouldStartAtFiveint
}
// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func(suite*ExampleTestSuite)SetupTest(){
suite.VariableThatShouldStartAtFive=5
}
// All methods that begin with "Test" are run as tests within a
// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
funcTestExampleTestSuite(t*testing.T){
suite.Run(t,new(ExampleTestSuite))
}
```
For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go)
For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite).
`Suite` object has assertion methods:
```go
// Basic imports
import(
"testing"
"github.com/stretchr/testify/suite"
)
// Define the suite, and absorb the built-in basic suite
// functionality from testify - including assertion methods.
typeExampleTestSuitestruct{
suite.Suite
VariableThatShouldStartAtFiveint
}
// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func(suite*ExampleTestSuite)SetupTest(){
suite.VariableThatShouldStartAtFive=5
}
// All methods that begin with "Test" are run as tests within a
// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
funcTestExampleTestSuite(t*testing.T){
suite.Run(t,new(ExampleTestSuite))
}
```
------
Installation
============
To install Testify, use `go get`:
go get github.com/stretchr/testify
This will then make the following packages available to you:
github.com/stretchr/testify/assert
github.com/stretchr/testify/mock
github.com/stretchr/testify/http
Import the `testify/assert` package into your code using this template:
```go
packageyours
import(
"testing"
"github.com/stretchr/testify/assert"
)
funcTestSomething(t*testing.T){
assert.True(t,true,"True is true!")
}
```
------
Staying up to date
==================
To update Testify to the latest version, use `go get -u github.com/stretchr/testify`.
------
Supported go versions
==================
We support the three major Go versions, which are 1.9, 1.10, and 1.11 at the moment.
------
Contributing
============
Please feel free to submit issues, fork the repository and send pull requests!
When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it.
------
License
=======
This project is licensed under the terms of the MIT license.
// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.
// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.
// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.
// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.
// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.
// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.
// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
//
// \t{{label}}:{{align_spaces}}\t{{content}}\n
//
// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
// alignment is achieved, "\t{{content}}\n" is added for the output.
//
// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
returnFail(t,fmt.Sprintf("Should not be zero, but was %v",i),msgAndArgs...)
}
returntrue
}
// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.
returnFail(t,fmt.Sprintf("unable to find file %q",path),msgAndArgs...)
}
returnFail(t,fmt.Sprintf("error when running os.Lstat(%q): %s",path,err),msgAndArgs...)
}
ifinfo.IsDir(){
returnFail(t,fmt.Sprintf("%q is a directory",path),msgAndArgs...)
}
returntrue
}
// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.
// Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend.
//
// testify contains the following packages:
//
// The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system.
//
// The http package contains tools to make it easier to test http activity using the Go testing system.
//
// The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected.
//
// The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces.
m.fail("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s",methodName,methodName,callString(methodName,arguments,true),assert.CallerInfo())
t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s",len(expectedCalls)-failedExpectations,len(expectedCalls),failedExpectations,assert.CallerInfo())
}
return!somethingMissing
}
// AssertNumberOfCalls asserts that the method was called expectedCalls times.
returnassert.Equal(t,expectedCalls,actualCalls,fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).",expectedCalls,actualCalls))
}
// AssertCalled asserts that the method was called.
// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method.