本文整理汇总了Golang中github.com/stretchr/testify/assert.JSONEq函数的典型用法代码示例。如果您正苦于以下问题:Golang JSONEq函数的具体用法?Golang JSONEq怎么用?Golang JSONEq使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了JSONEq函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestMarshallAuthor
func TestMarshallAuthor(t *testing.T) {
a := &entity.Author{
ID: 13,
Ordering: 65,
Name: "Tilo Jung",
Title: "Politik",
URL: "/13--tilo-jung",
Biography: "Tilo Jung",
SocialMedia: "TWITTER | FACEBOOK",
CreatedAt: time.Date(2016, 06, 05, 22, 32, 0, 0, time.UTC),
UpdatedAt: time.Date(2016, 06, 05, 22, 32, 0, 0, time.UTC),
}
b, err := json.Marshal(Author(a))
assert.Nil(t, err)
assert.JSONEq(
t,
`{"data":{"id":13,"order":65,"name":"Tilo Jung","title":"Politik","url":"https://krautreporter.de/13--tilo-jung","biography":"Tilo Jung","socialmedia":"TWITTER | FACEBOOK","created_at":"2016-06-05T22:32:00Z","updated_at":"2016-06-05T22:32:00Z","images":null}}`,
string(b),
)
a.Images = append(a.Images, entity.Image{ID: 123, Width: 256, Src: "/foo.jpg"})
b, err = json.Marshal(Author(a))
assert.Nil(t, err)
assert.JSONEq(
t,
`{"data":{"id":13,"order":65,"name":"Tilo Jung","title":"Politik","url":"https://krautreporter.de/13--tilo-jung","biography":"Tilo Jung","socialmedia":"TWITTER | FACEBOOK","created_at":"2016-06-05T22:32:00Z","updated_at":"2016-06-05T22:32:00Z","images":{"data":[{"id":123,"width":256,"src":"https://krautreporter.de/foo.jpg"}]}}}`,
string(b),
)
}
示例2: TestMarshallArticle
func TestMarshallArticle(t *testing.T) {
a := &entity.Article{
ID: 123,
Ordering: 10,
Title: "Title",
Headline: "Headline",
Preview: true,
URL: "/123--article",
Excerpt: "foo",
Content: "bar",
AuthorID: 13,
}
b, err := json.Marshal(Article(a))
assert.Nil(t, err)
assert.JSONEq(
t,
`{"data":{"id":123,"order":10,"title":"Title","headline":"Headline","date":"0001-01-01T00:00:00Z","morgenpost":false,"preview":true,"url":"https://krautreporter.de/123--article","excerpt":"foo","content":"bar","created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","author_id":13,"images":null}}`,
string(b),
)
a.Images = append(a.Images, entity.Image{ID: 123, Width: 256, Src: "/foo.jpg"})
b, err = json.Marshal(Article(a))
assert.Nil(t, err)
assert.JSONEq(
t,
`{"data":{"id":123,"order":10,"title":"Title","headline":"Headline","date":"0001-01-01T00:00:00Z","morgenpost":false,"preview":true,"url":"https://krautreporter.de/123--article","excerpt":"foo","content":"bar","created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","author_id":13,"images":{"data":[{"id":123,"width":256,"src":"https://krautreporter.de/foo.jpg"}]}}}`,
string(b),
)
}
示例3: TestImage
func TestImage(t *testing.T) {
i := []entity.Image{}
b, err := json.Marshal(Images(i))
assert.Nil(t, err)
assert.JSONEq(t, `{"data":null}`, string(b))
i = append(i, entity.Image{ID: 123, Width: 256, Src: "/foo.jpg"})
b, err = json.Marshal(Images(i))
assert.Nil(t, err)
assert.JSONEq(t, `{"data":[{"id":123,"width":256,"src":"https://krautreporter.de/foo.jpg"}]}`, string(b))
}
示例4: TestCreateIRule
func (s *LTMTestSuite) TestCreateIRule() {
s.Client.CreateIRule("rule1", `when CLIENT_ACCEPTED { log local0. "test"}`)
assert.Equal(s.T(), fmt.Sprintf("/mgmt/tm/%s", uriRule), s.LastRequest.URL.Path)
assert.Equal(s.T(), "POST", s.LastRequest.Method)
assert.JSONEq(s.T(), `{"name":"rule1","apiAnonymous":"when CLIENT_ACCEPTED { log local0. \"test\"}"}`, s.LastRequestBody)
}
示例5: TestModifyIRule
func (s *LTMTestSuite) TestModifyIRule() {
s.Client.ModifyIRule("rule1", &IRule{Rule: "modified"})
assert.Equal(s.T(), fmt.Sprintf("/mgmt/tm/%s/%s", uriRule, "rule1"), s.LastRequest.URL.Path)
assert.Equal(s.T(), "PUT", s.LastRequest.Method)
assert.JSONEq(s.T(), `{"name":"rule1","apiAnonymous":"modified"}`, s.LastRequestBody)
}
示例6: TestWriteLog
// Looking at the gorilla/mux CombinedLoggingHandler, the only test is for the WriteCombinedLog function, so doing the same here
// (this test inspired by their test)
func TestWriteLog(t *testing.T) {
assert := assert.New(t)
now := time.Now().Format(time.RFC3339)
resptime := time.Millisecond * 123
// A typical request with an OK response
req, err := http.NewRequest("GET", "http://example.com", nil)
req.RemoteAddr = "192.168.100.11"
req.Header.Set("Referer", "http://example.com")
req.Header.Set("User-Agent", "User agent")
logger := log.New()
buf := new(bytes.Buffer)
logger.Out = buf
logger.Formatter = new(log.JSONFormatter)
writeRequestLog(logger, req, knownTransactionID, *req.URL, resptime, http.StatusOK, 100)
var fields log.Fields
err = json.Unmarshal(buf.Bytes(), &fields)
assert.NoError(err, "Could not unmarshall")
expected := fmt.Sprintf(`{"host":"192.168.100.11",
"level":"info","method":"GET","msg":"","protocol":"HTTP/1.1",
"referer":"http://example.com","responsetime":%d,"size":100,"status":200,
"time":"%s", "transaction_id":"KnownTransactionId",
"uri":"/","userAgent":"User agent","username":"-"}`, int64(resptime.Seconds()*1000), now)
assert.JSONEq(expected, buf.String(), "Log format didn't match")
}
示例7: TestConvertWithNewLines
func TestConvertWithNewLines(t *testing.T) {
assert := assert.New(t)
s := `<?xml version="1.0" encoding="UTF-8"?>
<osm>
<foo>
foo
bar
</foo>
</osm>`
// Build SimpleJSON
json, err := sj.NewJson([]byte(`{
"osm": {
"foo": "foo\n\n\t\tbar"
}
}`))
assert.NoError(err)
expected, err := json.MarshalJSON()
assert.NoError(err)
// Then encode it in JSON
res, err := Convert(strings.NewReader(s))
assert.NoError(err)
// Assertion
assert.JSONEq(string(expected), res.String(), "Drumroll")
}
示例8: TestJobsProperties
func TestJobsProperties(t *testing.T) {
assert := assert.New(t)
workDir, err := os.Getwd()
assert.NoError(err)
ntpReleasePath := filepath.Join(workDir, "../test-assets/ntp-release")
ntpReleasePathBoshCache := filepath.Join(ntpReleasePath, "bosh-cache")
release, err := NewDevRelease(ntpReleasePath, "", "", ntpReleasePathBoshCache)
assert.NoError(err)
assert.Len(release.Jobs, 1)
lightOpinionsPath := filepath.Join(workDir, "../test-assets/ntp-opinions/opinions.yml")
darkOpinionsPath := filepath.Join(workDir, "../test-assets/ntp-opinions/dark-opinions.yml")
opinions, err := newOpinions(lightOpinionsPath, darkOpinionsPath)
assert.NoError(err)
properties, err := release.Jobs[0].getPropertiesForJob(opinions)
assert.Len(properties, 2)
actualJSON, err := json.Marshal(properties)
if assert.NoError(err) {
assert.JSONEq(`{
"ntp_conf" : "zip.conf",
"with": {
"json": {
"default": { "key": "value" }
}
}
}`, string(actualJSON), "Unexpected properties")
}
}
示例9: TestMarshallImage
func TestMarshallImage(t *testing.T) {
i := entity.Image{ID: 123, Width: 256, Src: "/foo.jpg"}
b, err := json.Marshal(marshallImage(i))
assert.Nil(t, err)
assert.JSONEq(t, `{"id":123,"width":256,"src":"https://krautreporter.de/foo.jpg"}`, string(b))
}
示例10: assertRestCall
func assertRestCall(s *NetTestSuite, method, path, body string) {
assert.Equal(s.T(), method, s.LastRequest.Method)
assert.Equal(s.T(), path, s.LastRequest.URL.Path)
if body != "" {
assert.JSONEq(s.T(), body, s.LastRequestBody)
}
}
示例11: TestGrantAndRevokeChannelLevelSubscribe
func TestGrantAndRevokeChannelLevelSubscribe(t *testing.T) {
assert := assert.New(t)
stop, sleep := NewVCRNonSubscribe(
"fixtures/pam/grantAndRevokeChannelLevelSubscribe",
[]string{"uuid", "signature", "timestamp"})
defer stop()
pubnubInstance := messaging.NewPubnub(PamPubKey, PamSubKey, PamSecKey, "", false, "")
channel := "testChannelGrantAndRevokeChannelLevelSubscribe"
ttl := 8
message := fmt.Sprintf(`{"status":200,"service":"Access Manager","message":"Success","payload":{"channels":{"%s":{"r":1,"m":0,"w":1}},"subscribe_key":"%s","ttl":%d,"level":"channel"}}`, channel, PamSubKey, ttl)
message2 := fmt.Sprintf(`{"status":200,"service":"Access Manager","message":"Success","payload":{"channels":{"%s":{"r":0,"m":0,"w":0}},"subscribe_key":"%s","ttl":%d,"level":"channel"}}`, channel, PamSubKey, 1)
successChannel := make(chan []byte)
errorChannel := make(chan []byte)
go pubnubInstance.GrantSubscribe(channel, true, true, ttl, "", successChannel, errorChannel)
select {
case resp := <-successChannel:
response := string(resp)
assert.JSONEq(message, response)
case err := <-errorChannel:
assert.Fail(string(err))
case <-timeout():
assert.Fail("GrantSubscribe Timeout")
}
successChannel2 := make(chan []byte)
errorChannel2 := make(chan []byte)
sleep(5)
go pubnubInstance.GrantSubscribe(channel, false, false, -1, "", successChannel2, errorChannel2)
select {
case resp := <-successChannel2:
response := string(resp)
assert.JSONEq(message2, response)
case err := <-errorChannel2:
assert.Fail(string(err))
case <-timeout():
assert.Fail("GrantSubscribe Timeout")
}
}
示例12: TestGetLogs
func TestGetLogs(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "logs")
defer os.RemoveAll(tempDir)
deploymentLogger := NewDeploymentLogManager(tempDir)
// test message formatting when have no log file
logs, err := deploymentLogger.GetLogs("non-existing-log-file")
assert.NoError(t, err)
assert.JSONEq(t, `{"messages":[]}`, string(logs))
// test message formating with correct log file
// add some content to the first file
logFileWithContent := path.Join(tempDir, fmt.Sprintf(logFileNameScheme, 1, "1111-2222"))
logContent := `{"msg":"test"}`
err = openLogFileWithContent(logFileWithContent, logContent)
assert.NoError(t, err)
// check if file really exists
_, err = deploymentLogger.findLogsForSpecificID("1111-2222")
assert.NoError(t, err)
logs, err = deploymentLogger.GetLogs("1111-2222")
assert.JSONEq(t, `{"messages":[{"msg":"test"}]}`, string(logs))
// test message formating with empty log file;
// below should create empty log file
deploymentLogger.Enable("1111-3333")
_, err = deploymentLogger.findLogsForSpecificID("1111-3333")
assert.NoError(t, err)
logs, err = deploymentLogger.GetLogs("1111-3333")
assert.JSONEq(t, `{"messages":[]}`, string(logs))
// test broken log entry
logFileWithContent = path.Join(tempDir, fmt.Sprintf(logFileNameScheme, 1, "1111-4444"))
logContent = `{"msg":"test"}
{"msg": "broken
{"msg": "test2"}`
err = openLogFileWithContent(logFileWithContent, logContent)
assert.NoError(t, err)
logs, err = deploymentLogger.GetLogs("1111-4444")
assert.JSONEq(t, `{"messages":[{"msg":"test"}, {"msg": "test2"}]}`, string(logs))
}
示例13: TestAuthorize
func TestAuthorize(t *testing.T) {
t.Parallel()
storageConfig := CreateStorageConfig("Authorize")
var err error
svc := createDynamoDB()
storage := New(svc, storageConfig)
err = storage.CreateSchema()
assert.Nil(t, err, "%s", err)
defer storage.DropSchema()
client := &osin.DefaultClient{
Id: "1234",
Secret: "aabbccdd",
}
err = storage.CreateClient(client)
assert.Nil(t, err, "%s", err)
authorizeData := &osin.AuthorizeData{
Client: client,
Code: "9999",
ExpiresIn: 3600,
RedirectUri: "/dev/null",
CreatedAt: time.Now(),
}
got, err := storage.LoadAuthorize(authorizeData.Code)
assert.Equal(t, ErrAuthorizeNotFound, err)
assert.Nil(t, got)
err = storage.SaveAuthorize(authorizeData)
assert.Nil(t, err, "%s", err)
got, err = storage.LoadAuthorize(authorizeData.Code)
// We need to convert it to json as pointers inside structs are different
// and assert library doesn't provide recursive value comparison for structs
assert.Nil(t, err, "%s", err)
gotJSON, err := json.Marshal(got)
assert.Nil(t, err, "%s", err)
expectedJSON, err := json.Marshal(authorizeData)
assert.Nil(t, err, "%s", err)
assert.JSONEq(t, string(expectedJSON), string(gotJSON))
err = storage.RemoveAuthorize(authorizeData.Code)
assert.Nil(t, err, "%s", err)
got, err = storage.LoadAuthorize(authorizeData.Code)
assert.Equal(t, ErrAuthorizeNotFound, err)
assert.Nil(t, got)
// let's try with expired token
authorizeData.CreatedAt = authorizeData.CreatedAt.Add(-time.Duration(authorizeData.ExpiresIn) * time.Second)
err = storage.SaveAuthorize(authorizeData)
assert.Nil(t, err, "%s", err)
got, err = storage.LoadAuthorize(authorizeData.Code)
assert.Equal(t, ErrTokenExpired, err)
assert.Nil(t, got)
}
示例14: TestMiddleware_ServeHTTP
func TestMiddleware_ServeHTTP(t *testing.T) {
mw, rec, req := setupServeHTTP(t)
mw.ServeHTTP(rec, req, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(418)
})
lines := strings.Split(strings.TrimSpace(mw.Logger.Out.(*bytes.Buffer).String()), "\n")
assert.Len(t, lines, 2)
assert.JSONEq(t,
fmt.Sprintf(`{"level":"info","method":"GET","msg":"started handling request",`+
`"remote":"10.10.10.10","request":"http://example.com/stuff?rly=ya",`+
`"request_id":"22035D08-98EF-413C-BBA0-C4E66A11B28D","time":"%s"}`, nowToday),
lines[0])
assert.JSONEq(t,
fmt.Sprintf(`{"level":"info","method":"GET","msg":"completed handling request",`+
`"remote":"10.10.10.10","request":"http://example.com/stuff?rly=ya",`+
`"measure#web.latency":10000,"took":10000,"text_status":"I'm a teapot",`+
`"status":418,"request_id":"22035D08-98EF-413C-BBA0-C4E66A11B28D","time":"%s"}`, nowToday),
lines[1])
}
示例15: equalJSONs
func equalJSONs(t assert.TestingT, exp, act interface{}) bool {
e, err := json.Marshal(exp)
if assert.NoError(t, err) {
return false
}
a, err := json.Marshal(act)
if assert.NoError(t, err) {
return false
}
return assert.JSONEq(t, string(e), string(a))
}