Beispiel #1
0
func TestPing(t *testing.T) {
	testflight.WithServer(handler, func(r *testflight.Requester) {
		response := r.Get("/ping")
		assert.Equal(t, 200, response.StatusCode)
		assert.Equal(t, "OK", response.Body)
	})
}
func TestCommonHeaders(t *testing.T) {
	corsOrigins := []string{"http://example.com"}

	Convey("Test common headers", t, func() {
		testflight.WithServer(
			testHandler(corsOrigins),
			func(r *testflight.Requester) {
				headers := r.Get("/ping").RawResponse.Header

				Convey("Sets content-type header", func() {
					actual := headers.Get("Content-Type")
					So(actual, ShouldEqual, "application/vnd.api+json")
				})

				Convey("Sets access-control-allow header", func() {
					actual := headers.Get("Access-Control-Allow-Headers")
					So(actual, ShouldEqual, "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
				})
			},
		)
	})

	Convey("Test CORS headers", t, func() {
		testflight.WithServer(
			testHandler(corsOrigins),
			func(r *testflight.Requester) {
				headerName := "Access-Control-Allow-Origin"
				request, _ := http.NewRequest(
					"GET", "/ping", strings.NewReader(""),
				)

				Convey("Returns CORS header for allowed origin", func() {
					request.Header.Add("Origin", "http://example.com")
					actual := r.Do(request).RawResponse.Header.Get(headerName)
					So(actual, ShouldEqual, "http://example.com")
				})

				Convey("Does not return CORS header for not allowed origin", func() {
					request.Header.Add("Origin", "http://not-allowed.com")
					actual := r.Do(request).RawResponse.Header.Get(headerName)
					So(actual, ShouldEqual, "")
				})
			},
		)
	})
}
func TestUserGet(t *testing.T) {
	testflight.WithServer(rooter(goji.DefaultMux), func(r *testflight.Requester) {
		req, _ := http.NewRequest("GET", "/user/edit/22", nil)
		req.Header.Set("Authorization", "Basic dXNlcjp1c2Vy")
		response := r.Do(req)
		assert.Equal(t, 200, response.StatusCode)
	})
}
Beispiel #4
0
func TestWebSocketRecordsReceivedMessages(t *testing.T) {
	testflight.WithServer(websocketHandler(), func(r *testflight.Requester) {
		connection := Connect(r, "/websocket")

		connection.WriteMessage("Drew")
		connection.ReceiveMessage()
		assert.Equal(t, "Hello, Drew", connection.ReceivedMessages[0])
	})
}
Beispiel #5
0
func TestWebSocketTimesOutWhileFlushingMessages(t *testing.T) {
	testflight.WithServer(donothingwebsocketHandler(), func(r *testflight.Requester) {
		connection := Connect(r, "/websocket")
		connection.WriteMessage("Drew")

		err := connection.FlushMessages(2)
		assert.Equal(t, TimeoutError{}, *err)
	})
}
Beispiel #6
0
func TestWebSocket(t *testing.T) {
	testflight.WithServer(websocketHandler(), func(r *testflight.Requester) {
		connection := Connect(r, "/websocket")

		connection.SendMessage("Drew")
		message, _ := connection.ReceiveMessage()
		assert.Equal(t, "Hello, Drew", message)
	})
}
Beispiel #7
0
func testDelete(t *testing.T, url string) {
	testflight.WithServer(
		CRUDRouter(),
		func(r *testflight.Requester) {
			response := r.Delete(url, testflight.JSON, "")

			structJSONCompare(t, http.StatusNoContent, response.StatusCode)
		},
	)
}
Beispiel #8
0
func TestWebSocketFlushesMessages(t *testing.T) {
	testflight.WithServer(multiresponsewebsocketHandler(), func(r *testflight.Requester) {
		connection := Connect(r, "/websocket")

		connection.WriteMessage("Drew")
		connection.WriteMessage("Bob")
		connection.FlushMessages(2)
		assert.Equal(t, 2, len(connection.ReceivedMessages))
	})
}
Beispiel #9
0
func TestWebSocketReceiveMessageTimesOut(t *testing.T) {

	testflight.WithServer(donothingwebsocketHandler(), func(r *testflight.Requester) {
		connection := Connect(r, "/websocket")

		connection.WriteMessage("Drew")
		_, err := connection.ReceiveMessage()
		assert.Equal(t, TimeoutError{}, *err)
	})
}
Beispiel #10
0
func TestClosingConnections(t *testing.T) {
	testflight.WithServer(pollingHandler(), func(r *testflight.Requester) {
		connection := Connect(r, "/websocket")

		connection.SendMessage("Drew")
		connection.SendMessage("Bob")
		connection.FlushMessages(2)
		connection.Close()
		assert.Equal(t, 2, len(connection.ReceivedMessages))
	})
}
Beispiel #11
0
func TestWebSocketTimeoutIsConfigurable(t *testing.T) {
	testflight.WithServer(websocketHandler(), func(r *testflight.Requester) {
		connection := Connect(r, "/websocket")
		connection.Timeout = 2 * time.Second

		go func() {
			time.Sleep(1 * time.Second)
			connection.WriteMessage("Drew")
		}()

		message, _ := connection.ReceiveMessage()
		assert.Equal(t, "Hello, Drew", message)
	})
}
func TestProducer(t *testing.T) {
	stack := new(mango.Stack)
	handler := stack.HandlerFunc(pact.Producer)

	testflight.WithServer(handler, func(r *testflight.Requester) {

		pact_str, err := ioutil.ReadFile("../pacts/my_consumer-my_producer.json")
		if err != nil {
			t.Error(err)
		}

		pacts := make(map[string]interface{})
		err = json.Unmarshal(pact_str, &pacts)
		if err != nil {
			t.Error(err)
		}

		for _, i := range pacts["interactions"].([]interface{}) {
			interaction := i.(map[string]interface{})
			t.Logf("Given %s", interaction["producer_state"])
			t.Logf("  %s", interaction["description"])

			request := interaction["request"].(map[string]interface{})
			var actualResponse *testflight.Response
			switch request["method"] {
			case "get":
				actualResponse = r.Get(request["path"].(string) + "?" + request["query"].(string))
			}

			expectedResponse := interaction["response"].(map[string]interface{})

			assert.Equal(t, int(expectedResponse["status"].(float64)), actualResponse.StatusCode)

			for k, v := range expectedResponse["headers"].(map[string]interface{}) {
				assert.Equal(t, v, actualResponse.RawResponse.Header[k][0])
			}

			responseBody := make(map[string]interface{})
			err = json.Unmarshal([]byte(actualResponse.Body), &responseBody)
			if err != nil {
				t.Error(err)
			}
			for _, diff := range pretty.Diff(expectedResponse["body"], responseBody) {
				t.Log(diff)
			}
			assert.Equal(t, expectedResponse["body"], responseBody)
		}
	})
}
func TestUserDelete(t *testing.T) {
	testflight.WithServer(rooter(goji.DefaultMux), func(r *testflight.Requester) {
		Users := []models.User{}
		count_before := 0
		count_after := 0
		db.Find(&Users).Count(&count_before)

		req, _ := http.NewRequest("GET", "/user/delete/1", nil)
		req.Header.Set("Authorization", "Basic dXNlcjp1c2Vy")
		r.Do(req)

		db.Find(&Users).Count(&count_after)
		assert.Equal(t, count_before-1, count_after)
	})
}
Beispiel #14
0
func testRead(t *testing.T, url string, v interface{}) {
	testflight.WithServer(
		CRUDRouter(),
		func(r *testflight.Requester) {
			response := r.Get(url)

			structJSONCompare(t, http.StatusOK, response.StatusCode)

			err := json.Unmarshal([]byte(response.Body), v)

			if err != nil {
				t.Error(err)
			}
		},
	)
}
func TestUserCreateError(t *testing.T) {
	testflight.WithServer(rooter(goji.DefaultMux), func(r *testflight.Requester) {
		count_before := 0
		count_after := 0
		db.Table("users").Count(&count_before)

		values := url.Values{}
		values.Add("Name", "エラー")

		req, _ := http.NewRequest("POST", "/user/new", strings.NewReader(values.Encode()))
		req.Header.Set("Authorization", "Basic dXNlcjp1c2Vy")
		req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		response := r.Do(req)

		db.Table("users").Count(&count_after)
		assert.Equal(t, 200, response.StatusCode)
		assert.Equal(t, count_before, count_after)
	})
}
Beispiel #16
0
func testUpdate(t *testing.T, url string, v interface{}) {
	enc, err := json.Marshal(v)

	if err != nil {
		t.Error(err)
	}

	testflight.WithServer(
		CRUDRouter(),
		func(r *testflight.Requester) {
			response := r.Put(url, testflight.JSON, string(enc))

			structJSONCompare(t, http.StatusOK, response.StatusCode)

			err = json.Unmarshal([]byte(response.Body), v)

			if err != nil {
				t.Error(err)
			}
		},
	)
}
Beispiel #17
0
func TestPOST(t *testing.T) {
	testflight.WithServer(handler, func(r *testflight.Requester) {
		response := r.Post("/", testflight.JSON, `{"test":1}`)
		assert.Equal(t, 201, response.StatusCode)
	})
}
Beispiel #18
0
			return recorder
		}

		It("has a Content-Type header", func() {
			response := makeRequest()

			header := response.Header().Get("Content-Type")
			Ω(header).Should(Equal("application/json"))
		})
	})

	Describe("authentication", func() {
		makeRequestWithoutAuth := func() *testflight.Response {
			response := &testflight.Response{}
			testflight.WithServer(brokerAPI, func(r *testflight.Requester) {
				request, _ := http.NewRequest("GET", "/v2/catalog", nil)
				response = r.Do(request)
			})
			return response
		}

		makeRequestWithAuth := func(username string, password string) *testflight.Response {
			response := &testflight.Response{}
			testflight.WithServer(brokerAPI, func(r *testflight.Requester) {
				request, _ := http.NewRequest("GET", "/v2/catalog", nil)
				request.SetBasicAuth(username, password)

				response = r.Do(request)
			})
			return response
		}
Beispiel #19
0
func TestGET(t *testing.T) {
	testflight.WithServer(handler, func(r *testflight.Requester) {
		response := r.Get("/?test=1")
		assert.Equal(t, 201, response.StatusCode)
	})
}
Beispiel #20
0
func TestHandleAdd(t *testing.T) {
	aConfig := giles.LoadConfig("../giles.cfg")
	testArchiver = giles.NewArchiver(aConfig)
	h := NewHTTPHandler(testArchiver)
	uuid := common.NewUUID()

	for _, test := range []struct {
		title          string
		toPost         string
		expectedStatus int
		expectedBody   string
	}{
		{
			"No Readings",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v" }}`, uuid),
			200,
			"",
		},
		{
			"Empty Readings 1",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Readings": [ ]}}`, uuid),
			200,
			"",
		},
		{
			"Empty Readings 2",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Readings": [[ ]]}}`, uuid),
			200,
			"",
		},
		{
			"Bad JSON 1",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Readings": [ ]]}}`, uuid),
			400,
			"invalid character ']' after object key:value pair",
		},
		{
			"Bad JSON 2",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Readings": [[ ]]}`, uuid),
			400,
			"unexpected EOF",
		},
		{
			"Bad Readings 1: negative timestamp",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Readings": [[-1, 0]]}}`, uuid),
			400,
			"json: cannot unmarshal number -1 into Go value of type uint64",
		},
		{
			"Bad Readings 2: too big timestamp",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Readings": [[1000000000000000000, 0]]}}`, uuid),
			500,
			"Bad Timestamp: 1000000000000000000",
		},
		{
			"Bad Readings 3: too big timestamp",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Readings": [[3458764513820540929, 0]]}}`, uuid),
			500,
			"Bad Timestamp: 3458764513820540929",
		},
		{
			"Good readings: 1 reading max timestamp",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Properties": {"UnitofTime": "ns"}, "Readings": [[3458764513820540928, 0]]}}`, uuid),
			200,
			"",
		},
		{
			"Good readings: 2 repeat readings",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Properties": {"UnitofTime": "ns"}, "Readings": [[1000000000000000000, 0], [1000000000000000000, 0]]}}`, uuid),
			200,
			"",
		},
		{
			"Good readings: 2 repeat readings diff values",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Properties": {"UnitofTime": "ns"}, "Readings": [[2000000000000000000, 0], [2000000000000000000, 1]]}}`, uuid),
			200,
			"",
		},
		{
			"Lots of readings",
			fmt.Sprintf(`{"/sensor/0": {"Path": "/sensor/0", "uuid": "%v", "Properties": {"UnitofTime": "ns"}, "Readings": [ %v [1000000000000000000, 0]]}}`, uuid, strings.Repeat("[1000000000000000000, 0],", 1000)),
			200,
			"",
		},
	} {

		testflight.WithServer(h.handler, func(r *testflight.Requester) {
			response := r.Post("/add/dummykey", testflight.JSON, test.toPost)
			assert.Equal(t, test.expectedStatus, response.StatusCode, test.title)
			assert.Equal(t, test.expectedBody, response.Body, test.title)
		})
	}
}
Beispiel #21
0
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var r = mux.NewRouter()

var _ = Describe("SampleController", func() {

	BeforeSuite(func() {
		app.RegisterRoutes(r)
	})

	Context("GET /", func() {
		It("should be OK", func() {
			testflight.WithServer(r, func(r *testflight.Requester) {
				response := r.Get("/")
				Expect(response.StatusCode).To(Equal(200))
			})
		})
	})

	Context("GET /books", func() {
		It("Should be OK too", func() {
			testflight.WithServer(r, func(r *testflight.Requester) {
				response := r.Get("/books")
				Expect(response.StatusCode).To(Equal(200))
			})
		})
	})
})
Beispiel #22
0
	var fakeServiceBroker *fakes.FakeServiceBroker
	var brokerAPI http.Handler
	var brokerLogger *lagertest.TestLogger
	var credentials = brokerapi.BrokerCredentials{
		Username: "******",
		Password: "******",
	}

	makeInstanceProvisioningRequest := func(instanceID string, details brokerapi.ProvisionDetails) *testflight.Response {
		response := &testflight.Response{}
		testflight.WithServer(brokerAPI, func(r *testflight.Requester) {
			path := "/v2/service_instances/" + instanceID

			buffer := &bytes.Buffer{}
			json.NewEncoder(buffer).Encode(details)
			request, err := http.NewRequest("PUT", path, buffer)
			Expect(err).NotTo(HaveOccurred())
			request.Header.Add("Content-Type", "application/json")
			request.SetBasicAuth(credentials.Username, credentials.Password)

			response = r.Do(request)
		})
		return response
	}

	lastLogLine := func() lager.LogFormat {
		if len(brokerLogger.Logs()) == 0 {
			// better way to raise error?
			err := errors.New("expected some log lines but there were none!")
			Expect(err).NotTo(HaveOccurred())
		}
Beispiel #23
0
func withServer(f func(*testflight.Requester)) {
	netrackerServer := New()
	testflight.WithServer(netrackerServer.handler(), f)
}