Esempio n. 1
0
func TestMatcherFuncDecision(t *testing.T) {

	assert.Equal(t, MatcherFuncDecision(-1), DontCare)
	assert.Equal(t, MatcherFuncDecision(0), NoMatch)
	assert.Equal(t, MatcherFuncDecision(1), Match)

}
Esempio n. 2
0
func TestPath_cleanPath(t *testing.T) {

	assert.Equal(t, "people/123/books", cleanPath("/people/123/books/"))
	assert.Equal(t, "people/123/books", cleanPath("//people/123/books/"))
	assert.Equal(t, "people/123/books", cleanPath("//people/123/books////"))

}
Esempio n. 3
0
func TestPublicData_WithArray(t *testing.T) {

	o := new(test.TestObjectWithFacade)
	o1 := new(test.TestObjectWithFacade)
	o2 := new(test.TestObjectWithFacade)

	arr := []interface{}{o, o1, o2}

	o.Mock.On("PublicData", map[string]interface{}{}).Return(objx.New(map[string]interface{}{"theName": "1"}), nil)
	o1.Mock.On("PublicData", map[string]interface{}{}).Return(objx.New(map[string]interface{}{"theName": "2"}), nil)
	o2.Mock.On("PublicData", map[string]interface{}{}).Return(objx.New(map[string]interface{}{"theName": "3"}), nil)

	public, err := PublicData(arr, map[string]interface{}{})

	if assert.Nil(t, err) {
		assert.Equal(t, reflect.Slice, reflect.TypeOf(public).Kind(), "Result should be array not %v", reflect.TypeOf(public))
	}

	mock.AssertExpectationsForObjects(t, o.Mock, o1.Mock, o2.Mock)

	publicArray := public.([]interface{})
	if assert.Equal(t, 3, len(publicArray)) {
		assert.Equal(t, publicArray[0].(objx.Map).Get("theName").Str(), "1", "o")
		assert.Equal(t, publicArray[1].(objx.Map).Get("theName").Str(), "2", "o1")
		assert.Equal(t, publicArray[2].(objx.Map).Get("theName").Str(), "3", "o2")
	}

}
Esempio n. 4
0
func TestFileExtension(t *testing.T) {

	responseWriter := new(http_test.TestResponseWriter)
	codecService := codecsservices.NewWebCodecService()

	testRequest, _ := http.NewRequest("get", "http://goweb.org/people/123.json", nil)
	c := NewWebContext(responseWriter, testRequest, codecService)
	assert.Equal(t, ".json", c.FileExtension())

	testRequest, _ = http.NewRequest("get", "http://goweb.org/people/123.bson", nil)
	c = NewWebContext(responseWriter, testRequest, codecService)
	assert.Equal(t, ".bson", c.FileExtension())

	testRequest, _ = http.NewRequest("get", "http://goweb.org/people/123.xml", nil)
	c = NewWebContext(responseWriter, testRequest, codecService)
	assert.Equal(t, ".xml", c.FileExtension())

	testRequest, _ = http.NewRequest("get", "http://goweb.org/people.with.dots/123.xml", nil)
	c = NewWebContext(responseWriter, testRequest, codecService)
	assert.Equal(t, ".xml", c.FileExtension())

	testRequest, _ = http.NewRequest("get", "http://goweb.org/people.with.dots/123.xml?a=b", nil)
	c = NewWebContext(responseWriter, testRequest, codecService)
	assert.Equal(t, ".xml", c.FileExtension())

}
Esempio n. 5
0
func TestRequestData(t *testing.T) {

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

	codecService := codecsservices.NewWebCodecService()

	c := NewWebContext(responseWriter, testRequest, codecService)

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

	if assert.NoError(t, datErr) {
		assert.Equal(t, true, dat.(map[string]interface{})["something"])
	}

	responseWriter = new(http_test.TestResponseWriter)
	testRequest, _ = http.NewRequest("GET", "http://goweb.org/people/123?body={\"something\":true}", nil)

	codecService = codecsservices.NewWebCodecService()

	c = NewWebContext(responseWriter, testRequest, codecService)

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

	if assert.NoError(t, datErr) {
		assert.Equal(t, true, dat.(map[string]interface{})["something"])
	}

}
Esempio n. 6
0
func TestMapStaticFile(t *testing.T) {

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

	h.MapStaticFile("/static-file", "/location/of/static-file")

	assert.Equal(t, 1, len(h.HandlersPipe()))

	staticHandler := h.HandlersPipe()[0].(*PathMatchHandler)

	if assert.Equal(t, 1, len(staticHandler.HttpMethods)) {
		assert.Equal(t, goweb_http.MethodGet, staticHandler.HttpMethods[0])
	}

	var ctx context.Context
	var willHandle bool

	ctx = context_test.MakeTestContextWithPath("/static-file")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

	ctx = context_test.MakeTestContextWithPath("static-file")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

	ctx = context_test.MakeTestContextWithPath("static-file/")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

	ctx = context_test.MakeTestContextWithPath("static-file/something-else")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.False(t, willHandle, "Static handler NOT should handle")

}
Esempio n. 7
0
func TestRegexPath(t *testing.T) {

	pattern := `^[a-z]+\[[0-9]+\]$`
	matcherFunc := RegexPath(pattern)

	var ctx context.Context
	var decision MatcherFuncDecision

	ctx = context_test.MakeTestContextWithPath("adam[23]")
	decision, _ = matcherFunc(ctx)
	assert.Equal(t, Match, decision, "adam[23] should match")

	ctx = context_test.MakeTestContextWithPath("eve[7]")
	decision, _ = matcherFunc(ctx)
	assert.Equal(t, Match, decision, "eve[7] should match")

	ctx = context_test.MakeTestContextWithPath("Job[23]")
	decision, _ = matcherFunc(ctx)
	assert.Equal(t, NoMatch, decision, "Job[23] should NOT match")

	ctx = context_test.MakeTestContextWithPath("snakey")
	decision, _ = matcherFunc(ctx)
	assert.Equal(t, NoMatch, decision, "snakey should NOT match")

}
Esempio n. 8
0
func TestPrependPreHandler(t *testing.T) {

	handler1 := new(handlers_test.TestHandler)
	handler2 := new(handlers_test.TestHandler)
	codecService := codecsservices.NewWebCodecService()
	h := NewHttpHandler(codecService)

	handler1.TestData().Set("id", 1)
	handler2.TestData().Set("id", 2)

	handler1.On("WillHandle", mock.Anything).Return(true, nil)
	handler1.On("Handle", mock.Anything).Return(false, nil)
	handler2.On("WillHandle", mock.Anything).Return(true, nil)
	handler2.On("Handle", mock.Anything).Return(false, nil)

	h.PrependPreHandler(handler1)
	h.PrependPreHandler(handler2)
	h.Handlers.Handle(nil)
	assert.Equal(t, 2, len(h.PreHandlersPipe()))

	assert.Equal(t, 2, h.PreHandlersPipe()[0].(*handlers_test.TestHandler).TestData().Get("id").Data())
	assert.Equal(t, 1, h.PreHandlersPipe()[1].(*handlers_test.TestHandler).TestData().Get("id").Data())

	mock.AssertExpectationsForObjects(t, handler1.Mock)

}
Esempio n. 9
0
func TestMarshalValue(t *testing.T) {

	assert.Equal(t, "\"str\"", getMarshalValue("str"))
	assert.Equal(t, "18", getMarshalValue(18))
	assert.Equal(t, "true", getMarshalValue(true))

}
Esempio n. 10
0
func TestAccessorsAccessGetDeep(t *testing.T) {

	current := map[string]interface{}{"name": map[string]interface{}{"first": "Tyler", "last": "Bunnell"}}
	assert.Equal(t, "Tyler", access(current, "name.first", nil, false, true))
	assert.Equal(t, "Bunnell", access(current, "name.last", nil, false, true))

}
Esempio n. 11
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())
		}
	}

}
Esempio n. 12
0
func TestRespondEnvelopOptions(t *testing.T) {

	http := new(GowebHTTPResponder)
	codecService := codecsservices.NewWebCodecService()
	API := NewGowebAPIResponder(codecService, http)
	ctx := context_test.MakeTestContextWithPath("/?envelop=false")
	data := map[string]interface{}{"name": "Mat"}

	// When AlwaysEvenlopResponse = true but ?envelop=false
	API.Respond(ctx, 200, data, nil)
	assert.Equal(t, context_test.TestResponseWriter.Output, "{\"name\":\"Mat\"}")

	// When AlwaysEvenlopResponse = false
	ctx = context_test.MakeTestContext()
	API.AlwaysEnvelopResponse = false

	API.Respond(ctx, 200, data, nil)
	assert.Equal(t, context_test.TestResponseWriter.Output, "{\"name\":\"Mat\"}")

	// When AlwaysEvenlopResponse = false but ?envelop=true
	ctx = context_test.MakeTestContextWithPath("/?envelop=true")

	API.Respond(ctx, 200, data, nil)
	assert.Equal(t, context_test.TestResponseWriter.Output, "{\"d\":{\"name\":\"Mat\"},\"s\":200}")

}
Esempio n. 13
0
func TestBeforeHandler(t *testing.T) {

	cont := new(controllers_test.TestHandlerWithBeforeAndAfters)

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

	h.MapController(cont)

	log.Printf("%s", h)

	if assert.Equal(t, 2, len(h.PreHandlersPipe()), "2 pre handler's expected") {
		assertPathMatchHandler(t, h.PreHandlersPipe()[0].(*PathMatchHandler), "/test", "POST", "before POST /test")
		assertPathMatchHandler(t, h.PreHandlersPipe()[1].(*PathMatchHandler), "/test/123", "PUT", "before PUT /test/123")
		assertPathMatchHandler(t, h.PreHandlersPipe()[0].(*PathMatchHandler), "/test", "OPTIONS", "before OPTIONS /test")
		assertPathMatchHandler(t, h.PreHandlersPipe()[1].(*PathMatchHandler), "/test/123", "OPTIONS", "before OPTIONS /test/123")
	}

	if assert.Equal(t, 2, len(h.PostHandlersPipe()), "2 post handler's expected") {
		assertPathMatchHandler(t, h.PostHandlersPipe()[0].(*PathMatchHandler), "/test", "POST", "after POST /test")
		assertPathMatchHandler(t, h.PostHandlersPipe()[1].(*PathMatchHandler), "/test/123", "PUT", "after PUT /test/123")
		assertPathMatchHandler(t, h.PostHandlersPipe()[0].(*PathMatchHandler), "/test", "OPTIONS", "after OPTIONS /test")
		assertPathMatchHandler(t, h.PostHandlersPipe()[1].(*PathMatchHandler), "/test/123", "OPTIONS", "after OPTIONS /test/123")
	}

}
Esempio n. 14
0
func TestUnMarshal_ObjxMap(t *testing.T) {

	obj1 := objx.MSI("name", "Mat", "age", 30, "language", "en")
	obj2 := objx.MSI("obj", obj1)
	obj3 := objx.MSI("another_obj", obj2)

	csvCodec := new(CsvCodec)
	bytes, _ := csvCodec.Marshal(obj3, nil)

	log.Printf("bytes = %s", string(bytes))

	// unmarshal it back
	var obj interface{}
	csvCodec.Unmarshal(bytes, &obj)

	if objmap, ok := obj.(map[string]interface{}); ok {
		if objmap2, ok := objmap["another_obj"].(map[string]interface{}); ok {
			if objmap3, ok := objmap2["obj"].(map[string]interface{}); ok {

				assert.Equal(t, "Mat", objmap3["name"])
				assert.Equal(t, 30, objmap3["age"])
				assert.Equal(t, "en", objmap3["language"])

			} else {
				assert.True(t, false, "another_obj.obj should be msi")
			}
		} else {
			assert.True(t, false, "another_obj should be msi")
		}
	} else {
		assert.True(t, false, "obj should be msi")
	}

}
Esempio n. 15
0
func TestErrorHandlerGetsUsedOnError(t *testing.T) {

	responseWriter := new(http_test.TestResponseWriter)
	testRequest, _ := http.NewRequest("GET", "http://stretchr.org/goweb", nil)

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

	errorHandler := new(handlers_test.TestHandler)
	handler.SetErrorHandler(errorHandler)

	errorHandler.On("Handle", mock.Anything).Return(false, nil)

	// make a handler throw an error
	var theError error = errors.New("Test error")
	handler.Map(func(c context.Context) error {
		return theError
	})

	handler.ServeHTTP(responseWriter, testRequest)

	if mock.AssertExpectationsForObjects(t, errorHandler.Mock) {

		// get the first context
		ctx := errorHandler.Calls[0].Arguments[0].(context.Context)

		// make sure the error data field was set
		assert.Equal(t, theError.Error(), ctx.Data().Get("error").Data().(HandlerError).Error(), "the error should be set in the data with the 'error' key")

		assert.Equal(t, responseWriter, ctx.HttpResponseWriter())
		assert.Equal(t, testRequest, ctx.HttpRequest())

	}

}
Esempio n. 16
0
func TestParseAccept_NoParams(t *testing.T) {
	acceptString := "application/json"
	accept, err := ParseAcceptEntry(acceptString)
	assert.NoError(t, err, acceptString+" should parse with no errors")
	assert.Equal(t, acceptString, accept.ContentType.MimeType)
	assert.Equal(t, accept.Quality, 1.0)
}
Esempio n. 17
0
func TestUnMarshal_ComplexMap(t *testing.T) {

	obj1 := map[string]interface{}{"name": "Mat", "age": 30, "language": "en"}
	obj2 := map[string]interface{}{"obj": obj1}
	obj3 := map[string]interface{}{"another_obj": obj2}

	csvCodec := new(CsvCodec)
	bytes, _ := csvCodec.Marshal(obj3, nil)

	// unmarshal it back
	var obj interface{}
	csvCodec.Unmarshal(bytes, &obj)

	if objmap, ok := obj.(map[string]interface{}); ok {
		if objmap2, ok := objmap["another_obj"].(map[string]interface{}); ok {
			if objmap3, ok := objmap2["obj"].(map[string]interface{}); ok {

				assert.Equal(t, "Mat", objmap3["name"])
				assert.Equal(t, 30, objmap3["age"])
				assert.Equal(t, "en", objmap3["language"])

			} else {
				assert.True(t, false, "another_obj.obj should be msi")
			}
		} else {
			assert.True(t, false, "another_obj should be msi")
		}
	} else {
		assert.True(t, false, "obj should be msi")
	}

}
Esempio n. 18
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")
		}
	}

}
Esempio n. 19
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.")
	}

}
Esempio n. 20
0
func TestCleanSegmentName(t *testing.T) {

	assert.Equal(t, "id", cleanSegmentName("id"))
	assert.Equal(t, "id", cleanSegmentName("{id}"))
	assert.Equal(t, "id", cleanSegmentName("[id]"))

}
Esempio n. 21
0
func TestUnmarshalValue(t *testing.T) {

	assert.Equal(t, "str", getUnmarshalValue("\"str\""))
	assert.Equal(t, "str", getUnmarshalValue("str"))
	assert.Equal(t, 18, getUnmarshalValue("18"))
	assert.Equal(t, true, getUnmarshalValue("true"))

}
Esempio n. 22
0
func TestRedirectTo(t *testing.T) {

	r := new(testhttp.TestResponseWriter)
	RedirectTo(r, "http://www.stretchr.com", "test")
	assert.Equal(t, "http://www.stretchr.com/test", r.Header().Get("Location"))
	assert.Equal(t, 0, r.StatusCode)

}
Esempio n. 23
0
/*
	Arguments helper methods
*/
func Test_Arguments_Get(t *testing.T) {

	var args Arguments = []interface{}{"string", 123, true}

	assert.Equal(t, "string", args.Get(0).(string))
	assert.Equal(t, 123, args.Get(1).(int))
	assert.Equal(t, true, args.Get(2).(bool))

}
Esempio n. 24
0
func TestNewHttpHandler(t *testing.T) {

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

	assert.Equal(t, 3, len(h.Handlers))
	assert.Equal(t, codecService, h.CodecService())

}
Esempio n. 25
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())
	}

}
Esempio n. 26
0
func Test_Mock_On(t *testing.T) {

	// make a test impl object
	var mockedService *TestExampleImplementation = new(TestExampleImplementation)

	assert.Equal(t, mockedService.Mock.On("TheExampleMethod"), &mockedService.Mock)
	assert.Equal(t, "TheExampleMethod", mockedService.Mock.onMethodName)

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

	assert.Equal(t, segmentType(segmentTypeLiteral), getSegmentType("people"))
	assert.Equal(t, segmentType(segmentTypeDynamic), getSegmentType("{id}"))
	assert.Equal(t, segmentType(segmentTypeDynamicOptional), getSegmentType("[id]"))
	assert.Equal(t, segmentType(segmentTypeWildcard), getSegmentType(segmentWildcard))
	assert.Equal(t, segmentType(segmentTypeCatchall), getSegmentType(segmentCatchAll))

}
Esempio n. 28
0
func TestPathPrefixForClass(t *testing.T) {

	c := new(ChildController)
	assert.Equal(t, PathPrefixForClass(c), "child")

	c2 := new(ChildWithMultipleWordsController)
	assert.Equal(t, PathPrefixForClass(c2), "child-with-multiple-words")

}
Esempio n. 29
0
func TestOptionsListForSingleResource(t *testing.T) {
	codecService := codecsservices.NewWebCodecService()
	h := NewHttpHandler(codecService)
	c := new(test.TestController)
	assert.Equal(t, "GET,DELETE,PATCH,PUT,HEAD,OPTIONS", strings.Join(optionsListForSingleResource(h, c), ","))

	c2 := new(test.TestSemiRestfulController)
	assert.Equal(t, "GET,OPTIONS", strings.Join(optionsListForSingleResource(h, c2), ","))

}
Esempio n. 30
0
func TestAccessorsAccessSetSingleField(t *testing.T) {

	current := map[string]interface{}{"name": "Tyler"}
	access(current, "name", "Mat", true, false)
	assert.Equal(t, current["name"], "Mat")

	access(current, "age", 29, true, true)
	assert.Equal(t, current["age"], 29)

}