Example #1
0
func TestGetCodec(t *testing.T) {

	service := NewWebCodecService()
	var codec codecs.Codec

	codec, _ = service.GetCodec(constants.ContentTypeJSON)

	if assert.NotNil(t, codec, "Json should exist") {
		assert.Equal(t, constants.ContentTypeJSON, codec.ContentType(), "ContentTypeJson")
	}

	// case insensitivity
	codec, _ = service.GetCodec(strings.ToUpper(constants.ContentTypeJSON))

	if assert.NotNil(t, codec, "Content case should not matter") {
		assert.Equal(t, constants.ContentTypeJSON, codec.ContentType(), "ContentTypeJson")
	}

	// with noise
	codec, _ = service.GetCodec(fmt.Sprintf("%s; charset=UTF-8", constants.ContentTypeJSON))
	if assert.NotNil(t, codec, "charset in Content-Type should not matter") {
		assert.Equal(t, constants.ContentTypeJSON, codec.ContentType(), "ContentTypeJson")
	}

	// default
	codec, _ = service.GetCodec("")

	if assert.NotNil(t, codec, "Empty contentType string should assume JSON") {
		assert.Equal(t, constants.ContentTypeJSON, codec.ContentType(), "Should assume JSON.")
	}

}
Example #2
0
func TestMapCreation(t *testing.T) {

	o := New(nil)
	assert.Nil(t, o)

	o = New("Tyler")
	assert.Nil(t, o)

	unconvertable := &Unconvertable{name: "Tyler"}
	o = New(unconvertable)
	assert.Nil(t, o)

	convertable := &Convertable{name: "Tyler"}
	o = New(convertable)
	if assert.NotNil(t, convertable) {
		assert.Equal(t, "Tyler", o["name"], "Tyler")
	}

	o = MSI()
	if assert.NotNil(t, o) {
		assert.NotNil(t, o)
	}

	o = MSI("name", "Tyler")
	if assert.NotNil(t, o) {
		if assert.NotNil(t, o) {
			assert.Equal(t, o["name"], "Tyler")
		}
	}

}
Example #3
0
func TestCodecOptions(t *testing.T) {

	c := new(WebContext)

	c.codecOptions = nil

	assert.NotNil(t, c.CodecOptions())
	assert.NotNil(t, c.codecOptions)
}
Example #4
0
func TestData(t *testing.T) {

	c := new(WebContext)

	c.data = nil

	assert.NotNil(t, c.Data())
	assert.NotNil(t, c.data)

}
Example #5
0
func TestMapFromJSON(t *testing.T) {

	o := MustFromJSON(`{"name":"Mat"}`)

	if assert.NotNil(t, o) {
		if assert.NotNil(t, o) {
			assert.Equal(t, "Mat", o["name"])
		}
	}

}
Example #6
0
func TestMarshalAndUnmarshal(t *testing.T) {

	// make a big object
	obj := map[string]interface{}{}
	obj["name"] = "Mat"
	obj["age"] = 30
	obj["address"] = map[string]interface{}{
		"street":  "Pearl Street",
		"city":    "Boulder",
		"state":   "CO",
		"country": "USA",
	}
	obj["animals"] = map[string]interface{}{
		"favourite": []string{"Dog", "Cat"},
	}

	bytes, marshalErr := xmlCodec.Marshal(obj, nil)

	if assert.NoError(t, marshalErr) {
		assert.Contains(t, string(bytes), "<?xml version=\"1.0\"?>", "Output")
	}

	// unmarshal it
	var newObj interface{}
	if assert.NoError(t, xmlCodec.Unmarshal(bytes, &newObj)) {

		assert.NotNil(t, newObj)

	}

}
Example #7
0
func assertPathMatchHandler(t *testing.T, handler *PathMatchHandler, path, method string, message string) bool {

	if assert.NotNil(t, handler) {

		ctx := context_test.MakeTestContextWithDetails(path, method)

		willHandle, _ := handler.WillHandle(ctx)
		if assert.True(t, willHandle, fmt.Sprintf("This handler is expected to handle it: %s", message)) {

			// make sure the method is in the list
			methodFound := false
			for _, methodInList := range handler.HttpMethods {
				if methodInList == method {
					methodFound = true
					break
				}
			}

			return assert.True(t, methodFound, "Method (%s) should be in the method list (%s)", method, handler.HttpMethods)
		}

	}

	return false

}
Example #8
0
func TestUnmarshal_MultipleObjects(t *testing.T) {

	raw := "field_a,field_b,field_c\nrow1a,row1b,row1c\nrow2a,row2b,row2c\nrow3a,row3b,row3c"

	csvCodec := new(CsvCodec)

	var obj interface{}
	csvCodec.Unmarshal([]byte(raw), &obj)

	if assert.NotNil(t, obj, "Unmarshal should make an object") {
		if array, ok := obj.([]interface{}); ok {

			if assert.Equal(t, 3, len(array), "Should be 3 items") {

				assert.Equal(t, "row1a", array[0].(map[string]interface{})["field_a"])
				assert.Equal(t, "row1b", array[0].(map[string]interface{})["field_b"])
				assert.Equal(t, "row1c", array[0].(map[string]interface{})["field_c"])

				assert.Equal(t, "row2a", array[1].(map[string]interface{})["field_a"])
				assert.Equal(t, "row2b", array[1].(map[string]interface{})["field_b"])
				assert.Equal(t, "row2c", array[1].(map[string]interface{})["field_c"])

				assert.Equal(t, "row3a", array[2].(map[string]interface{})["field_a"])
				assert.Equal(t, "row3b", array[2].(map[string]interface{})["field_b"])
				assert.Equal(t, "row3c", array[2].(map[string]interface{})["field_c"])

			}

		} else {
			t.Errorf("Expected to be array type, not %s.", reflect.TypeOf(obj).Elem().Name())
		}
	}

}
Example #9
0
func TestUnmarshal_arrayOfMaps(t *testing.T) {

	xml := `<objects><object><name>Mat</name><age type="int">30</age><yesOrNo type="bool">true</yesOrNo><address><city>Boulder</city><state>CO</state></address></object><object><name>Tyler</name><age type="int">28</age><yesOrNo type="bool">false</yesOrNo><address><city>Salt Lake City</city><state>UT</state></address></object></objects>`

	obj, err := unmarshal(xml, nil)

	if assert.NoError(t, err) {
		if assert.NotNil(t, obj) {

			os := obj.([]interface{})

			o1 := os[0].(map[string]interface{})
			assert.Equal(t, "Mat", o1["name"])
			assert.Equal(t, 30, o1["age"])
			assert.Equal(t, true, o1["yesOrNo"])

			o2 := os[1].(map[string]interface{})
			assert.Equal(t, "Tyler", o2["name"])
			assert.Equal(t, 28, o2["age"])
			assert.Equal(t, false, o2["yesOrNo"])

		}
	}

}
Example #10
0
func TestMapFromURLQuery(t *testing.T) {

	m, err := FromURLQuery("name=tyler&state=UT")
	if assert.NoError(t, err) && assert.NotNil(t, m) {
		assert.Equal(t, "tyler", m.Get("name").Str())
		assert.Equal(t, "UT", m.Get("state").Str())
	}

}
Example #11
0
func TestNewPathPattern(t *testing.T) {

	path := "/people/{id}/books"
	p, _ := NewPathPattern(path)

	if assert.NotNil(t, p) {
		assert.Equal(t, path, p.RawPath)
	}

}
Example #12
0
func Test_Mock_TestData(t *testing.T) {

	var mockedService *TestExampleImplementation = new(TestExampleImplementation)

	if assert.NotNil(t, mockedService.TestData()) {

		mockedService.TestData().Set("something", 123)
		assert.Equal(t, 123, mockedService.TestData().Get("something").Data())

	}

}
Example #13
0
func TestGetCodecForResponding_DefaultCodec(t *testing.T) {

	service := NewWebCodecService()
	var codec codecs.Codec

	codec, _ = service.GetCodecForResponding("", "", false)

	if assert.NotNil(t, codec, "Return of GetCodecForAcceptStringOrExtension should default to JSON") {
		assert.Equal(t, constants.ContentTypeJSON, codec.ContentType(), "Should default to JSON")
	}

}
Example #14
0
func TestMapFromFieldsAndRow(t *testing.T) {

	fields := []string{"field1", "field2", "field3"}
	row := []string{"one", "two", "three"}

	m, err := mapFromFieldsAndRow(fields, row)

	if assert.NoError(t, err) && assert.NotNil(t, m) {

		assert.Equal(t, "one", m["field1"])
		assert.Equal(t, "two", m["field2"])
		assert.Equal(t, "three", m["field3"])

	}

}
Example #15
0
func TestGetAndSetErrorHandler(t *testing.T) {

	codecService := codecsservices.NewWebCodecService()
	handler := NewHttpHandler(codecService)

	errorHandler := new(handlers_test.TestHandler)

	// default one should be made
	assert.NotNil(t, handler.ErrorHandler())

	//... but if we set one explicitally
	handler.SetErrorHandler(errorHandler)

	//... it should be set!
	assert.Equal(t, errorHandler, handler.ErrorHandler())

}
Example #16
0
func Test_Mock_findExpectedCall(t *testing.T) {

	m := new(Mock)
	m.On("One", 1).Return("one")
	m.On("Two", 2).Return("two")
	m.On("Two", 3).Return("three")

	f, c := m.findExpectedCall("Two", 3)

	if assert.Equal(t, 2, f) {
		if assert.NotNil(t, c) {
			assert.Equal(t, "Two", c.Method)
			assert.Equal(t, 3, c.Arguments[0])
			assert.Equal(t, "three", c.ReturnArguments[0])
		}
	}

}
Example #17
0
func TestNewContext(t *testing.T) {

	responseWriter := new(http_test.TestResponseWriter)
	testRequest, _ := http.NewRequest("GET", "http://goweb.org/people/123", nil)
	codecService := codecsservices.NewWebCodecService()

	c := NewWebContext(responseWriter, testRequest, codecService)

	if assert.NotNil(t, c) {

		assert.Equal(t, "people/123", c.Path().RawPath)
		assert.Equal(t, testRequest, c.httpRequest)
		assert.Equal(t, responseWriter, c.httpResponseWriter)
		assert.Equal(t, codecService, c.codecService)
		assert.Equal(t, codecService, c.CodecService())

	}

}
Example #18
0
func TestUnmarshal_map(t *testing.T) {

	xml := `<object><name>Mat</name><age type='int'>30</age><yesOrNo type='bool'>true</yesOrNo><address><city>Boulder</city><state>CO</state></address></object>`

	obj, err := unmarshal(xml, nil)

	if assert.NoError(t, err) {
		if assert.NotNil(t, obj) {

			o := obj.(map[string]interface{})

			assert.Equal(t, "Mat", o["name"])
			assert.Equal(t, 30, o["age"])
			assert.Equal(t, true, o["yesOrNo"])

		}
	}

}
Example #19
0
func TestRequestData_ArrayOfData(t *testing.T) {

	responseWriter := new(http_test.TestResponseWriter)
	testRequest, _ := http.NewRequest("GET", "http://goweb.org/people/123", strings.NewReader("[{\"something\":true},{\"something\":false}]"))

	codecService := codecsservices.NewWebCodecService()

	c := NewWebContext(responseWriter, testRequest, codecService)

	bod, _ := c.RequestBody()
	assert.Equal(t, "[{\"something\":true},{\"something\":false}]", string(bod))
	dat, datErr := c.RequestData()

	if assert.NoError(t, datErr) {
		assert.NotNil(t, dat.([]interface{}))
		responseDataArray, _ := c.RequestDataArray()
		assert.Equal(t, dat.([]interface{}), responseDataArray)
	}

}
Example #20
0
func TestQueryParams(t *testing.T) {

	responseWriter := new(http_test.TestResponseWriter)
	testRequest, _ := http.NewRequest("GET", "http://goweb.org/people/123?name=Mat&name=Laurie&age=30&something=true", strings.NewReader("[{\"something\":true},{\"something\":false}]"))

	codecService := codecsservices.NewWebCodecService()

	c := NewWebContext(responseWriter, testRequest, codecService)

	params := c.QueryParams()

	if assert.NotNil(t, params) {

		assert.Equal(t, "Mat", params.Get("name").StrSlice()[0])
		assert.Equal(t, "Laurie", params.Get("name").StrSlice()[1])
		assert.Equal(t, "30", params.Get("age").StrSlice()[0])
		assert.Equal(t, "true", params.Get("something").StrSlice()[0])

	}

}
Example #21
0
func TestUnmarshal_SingleObject_WithNoEndLinefeed(t *testing.T) {

	raw := "field_a,field_b,field_c\nrow1a,row1b,row1c"

	csvCodec := new(CsvCodec)

	var obj interface{}
	csvCodec.Unmarshal([]byte(raw), &obj)

	if assert.NotNil(t, obj, "Unmarshal should make an object") {
		if object, ok := obj.(map[string]interface{}); ok {

			assert.Equal(t, "row1a", object["field_a"])
			assert.Equal(t, "row1b", object["field_b"])
			assert.Equal(t, "row1c", object["field_c"])

		} else {
			t.Errorf("Expected to be array type, not %s.", reflect.TypeOf(obj).Elem().Name())
		}
	}

}
Example #22
0
func TestFormParams(t *testing.T) {

	responseWriter := new(http_test.TestResponseWriter)
	testRequest, _ := http.NewRequest("POST", "http://goweb.org/people/123?query=yes", strings.NewReader("name=Mat&name=Laurie&age=30&something=true"))
	testRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	codecService := codecsservices.NewWebCodecService()

	c := NewWebContext(responseWriter, testRequest, codecService)

	params := c.FormParams()

	if assert.NotNil(t, params) {

		assert.Equal(t, "Mat", params.Get("name").StrSlice()[0])
		assert.Equal(t, "Laurie", params.Get("name").StrSlice()[1])
		assert.Equal(t, "30", params.Get("age").StrSlice()[0])
		assert.Equal(t, "true", params.Get("something").StrSlice()[0])
		assert.Equal(t, "yes", params.Get("query").StrSlice()[0])

	}

}
Example #23
0
// TestOn is the same as the goweb.Test function, except it allows you
// to explicitly specify the HttpHandler on which to run the tests.
func TestOn(t *testing.T, handler *handlers.HttpHandler, options ...interface{}) {

	/*
	   Get the request builder function
	*/

	var requestBuilder RequestBuilderFunc

	switch options[0].(type) {
	case string:
		// Test(t, "GET people/123", func)

		// split out the method and path
		methodAndPath := strings.Split(options[0].(string), " ")

		// make sure we have a method and a path
		if !assert.Equal(t, 2, len(methodAndPath), "goweb: First options argument of goweb.Test, if a string, must follow the format \"METHOD path\", and cannot be \"%s\".", options[0]) {
			return
		}

		var method string = methodAndPath[0]
		var path string = methodAndPath[1]
		var body string

		// do we have a body?
		switch options[1].(type) {
		case []byte:
			body = string(options[1].([]byte))
		case string:
			body = options[1].(string)
		}

		// set the builder
		requestBuilder = func() *http.Request {

			httpRequest, httpRequestError := http.NewRequest(method, path, strings.NewReader(body))

			if httpRequestError != nil {
				t.Errorf("goweb: Could not build request: %s", httpRequestError)
			}

			return httpRequest

		}

	case RequestBuilderFunc:

		// just use their method
		requestBuilder = options[0].(RequestBuilderFunc)

	default:
		t.Errorf("goweb: First options argument of goweb.Test must be either a string, or a RequestBuilderFunc, not %v.", reflect.TypeOf(options[0]))
		return
	}

	/*
	   Get the response assertion function
	*/
	var testAssertionFunc func(*testing.T, *testifyhttp.TestResponseWriter)

	switch options[len(options)-1].(type) {
	case func(*testing.T, *testifyhttp.TestResponseWriter):

		testAssertionFunc = options[len(options)-1].(func(*testing.T, *testifyhttp.TestResponseWriter))

	default:
		t.Errorf("goweb: Last options argument of goweb.Test must be a func(*testing.T, *testifyhttp.TestResponseWriter), not %v.", reflect.TypeOf(options[len(options)-1]))
		return
	}

	/*
	   Get the TestRequest using the builder function
	*/
	TestHttpRequest = requestBuilder()

	// make sure it's not nil
	if !assert.NotNil(t, TestHttpRequest, "goweb: RequestBuilderFunc must return a *TestRequest object.") {
		return
	}

	/*
	   Build a context to use
	*/
	TestResponseWriter = new(testifyhttp.TestResponseWriter)

	/*
	   Ask Goweb to handle the context
	*/
	handler.ServeHTTP(TestResponseWriter, TestHttpRequest)

	/*
	   Over to the func(*testing.T, *testifyhttp.TestResponseWriter) to do its magic
	*/
	testAssertionFunc(t, TestResponseWriter)

}
Example #24
0
func TestGetCodecForResponding(t *testing.T) {

	service := NewWebCodecService()
	var codec codecs.Codec

	// JSON - accept header

	codec, _ = service.GetCodecForResponding("something/something,application/json,text/xml", "", false)

	if assert.NotNil(t, codec, "Return of GetCodecForAcceptStringOrExtension") {
		assert.Equal(t, constants.ContentTypeJSON, codec.ContentType(), "ContentTypeJson 1")
	}

	// JSON - accept header (case)

	codec, _ = service.GetCodecForResponding("something/something,application/JSON,text/xml", "", false)

	if assert.NotNil(t, codec, "Case should not matter") {
		assert.Equal(t, constants.ContentTypeJSON, codec.ContentType(), "Case should not matter")
	}

	// JSON - file extension

	codec, _ = service.GetCodecForResponding("", constants.FileExtensionJSON, false)

	if assert.NotNil(t, codec, "Return of GetCodecForAcceptStringOrExtension") {
		assert.Equal(t, constants.ContentTypeJSON, codec.ContentType(), "ContentTypeJson")
	}

	// JSONP - has callback

	codec, _ = service.GetCodecForResponding("", "", true)

	if assert.NotNil(t, codec, "Should return the first codec that can handle a callback") {
		assert.Equal(t, constants.ContentTypeJSONP, codec.ContentType(), "ContentTypeJavaScript")
	}

	// JSONP - file extension

	codec, _ = service.GetCodecForResponding("", constants.FileExtensionJSONP, false)

	if assert.NotNil(t, codec, "Return of GetCodecForAcceptStringOrExtension") {
		assert.Equal(t, constants.ContentTypeJSONP, codec.ContentType(), "ContentTypeJavaScript")
	}

	// JSONP - file extension (case)

	codec, _ = service.GetCodecForResponding("", strings.ToUpper(constants.FileExtensionJSONP), false)

	if assert.NotNil(t, codec, "Return of GetCodecForAcceptStringOrExtension") {
		assert.Equal(t, constants.ContentTypeJSONP, codec.ContentType(), "ContentTypeJavaScript 4")
	}

	// JSONP - Accept header

	codec, _ = service.GetCodecForResponding("something/something,text/javascript,text/xml", "", false)

	if assert.NotNil(t, codec, "Return of GetCodecForAcceptStringOrExtension") {
		assert.Equal(t, constants.ContentTypeJSONP, codec.ContentType(), "ContentTypeJavaScript 5")
	}

	// hasCallback takes precedence over everything else

	codec, _ = service.GetCodecForResponding(constants.ContentTypeJSON, constants.FileExtensionXML, true)

	if assert.NotNil(t, codec, "Return of GetCodecForAcceptStringOrExtension") {
		assert.Equal(t, constants.ContentTypeJSONP, codec.ContentType(), "HasCallback takes precedence over all")
	}

	// File extension takes precedence over accept header

	codec, _ = service.GetCodecForResponding(constants.ContentTypeJSON, constants.FileExtensionXML, false)

	if assert.NotNil(t, codec, "Return of GetCodecForAcceptStringOrExtension") {
		assert.Equal(t, constants.ContentTypeXML, codec.ContentType(), "Extension takes precedence over accept")
	}

}