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),
	)
}
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),
	)
}
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))
}
Beispiel #4
0
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)
}
Beispiel #5
0
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)
}
// 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")
}
Beispiel #7
0
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")
}
Beispiel #8
0
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")
	}
}
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))
}
Beispiel #10
0
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)
	}
}
Beispiel #11
0
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")
	}
}
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))
}
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)
}
Beispiel #14
0
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])
}
Beispiel #15
0
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))
}
Beispiel #16
0
// fieldValidator returns a encoderValidator that will compare the JSON of v["properties"][fieldName] only, where v is a
// top-level JSONSchema object.
func fieldValidator(fieldName, expected string) encoderValidator {
	return func(t *testing.T, result []byte) {
		v := struct {
			Properties map[string]interface{} `json:"properties"`
		}{}
		err := json.Unmarshal(result, &v)
		assert.NoError(t, err, "Input ('%s') needs to be valid JSON", result)
		actual, err := json.Marshal(v.Properties[fieldName])
		assert.NoError(t, err)
		assert.JSONEq(t, expected, string(actual))
	}
}
Beispiel #17
0
func TestJSONHelperValidInput(t *testing.T) {
	assert := assert.New(t)

	testDataList := []jsonHelpInputTestData{
		jsonHelpInputTestData{
			name: "Simple number input",
			yaml: `1`,
			json: `1`,
		},
		jsonHelpInputTestData{
			name: "Simple map",
			yaml: `a: 1`,
			json: `{"a": 1}`,
		},
		jsonHelpInputTestData{
			name: "Nested map",
			yaml: `a: { b: c }`,
			json: `{"a": {"b": "c"}}`,
		},
		jsonHelpInputTestData{
			name: "Map in slice",
			yaml: `[ { a: b } ]`,
			json: `[ {"a": "b" } ]`,
		},
		jsonHelpInputTestData{
			name:   "Map with non-string keys",
			yaml:   `1: 2`,
			errMsg: `Failed to convert keys in path : Invalid key 1`,
		},
		jsonHelpInputTestData{
			name:   "Nested map with non-string keys",
			yaml:   `a: { b: { 1: 2 } }`,
			errMsg: `Failed to convert keys in path a.b: Invalid key 1`,
		},
	}

	for _, testData := range testDataList {
		var unmarshaled interface{}
		err := yaml.Unmarshal([]byte(testData.yaml), &unmarshaled)
		if !assert.NoError(err, "Failed to unmarshal YAML data for test sample %s", testData.name) {
			continue
		}
		result, err := JSONMarshal(unmarshaled)
		if testData.errMsg != "" {
			assert.Error(err, "Exepected test sample %s to result in an error", testData.name)
			assert.Contains(err.Error(), testData.errMsg, "Error message did not contain expected string for test sample %s", testData.name)
		} else {
			if assert.NoError(err, "Unexpected error for test sample %s", testData.name) {
				assert.JSONEq(testData.json, string(result), "Unexpected result for test sample %s", testData.name)
			}
		}
	}
}
Beispiel #18
0
func TestStatusClient(t *testing.T) {
	responder := &struct {
		httpStatus int
		recdata    []byte
		path       string
	}{
		http.StatusNoContent, // 204
		[]byte{},
		"",
	}

	// Test server that always responds with 200 code, and specific payload
	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(responder.httpStatus)

		responder.recdata, _ = ioutil.ReadAll(r.Body)
		responder.path = r.URL.Path
	}))
	defer ts.Close()

	ac, err := NewApiClient(
		Config{"client.crt", "client.key", "server.crt", true, false},
	)
	assert.NotNil(t, ac)
	assert.NoError(t, err)

	client := NewStatus()
	assert.NotNil(t, client)

	err = client.Report(NewMockApiClient(nil, errors.New("foo")),
		ts.URL,
		StatusReport{
			DeploymentID: "deployment1",
			Status:       StatusFailure,
		})
	assert.Error(t, err)

	err = client.Report(ac, ts.URL, StatusReport{
		DeploymentID: "deployment1",
		Status:       StatusFailure,
	})
	assert.NoError(t, err)
	assert.NotNil(t, responder.recdata)
	assert.JSONEq(t, `{"status": "failure"}`, string(responder.recdata))
	assert.Equal(t, apiPrefix+"deployments/device/deployments/deployment1/status", responder.path)

	responder.httpStatus = 401
	err = client.Report(ac, ts.URL, StatusReport{
		DeploymentID: "deployment1",
		Status:       StatusSuccess,
	})
	assert.Error(t, err)
}
func TestInventoryClient(t *testing.T) {
	responder := &struct {
		httpStatus int
		recdata    []byte
		path       string
	}{
		http.StatusOK,
		[]byte{},
		"",
	}

	// Test server that always responds with 200 code, and specific payload
	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(responder.httpStatus)

		responder.recdata, _ = ioutil.ReadAll(r.Body)
		responder.path = r.URL.Path
	}))
	defer ts.Close()

	ac, err := NewApiClient(
		Config{"client.crt", "client.key", "server.crt", true, false},
	)
	assert.NotNil(t, ac)
	assert.NoError(t, err)

	client := NewInventory()
	assert.NotNil(t, client)

	err = client.Submit(NewMockApiClient(nil, errors.New("foo")),
		ts.URL,
		InventoryData{
			{"foo", "bar"},
		})
	assert.Error(t, err)

	err = client.Submit(ac, ts.URL, InventoryData{
		{"foo", "bar"},
		{"bar", []string{"baz", "zen"}},
	})
	assert.NoError(t, err)
	assert.NotNil(t, responder.recdata)
	assert.JSONEq(t,
		`[{"name": "foo", "value": "bar"},{"name": "bar", "value": ["baz", "zen"]}]`,
		string(responder.recdata))
	assert.Equal(t, apiPrefix+"inventory/device/attributes", responder.path)

	responder.httpStatus = 401
	err = client.Submit(ac, ts.URL, nil)
	assert.Error(t, err)
}
func TestGetHandler(t *testing.T) {
	assert := assert.New(t)
	tests := []test{
		{"Success", newRequest("GET", fmt.Sprintf("/content/%s/annotations", knownUUID), "application/json", nil), dummyService{contentUUID: knownUUID}, http.StatusOK, "", "[]"},
		{"NotFound", newRequest("GET", fmt.Sprintf("/content/%s/annotations", "99999"), "application/json", nil), dummyService{contentUUID: knownUUID}, http.StatusNotFound, "", message("No annotations found for content with uuid 99999.")},
		{"ReadError", newRequest("GET", fmt.Sprintf("/content/%s/annotations", knownUUID), "application/json", nil), dummyService{contentUUID: knownUUID, failRead: true}, http.StatusServiceUnavailable, "", message("Error getting annotations (TEST failing to READ)")},
	}

	for _, test := range tests {
		rec := httptest.NewRecorder()
		router(httpHandlers{test.dummyService}).ServeHTTP(rec, test.req)
		assert.True(test.statusCode == rec.Code, fmt.Sprintf("%s: Wrong response code, was %d, should be %d", test.name, rec.Code, test.statusCode))
		assert.JSONEq(test.body, rec.Body.String(), fmt.Sprintf("%s: Wrong body", test.name))
	}
}
Beispiel #21
0
func (tc *encoderTestCase) Run(t *testing.T) {
	t.Run(tc.name, func(t *testing.T) {
		t.Parallel()

		b := new(bytes.Buffer)
		enc := jsonschema.NewEncoder(b)
		assert.NoError(t, enc.Encode(&tc.schema))

		if tc.customValidate == nil {
			assert.JSONEq(t, tc.expect, b.String())
		} else {
			tc.customValidate(t, b.Bytes())
		}
	})
}
Beispiel #22
0
func TestMiddleware_ServeHTTP_AfterOverride(t *testing.T) {
	mw, rec, req := setupServeHTTP(t)
	mw.After = func(entry *logrus.Entry, _ negroni.ResponseWriter, _ time.Duration, _ string) *logrus.Entry {
		return entry.WithFields(logrus.Fields{"hambone": 57})
	}
	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(`{"hambone":57,"level":"info","method":"GET","msg":"completed 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[1])
}
Beispiel #23
0
func TestMiddleware_ServeHTTP_BeforeOverride(t *testing.T) {
	mw, rec, req := setupServeHTTP(t)
	mw.Before = func(entry *logrus.Entry, _ *http.Request, _ string) *logrus.Entry {
		return entry.WithFields(logrus.Fields{"wat": 200})
	}
	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(`{"wat":200,"level":"info","msg":"completed handling request",`+
			`"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])
}
func TestMarshallAuthors(t *testing.T) {
	authors := []*entity.Author{{
		ID:       1,
		Ordering: 1,
	}, {
		ID:       2,
		Ordering: 0,
	}}

	b, err := json.Marshal(Authors(authors))
	assert.Nil(t, err)
	assert.JSONEq(
		t,
		`{"data":[{"id":1,"order":1,"name":"","title":"","url":"https://krautreporter.de","biography":"","socialmedia":"","created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","images":null},{"id":2,"order":0,"name":"","title":"","url":"https://krautreporter.de","biography":"","socialmedia":"","created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","images":null}]}`,
		string(b),
	)
}
Beispiel #25
0
func TestHandleInterfaceEmptySuccess(t *testing.T) {
	h := func(ctx context.Context, _ yarpc.ReqMeta, body interface{}) (interface{}, yarpc.ResMeta, error) {
		return body, nil, nil
	}

	handler := jsonHandler{reader: ifaceEmptyReader{}, handler: reflect.ValueOf(h)}

	resw := new(transporttest.FakeResponseWriter)
	err := handler.Handle(context.Background(), &transport.Request{
		Procedure: "foo",
		Encoding:  "json",
		Body:      jsonBody(`["a", "b", "c"]`),
	}, resw)
	require.NoError(t, err)

	assert.JSONEq(t, `["a", "b", "c"]`, resw.Body.String())
}
func TestMarshallArticles(t *testing.T) {
	articles := []*entity.Article{{
		ID:       1,
		Ordering: 1,
	}, {
		ID:       2,
		Ordering: 0,
	}}

	b, err := json.Marshal(Articles(articles))
	assert.Nil(t, err)
	assert.JSONEq(
		t,
		`{"data":[{"id":1,"order":1,"title":"","headline":"","date":"0001-01-01T00:00:00Z","morgenpost":false,"preview":false,"url":"https://krautreporter.de","excerpt":"","content":"","created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","author_id":0,"images":null},{"id":2,"order":0,"title":"","headline":"","date":"0001-01-01T00:00:00Z","morgenpost":false,"preview":false,"url":"https://krautreporter.de","excerpt":"","content":"","created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","author_id":0,"images":null}]}`,
		string(b),
	)
}
Beispiel #27
0
func TestGrantChannelLevelSubscribeWithAuth(t *testing.T) {
	assert := assert.New(t)

	stop, _ := NewVCRNonSubscribe(
		"fixtures/pam/grantChannelLevelSubscribeWithAuth",
		[]string{"uuid", "signature", "timestamp"})
	defer stop()

	pubnubInstance := messaging.NewPubnub(PamPubKey, PamSubKey, PamSecKey, "", false, "")
	channel := "testGrantChannelLevelSubscribeWithAuth"
	authKey := "myAuthKey"

	ttl := 1
	expected := fmt.Sprintf(`{
		"auths":{"%s":{"r":1,"m":0,"w":1}},
		"channel":"%s",
		"level":"user",
		"ttl":%d,
		"subscribe_key":"%s"
	}`, authKey, channel, ttl, PamSubKey)

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.GrantSubscribe(channel, true, true, ttl, authKey, successChannel, errorChannel)
	select {
	case resp := <-successChannel:
		var response PamResponse
		err := json.Unmarshal(resp, &response)
		if err != nil {
			assert.Fail(err.Error())
		}

		payload, err := json.Marshal(response.Payload)
		if err != nil {
			assert.Fail(err.Error())
		}

		assert.JSONEq(expected, string(payload))
	case err := <-errorChannel:
		assert.Fail(string(err))
	case <-timeout():
		assert.Fail("GrantSubscribe Timeout")
	}
}
Beispiel #28
0
func (s *LTMTestSuite) TestCreateVitualAddress() {

	s.Client.CreateVirtualAddress("test-va", &VirtualAddress{Address: "10.10.10.10", ARP: true, AutoDelete: false})

	assert.Equal(s.T(), "POST", s.LastRequest.Method)
	assert.Equal(s.T(), fmt.Sprintf("/mgmt/tm/%s/%s", uriLtm, uriVirtualAddress), s.LastRequest.URL.Path)
	assert.JSONEq(s.T(), `
	{"name":"test-va",
	"arp":"enabled",
	"autoDelete":"false",
	"address" : "10.10.10.10",
	"enabled":"no",
	"floating":"disabled",
	"icmpEcho":"disabled",
	"inheritedTrafficGroup":"no",
	"routeAdvertisement":"disabled"}`, s.LastRequestBody)

}
Beispiel #29
0
func TestConvertWithMixedTags(t *testing.T) {
	assert := assert.New(t)

	s := `<?xml version="1.0" encoding="UTF-8"?>
	<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
	    <soap-env:Header>
	        <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext">
	            <wsse:BinarySecurityToken valueType="String" EncodingType="wsse:Base64Binary">
	                Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/ACPCRTC!ICESMSLB\/CRT.LB!-3379045898978075261!1563026!0
	            </wsse:BinarySecurityToken>
	        </wsse:Security>
	    </soap-env:Header>
	</soap-env:Envelope> `

	// Build SimpleJSON
	json, err := sj.NewJson([]byte(`{
	  "Envelope": {
	    "Header": {
	      "Security": {
	        "-wsse": "http://schemas.xmlsoap.org/ws/2002/12/secext",
	        "BinarySecurityToken": {
	          "#content": "Shared/IDL:IceSess\\/SessMgr:1\\.0.IDL/Common/!ICESMS\\/ACPCRTC!ICESMSLB\\/CRT.LB!-3379045898978075261!1563026!0",
	          "-EncodingType": "wsse:Base64Binary",
	          "-valueType": "String"
	        }
	      }
	    },
	    "-soap-env": "http://schemas.xmlsoap.org/soap/envelope/"
	  }
	}`))
	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")
}
func TestPutHandler(t *testing.T) {
	assert := assert.New(t)
	body, err := ioutil.ReadFile("annotations/examplePutBody.json")
	assert.NoError(err, "Unexpected error")
	invalidBody := []byte(`{"id": "1234"}`)
	missingConceptIDBody := []byte(`"{"thing": {"prefLabel": "Apple"}`)
	tests := []test{
		{"Success", newRequest("PUT", fmt.Sprintf("/content/%s/annotations", knownUUID), "application/json", body), dummyService{contentUUID: knownUUID}, http.StatusCreated, "application/json", message("Annotations for content 12345 created")},
		{"ParseError", newRequest("PUT", fmt.Sprintf("/content/%s/annotations", knownUUID), "application/json", invalidBody), dummyService{contentUUID: knownUUID, failParse: true}, http.StatusBadRequest, "application/json", message("Error (TEST failing to DECODE) parsing annotation request")},
		{"ValidationError", newRequest("PUT", fmt.Sprintf("/content/%s/annotations", knownUUID), "application/json", missingConceptIDBody), dummyService{contentUUID: knownUUID, failValidation: true}, http.StatusBadRequest, "application/json", message("Error creating annotations (TEST failing validation)")},
		{"NotJson", newRequest("PUT", fmt.Sprintf("/content/%s/annotations", knownUUID), "text/html", body), dummyService{contentUUID: knownUUID}, http.StatusBadRequest, "application/json", message("Http Header 'Content-Type' is not 'application/json', this is a JSON API")},
		{"WriteFailed", newRequest("PUT", fmt.Sprintf("/content/%s/annotations", knownUUID), "application/json", body), dummyService{contentUUID: knownUUID, failWrite: true}, http.StatusServiceUnavailable, "application/json", message("Error creating annotations (TEST failing to WRITE)")},
	}

	for _, test := range tests {
		rec := httptest.NewRecorder()
		router(httpHandlers{test.dummyService}).ServeHTTP(rec, test.req)
		assert.True(test.statusCode == rec.Code, fmt.Sprintf("%s: Wrong response code, was %d, should be %d", test.name, rec.Code, test.statusCode))
		assert.JSONEq(test.body, rec.Body.String(), fmt.Sprintf("%s: Wrong body", test.name))
	}
}