Esempio n. 1
0
func TestTokenProxier(t *testing.T) {
	a := New(t)

	hdl := &testHandler{}
	p := WithToken(hdl)

	req := httptest.NewRequest("GET", "/uri", bytes.NewBuffer([]byte{}))
	p.ServeHTTP(httptest.NewRecorder(), req)
	a.So(hdl.req.Header.Get("Grpc-Metadata-Token"), ShouldBeEmpty)

	req = httptest.NewRequest("GET", "/uri", bytes.NewBuffer([]byte{}))
	req.Header.Add("Authorization", "Key blabla")
	p.ServeHTTP(httptest.NewRecorder(), req)
	a.So(hdl.req.Header.Get("Grpc-Metadata-Token"), ShouldBeEmpty)

	req = httptest.NewRequest("GET", "/uri", bytes.NewBuffer([]byte{}))
	req.Header.Add("Authorization", "bearer token")
	p.ServeHTTP(httptest.NewRecorder(), req)
	a.So(hdl.req.Header.Get("Grpc-Metadata-Token"), ShouldEqual, "token")

	req = httptest.NewRequest("GET", "/uri", bytes.NewBuffer([]byte{}))
	req.Header.Add("Authorization", "Bearer token")
	p.ServeHTTP(httptest.NewRecorder(), req)
	a.So(hdl.req.Header.Get("Grpc-Metadata-Token"), ShouldEqual, "token")
}
Esempio n. 2
0
// TestActionsPOST sample test for the POST call.
func TestActionsPOST(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to test POST action call.")
	{
		action := "flagged_by"
		userID := "ITEST_80aa936a-f618-4234-a7be-df59a14cf8de"
		itemID := "ITEST_d16790f8-13e9-4cb4-b9ef-d82835589660"
		url := fmt.Sprintf("/v1/action/%s/user/%s/on/item/%s", action, userID, itemID)
		r := httptest.NewRequest("POST", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			t.Log("\tWhen we use version v1 of the actions endpoint.")

			if w.Code != http.StatusOK {
				t.Fatalf("\t%s\tShould be able to add the action : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to add the action.", tests.Success)
		}
	}

	t.Log("Given the need to test a wrong POST action call.")
	{
		action := "flagged_by"
		userID := "ITEST_80aa936a-f618-4234-a7be-df59a14cf8de"
		itemID := "wrongitem"
		url := fmt.Sprintf("/v1/action/%s/user/%s/on/item/%s", action, userID, itemID)
		r := httptest.NewRequest("POST", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			t.Log("\tWhen we use version v1 of the actions endpoint.")

			if w.Code != http.StatusInternalServerError {
				t.Fatalf("\t%s\tShould fail on finding the target : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould fail on finding the target.", tests.Success)
		}
	}

}
Esempio n. 3
0
// TestMaskByName tests the retrieval of a specific mask.
func TestMaskByName(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to get a specific mask.")
	{
		url := "/v1/mask/" + mCollection + "/observation_time"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			if w.Code != 200 {
				t.Fatalf("\t%s\tShould be able to retrieve the mask : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the mask.", tests.Success)

			var msk mask.Mask
			if err := json.Unmarshal(w.Body.Bytes(), &msk); err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the results : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the results.", tests.Success)

			if msk.Collection != mCollection && msk.Field != "observation_time" {
				t.Fatalf("\t%s\tShould have the correct mask : %s - %s", tests.Failed, msk.Collection, msk.Field)
			}
			t.Logf("\t%s\tShould have the correct mask.", tests.Success)
		}
	}
}
Esempio n. 4
0
func TestReverseProxyInsecureSkipVerify(t *testing.T) {
	log.SetOutput(ioutil.Discard)
	defer log.SetOutput(os.Stderr)

	var requestReceived bool
	backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestReceived = true
		w.Write([]byte("Hello, client"))
	}))
	defer backend.Close()

	// set up proxy
	p := &Proxy{
		Next:      httpserver.EmptyNext, // prevents panic in some cases when test fails
		Upstreams: []Upstream{newFakeUpstream(backend.URL, true)},
	}

	// create request and response recorder
	r := httptest.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()

	p.ServeHTTP(w, r)

	if !requestReceived {
		t.Error("Even with insecure HTTPS, expected backend to receive request, but it didn't")
	}
}
Esempio n. 5
0
// TestRetrieveRelationship tests the retrieval of a specific relationship.
func TestRetrieveRelationship(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to get a specific relationship.")
	{
		url := "/v1/relationship/" + relPrefix + "authored"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			if w.Code != 200 {
				t.Fatalf("\t%s\tShould be able to retrieve the relationship : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the relationship.", tests.Success)

			var rel relationship.Relationship
			if err := json.Unmarshal(w.Body.Bytes(), &rel); err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the results : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the results.", tests.Success)

			if rel.Predicate != relPrefix+"authored" {
				t.Fatalf("\t%s\tShould have the correct relationship : %s", tests.Failed, rel.Predicate)
			}
			t.Logf("\t%s\tShould have the correct relationship.", tests.Success)
		}
	}
}
Esempio n. 6
0
func TestAggregateGroup(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need aggregate across a form's submissions.")
	{
		url := "/v1/form/580627b42600e2035218509f/aggregate/all"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling aggregate endpoint: %s", url)
		{
			t.Log("\tWhen we user version v1 of the aggregate endpoint.")
			if w.Code != 200 {
				t.Fatalf("\t%s\tShould be able to get the aggregation keys : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to get the aggregation keys .", tests.Success)

			var ag form.Aggregation
			if err := json.Unmarshal(w.Body.Bytes(), &ag); err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the results : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the results.", tests.Success)

			if ag.Count != 9 {
				t.Fatalf("\t%s\tShould have only one aggregation instead of %v.", tests.Failed, ag.Count)
			}
			t.Logf("\t%s\tShould have only one aggregation.", tests.Success)
		}
	}
}
Esempio n. 7
0
// TestDigest tests the returning a form's digest
func TestDigest(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need aggregate across a form's submissions.")
	{
		url := "/v1/form/580627b42600e2035218509f/digest"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling aggregate endpoint: %s", url)
		{
			t.Log("\tWhen we user version v1 of the aggregate endpoint.")
			if w.Code != 200 {
				t.Fatalf("\t%s\tShould be able to get the aggregation keys : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to get the aggregation keys .", tests.Success)

			var fm handlers.FormDigest
			if err := json.Unmarshal(w.Body.Bytes(), &fm); err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the results : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the results.", tests.Success)

			if len(fm.Questions) != 5 {
				t.Fatalf("\t%s\tShould be able to return 1 question instead of %v.", tests.Failed, len(fm.Questions))
			}
			t.Logf("\t%s\tShould be able to return 1 question.", tests.Success)
		}
	}
}
Esempio n. 8
0
func TestWebSocketReverseProxyNonHijackerPanic(t *testing.T) {
	// Capture the expected panic
	defer func() {
		r := recover()
		if _, ok := r.(httpserver.NonHijackerError); !ok {
			t.Error("not get the expected panic")
		}
	}()

	var connCount int32
	wsNop := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) { atomic.AddInt32(&connCount, 1) }))
	defer wsNop.Close()

	// Get proxy to use for the test
	p := newWebSocketTestProxy(wsNop.URL)

	// Create client request
	r := httptest.NewRequest("GET", "/", nil)

	r.Header = http.Header{
		"Connection":            {"Upgrade"},
		"Upgrade":               {"websocket"},
		"Origin":                {wsNop.URL},
		"Sec-WebSocket-Key":     {"x3JJHMbDL1EzLkh9GBhXDw=="},
		"Sec-WebSocket-Version": {"13"},
	}

	nonHijacker := httptest.NewRecorder()
	p.ServeHTTP(nonHijacker, r)
}
Esempio n. 9
0
func DELETERequest(path, accessToken string) *httptest.ResponseRecorder {
	req := httptest.NewRequest(echo.DELETE, path, nil)
	req.Header.Set(echo.HeaderAuthorization, "Bearer "+accessToken)
	res := httptest.NewRecorder()
	e.ServeHTTP(res, req)
	return res
}
Esempio n. 10
0
func TestHostHeaderReplacedUsingForward(t *testing.T) {
	var requestHost string
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestHost = r.Host
		w.Write([]byte("Hello, client"))
	}))
	defer backend.Close()

	upstream := newFakeUpstream(backend.URL, false)
	proxyHostHeader := "test2.com"
	upstream.host.UpstreamHeaders = http.Header{"Host": []string{proxyHostHeader}}
	// set up proxy
	p := &Proxy{
		Next:      httpserver.EmptyNext, // prevents panic in some cases when test fails
		Upstreams: []Upstream{upstream},
	}

	r := httptest.NewRequest("GET", "/", nil)
	r.Host = "test.com"

	w := httptest.NewRecorder()

	p.ServeHTTP(w, r)

	if proxyHostHeader != requestHost {
		t.Fatalf("Expected %s as a Host header got %s\n", proxyHostHeader, requestHost)
	}
}
Esempio n. 11
0
// TestRetrievePattern tests the retrieval of a specific pattern.
func TestRetrievePattern(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to get a specific pattern.")
	{
		url := "/v1/pattern/" + patternPrefix + "comment"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			if w.Code != 200 {
				t.Fatalf("\t%s\tShould be able to retrieve the pattern : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the pattern.", tests.Success)

			var p pattern.Pattern
			if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the results : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the results.", tests.Success)

			if p.Type != patternPrefix+"comment" {
				t.Fatalf("\t%s\tShould have the correct pattern : %s", tests.Failed, p.Type)
			}
			t.Logf("\t%s\tShould have the correct pattern.", tests.Success)
		}
	}
}
Esempio n. 12
0
// TestActionsDELETE sample test for the DELETE call.
func TestActionsDELETE(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to test DELETE action call.")
	{
		action := "flagged_by"
		userID := "ITEST_a63af637-58af-472b-98c7-f5c00743bac6"
		itemID := "ITEST_d1dfa366-d2f7-4a4a-a64f-af89d4c97d82"

		url := fmt.Sprintf("/v1/action/%s/user/%s/on/item/%s", action, userID, itemID)
		r := httptest.NewRequest("DELETE", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			t.Log("\tWhen we use version v1 of the actions endpoint.")

			if w.Code != http.StatusOK {
				t.Fatalf("\t%s\tShould be able to remove the action : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to remove the action.", tests.Success)
		}
	}
}
Esempio n. 13
0
// TestExec tests the execution of a specific query.
func TestExec(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to execute a specific query.")
	{
		url := "/v1/exec/" + qPrefix + "_basic?station_id=42021"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			if w.Code != http.StatusOK {
				t.Fatalf("\t%s\tShould be able to retrieve the query : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the query.", tests.Success)

			recv := tests.IndentJSON(w.Body.String())
			resp := tests.IndentJSON(`{"results":[{"Name":"Basic","Docs":[{"name":"C14 - Pasco County Buoy, FL"}]}]}`)

			if resp != recv {
				t.Log(resp)
				t.Log(recv)
				t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
			}
			t.Logf("\t%s\tShould get the expected result.", tests.Success)
		}
	}
}
Esempio n. 14
0
func TestAggregateGroupSubmission(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need aggregate across a form's submissions.")
	{
		url := "/v1/form/580627b42600e2035218509f/aggregate/d452b94d-e650-41c6-80af-c56091315c90/submission"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling aggregate endpoint: %s", url)
		{
			t.Log("\tWhen we user version v1 of the aggregate endpoint.")
			if w.Code != 200 {
				t.Fatalf("\t%s\tShould be able to get the aggregation keys : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to get the aggregation keys .", tests.Success)

			var ta []form.TextAggregation
			if err := json.Unmarshal(w.Body.Bytes(), &ta); err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the results : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the results.", tests.Success)
		}
	}
}
Esempio n. 15
0
func TestHostSimpleProxyNoHeaderForward(t *testing.T) {
	var requestHost string
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestHost = r.Host
		w.Write([]byte("Hello, client"))
	}))
	defer backend.Close()

	// set up proxy
	p := &Proxy{
		Next:      httpserver.EmptyNext, // prevents panic in some cases when test fails
		Upstreams: []Upstream{newFakeUpstream(backend.URL, false)},
	}

	r := httptest.NewRequest("GET", "/", nil)
	r.Host = "test.com"

	w := httptest.NewRecorder()

	p.ServeHTTP(w, r)

	if !strings.Contains(backend.URL, "//") {
		t.Fatalf("The URL of the backend server doesn't contains //: %s", backend.URL)
	}

	expectedHost := strings.Split(backend.URL, "//")
	if expectedHost[1] != requestHost {
		t.Fatalf("Expected %s as a Host header got %s\n", expectedHost[1], requestHost)
	}
}
Esempio n. 16
0
// TestNamedOnView tests the execution of a specific named query on a view.
func TestNamedOnView(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to execute a specific query.")
	{
		url := "/v1/exec/" + qPrefix + "_basic_view/view/VTEST_thread/ITEST_c1b2bbfe-af9f-4903-8777-bd47c4d5b20a?item_of_interest=ITEST_d1dfa366-d2f7-4a4a-a64f-af89d4c97d82"

		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			if w.Code != http.StatusOK {
				t.Fatalf("\t%s\tShould be able to retrieve the query : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the query.", tests.Success)

			recv := tests.IndentJSON(w.Body.String())
			resp := tests.IndentJSON(`{"results":[{"Name":"BasicView","Docs":[{"item_id":"ITEST_d1dfa366-d2f7-4a4a-a64f-af89d4c97d82"}]}]}`)

			if resp != recv {
				t.Log(resp)
				t.Log(recv)
				t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
			}
			t.Logf("\t%s\tShould get the expected result.", tests.Success)
		}
	}
}
Esempio n. 17
0
// TestScriptByName tests the retrieval of a specific script.
func TestScriptByName(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to get a specific script.")
	{
		url := "/v1/script/" + sPrefix + "_basic_script_pre"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			if w.Code != 200 {
				t.Fatalf("\t%s\tShould be able to retrieve the script : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the script.", tests.Success)

			var scr script.Script
			if err := json.Unmarshal(w.Body.Bytes(), &scr); err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the results : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the results.", tests.Success)

			if scr.Name != sPrefix+"_basic_script_pre" {
				t.Fatalf("\t%s\tShould have the correct script : %s", tests.Failed, scr.Name)
			}
			t.Logf("\t%s\tShould have the correct script.", tests.Success)
		}
	}
}
Esempio n. 18
0
func Test_rpcHandler_Handler(t *testing.T) {
	rpc, teardown := setup()
	defer teardown()

	type args struct {
		httpMethod string
		req        Request
	}

	tests := []struct {
		name string
		args args
		want Response
	}{
		{
			"http GET",
			args{
				httpMethod: "GET",
				req:        Request{},
			},
			Response{
				Jsonrpc: jsonRPC,
				Error: &RPCError{
					Code:    errCodeInvalidRequest,
					Message: errMsgNotPost,
				},
			},
		},
		{
			"invalid jsonrpc",
			args{
				httpMethod: "POST",
				req: Request{
					ID:      "1",
					Jsonrpc: "1.0",
					Method:  "get_status",
				},
			},
			makeErrorResponse(errCodeInvalidParams, errMsgInvalidJsonrpc),
		},
	}

	for _, tt := range tests {
		d, err := json.Marshal(tt.args.req)
		if err != nil {
			t.Fatal(err)
		}

		r := httptest.NewRequest(tt.args.httpMethod, "/webrpc", bytes.NewBuffer(d))
		w := httptest.NewRecorder()
		rpc.Handler(w, r)
		var res Response
		if err := json.NewDecoder(w.Body).Decode(&res); err != nil {
			t.Fatal(err)
		}
		assert.Equal(t, res, tt.want)
	}

}
Esempio n. 19
0
func PUTRequest(path, accessToken, body string) *httptest.ResponseRecorder {
	req := httptest.NewRequest(echo.PUT, path, strings.NewReader(body))
	req.Header.Set(echo.HeaderAuthorization, "Bearer "+accessToken)
	req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
	res := httptest.NewRecorder()
	e.ServeHTTP(res, req)
	return res
}
Esempio n. 20
0
func TestLogRequestBody(t *testing.T) {
	var got bytes.Buffer
	logger := Logger{
		Rules: []*Rule{{
			PathScope: "/",
			Entries: []*Entry{{
				Format: "{request_body}",
				Log:    log.New(&got, "", 0),
			}},
		}},
		Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
			// drain up body
			ioutil.ReadAll(r.Body)
			return 0, nil
		}),
	}

	for i, c := range []struct {
		body   string
		expect string
	}{
		{"", "\n"},
		{"{hello} world!", "{hello} world!\n"},
		{func() string {
			length := httpserver.MaxLogBodySize + 100
			b := make([]byte, length)
			for i := 0; i < length; i++ {
				b[i] = 0xab
			}
			return string(b)
		}(), func() string {
			b := make([]byte, httpserver.MaxLogBodySize)
			for i := 0; i < httpserver.MaxLogBodySize; i++ {
				b[i] = 0xab
			}
			return string(b) + "\n"
		}(),
		},
	} {
		got.Reset()
		r := httptest.NewRequest("POST", "/", bytes.NewBufferString(c.body))
		r.Header.Set("Content-Type", "application/json")
		status, err := logger.ServeHTTP(httptest.NewRecorder(), r)
		if status != 0 {
			t.Errorf("case %d: Expected status to be 0, but was %d", i, status)
		}
		if err != nil {
			t.Errorf("case %d: Expected error to be nil, instead got: %v", i, err)
		}
		if got.String() != c.expect {
			t.Errorf("case %d: Expected body %q, but got %q", i, c.expect, got.String())
		}
	}
}
Esempio n. 21
0
func TestLogProxier(t *testing.T) {
	a := New(t)

	hdl := &testHandler{}
	p := WithLogger(hdl, GetLogger(t, ""))

	req := httptest.NewRequest("GET", "/uri", bytes.NewBuffer([]byte{}))
	p.ServeHTTP(httptest.NewRecorder(), req)
	a.So(hdl.req, ShouldNotBeNil)
	a.So(hdl.res, ShouldNotBeNil)
}
Esempio n. 22
0
// TestDeleteRelationship tests the insert and deletion of a relationship.
func TestDeleteRelationship(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to delete a relationship.")
	{
		//----------------------------------------------------------------------
		// Delete the Relationship.

		url := "/v1/relationship/" + relPrefix + "on"
		r := httptest.NewRequest("DELETE", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url to delete : %s", url)
		{
			if w.Code != 204 {
				t.Fatalf("\t%s\tShould be able to delete the relationship : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to delete the relationship.", tests.Success)
		}

		//----------------------------------------------------------------------
		// Retrieve the Relationship.

		url = "/v1/relationship/" + relPrefix + "on"
		r = httptest.NewRequest("GET", url, nil)
		w = httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url to get : %s", url)
		{
			if w.Code != 404 {
				t.Fatalf("\t%s\tShould not be able to retrieve the relationship : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould not be able to retrieve the relationship.", tests.Success)
		}
	}
}
Esempio n. 23
0
func ExampleResponseRecorder() {
	handler := func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "something failed", http.StatusInternalServerError)
	}

	req := httptest.NewRequest("GET", "http://example.com/foo", nil)
	w := httptest.NewRecorder()
	handler(w, req)

	fmt.Printf("%d - %s", w.Code, w.Body.String())
	// Output: 500 - something failed
}
Esempio n. 24
0
func TestHandleHealth(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	httpServer, server := newTestServer(ctx, t, nil)
	defer httpServer.Close()

	rr := httptest.NewRecorder()
	server.handleHealth(rr, httptest.NewRequest("GET", "/healthz", nil))
	if rr.Code != http.StatusOK {
		t.Errorf("expected 200 got %d", rr.Code)
	}

}
Esempio n. 25
0
// TestFormsGET sample test for the GET call.
func TestFormsGET(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to test GET form call.")
	{
		url := "/v1/form"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			t.Log("\tWhen we user version v1 of the forms endpoint.")
			if w.Code != http.StatusOK {
				t.Fatalf("\t%s\tShould be able to retrieve the forms list : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the forms list.", tests.Success)

			var forms []struct {
				ID string `json:"id"`
			}

			err := json.NewDecoder(w.Body).Decode(&forms)
			if err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the response : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the response.", tests.Success)

			total := 141
			if len(forms) != total {
				t.Log("GOT :", len(forms))
				t.Log("WANT:", total)
				t.Errorf("\t%s\tShould have the correct amount of forms.", tests.Failed)
			} else {
				t.Logf("\t%s\tShould have the correct amount of forms.", tests.Success)
			}

			want := "5790f40c6413f60007228586"
			if forms[0].ID != want {
				t.Log("GOT :", forms[0].ID)
				t.Log("WANT:", want)
				t.Errorf("\t%s\tShould have the correct id.", tests.Failed)
			} else {
				t.Logf("\t%s\tShould have the correct id.", tests.Success)
			}
		}
	}
}
Esempio n. 26
0
// TestDownloadCSV tests the retrieval of a CSV file.
func TestDownloadCSV(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need download submissions in a CSV format.")
	{
		url := "/v1/form/5810cc8b2600e2092e6a3fba/submission/export?download=true"
		r := httptest.NewRequest("GET", url, nil)
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling CSV URL : %s", url)
		{
			t.Log("\tWhen we user version v1 of the export endpoint.")
			if w.Code != 200 {
				t.Fatalf("\t%s\tShould be able to get the URL of the file to download : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to get the URL of the file to download.", tests.Success)

			isCSV := false
			for _, h := range w.HeaderMap["Content-Type"] {
				if h == "text/csv" {
					isCSV = true
					break
				}
			}
			if !isCSV {
				t.Fatalf("\t%s\tShould be able to get a CSV content-type file.", tests.Failed)
			}
			t.Logf("\t%s\tShould be able to get a CSV content-type file.", tests.Success)

			r := csv.NewReader(strings.NewReader(string(w.Body.Bytes())))
			records, err := r.ReadAll()
			if err != nil {
				t.Fatalf("\t%s\tShould be able to unmarshal the results : %v", tests.Failed, err)
			}
			t.Logf("\t%s\tShould be able to unmarshal the results.", tests.Success)

			expectedCount := 2
			if len(records) != expectedCount {
				t.Fatalf("\t%s\tShould have exactly %d rows but it has %d.", tests.Failed, expectedCount, len(records))
			}
			t.Logf("\t%s\tShould have exactly %d rows.", tests.Success, expectedCount)

		}
	}
}
Esempio n. 27
0
func TestSendResponseError(t *testing.T) {

	oldSendJSONEncode := sendJSONEncode
	defer func() { sendJSONEncode = oldSendJSONEncode }()
	sendJSONEncode = mockSendJSONEncode

	rw := httptest.NewRecorder()
	hr := httptest.NewRequest("GET", "http://example.com", nil)
	code := 200
	data := "TEST STRING"

	sendResponse(rw, hr, nil, code, data)

	if rw.Code != 200 {
		t.Error(fmt.Errorf("Expected 200, got %d", rw.Code))
	}
}
Esempio n. 28
0
// TestExecExplain tests the execution of a custom query with explain.
func TestExecExplain(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to execute a custom query with explain.")
	{
		qs, err := qfix.Get("basic.json")
		if err != nil {
			t.Fatalf("\t%s\tShould be able to retrieve the fixture : %v", tests.Failed, err)
		}
		t.Logf("\t%s\tShould be able to retrieve the fixture.", tests.Success)

		qs.Explain = true

		qsStrData, err := json.Marshal(&qs)
		if err != nil {
			t.Fatalf("\t%s\tShould be able to marshal the fixture : %v", tests.Failed, err)
		}
		t.Logf("\t%s\tShould be able to marshal the fixture.", tests.Success)

		url := "/v1/exec"
		r := httptest.NewRequest("POST", url, bytes.NewBuffer(qsStrData))
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			if w.Code != http.StatusOK {
				t.Fatalf("\t%s\tShould be able to retrieve the query : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the query.", tests.Success)

			recv := tests.IndentJSON(w.Body.String())
			resp := `queryPlanner`

			if !strings.Contains(recv, resp) {
				t.Log(resp)
				t.Log(recv)
				t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
			}
			t.Logf("\t%s\tShould get the expected result.", tests.Success)
		}
	}
}
Esempio n. 29
0
func TestSendResponse500(t *testing.T) {
	rw := httptest.NewRecorder()
	hr := httptest.NewRequest("GET", "http://example.com", nil)
	code := 500
	data := "TEST STRING"

	sendResponse(rw, hr, nil, code, data)

	if rw.Code != 500 {
		t.Error(fmt.Errorf("Expected 500, got %d", rw.Code))
	}
	if rw.HeaderMap["Content-Type"][0] != "application/json" {
		t.Error(fmt.Errorf("Expected 'application/json', got %s", rw.HeaderMap["Content-Type"][0]))
	}
	if !strings.Contains(rw.Body.String(), `"data":"TEST STRING"`) {
		t.Error(fmt.Errorf("The resulting body is not correct: %v", rw.Body.String()))
	}
}
Esempio n. 30
0
// TestCustomOnView tests the execution of a custom query on a view.
func TestExecCustomOnView(t *testing.T) {
	tests.ResetLog()
	defer tests.DisplayLog()

	t.Log("Given the need to execute a custom query on a view.")
	{
		qs, err := qfix.Get("basic_view.json")
		if err != nil {
			t.Fatalf("\t%s\tShould be able to retrieve the fixture : %v", tests.Failed, err)
		}
		t.Logf("\t%s\tShould be able to retrieve the fixture.", tests.Success)

		qsStrData, err := json.Marshal(&qs)
		if err != nil {
			t.Fatalf("\t%s\tShould be able to marshal the fixture : %v", tests.Failed, err)
		}
		t.Logf("\t%s\tShould be able to marshal the fixture.", tests.Success)

		url := "/v1/exec/view/VTEST_thread/ITEST_c1b2bbfe-af9f-4903-8777-bd47c4d5b20a?item_of_interest=ITEST_d1dfa366-d2f7-4a4a-a64f-af89d4c97d82"

		r := httptest.NewRequest("POST", url, bytes.NewBuffer(qsStrData))
		w := httptest.NewRecorder()

		a.ServeHTTP(w, r)

		t.Logf("\tWhen calling url : %s", url)
		{
			if w.Code != http.StatusOK {
				t.Fatalf("\t%s\tShould be able to retrieve the query : %v", tests.Failed, w.Code)
			}
			t.Logf("\t%s\tShould be able to retrieve the query.", tests.Success)

			recv := tests.IndentJSON(w.Body.String())
			resp := tests.IndentJSON(`{"results":[{"Name":"BasicView","Docs":[{"item_id":"ITEST_d1dfa366-d2f7-4a4a-a64f-af89d4c97d82"}]}]}`)

			if resp != recv {
				t.Log(resp)
				t.Log(recv)
				t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
			}
			t.Logf("\t%s\tShould get the expected result.", tests.Success)
		}
	}
}