Exemplo n.º 1
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")

}
Exemplo n.º 2
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")
	}

}
Exemplo n.º 3
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

}
Exemplo n.º 4
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")
	}

}
Exemplo n.º 5
0
func TestPathMatchHandler(t *testing.T) {

	pathPattern, _ := paths.NewPathPattern("collection/{id}/name")
	var called bool = false
	h := NewPathMatchHandler(pathPattern, HandlerExecutionFunc(func(c context.Context) error {
		called = true
		return nil
	}))

	ctx1 := context_test.MakeTestContextWithPath("/collection/123/name")
	will, _ := h.WillHandle(ctx1)
	assert.True(t, will)
	h.Handle(ctx1)
	assert.True(t, called, "Method should be called")
	assert.Equal(t, "123", ctx1.Data().Get(context.DataKeyPathParameters).ObjxMap().Get("id").Data())

	ctx2 := context_test.MakeTestContextWithPath("/collection")
	will, _ = h.WillHandle(ctx2)
	assert.False(t, will)
	assert.Nil(t, ctx2.Data().Get(context.DataKeyPathParameters).Data())

	h.BreakCurrentPipeline = true
	shouldStop, handleErr := h.Handle(ctx2)
	assert.Nil(t, handleErr)
	assert.True(t, shouldStop)
	assert.True(t, called, "Handler func should get called")

}
Exemplo n.º 6
0
func TestAcceptEntry_Specificity(t *testing.T) {
	greater := &AcceptEntry{
		Quality:          1.0,
		specificityCount: 2,
	}
	lesser := &AcceptEntry{
		Quality:          1.0,
		specificityCount: 1,
	}
	assert.True(t, greater.CompareTo(lesser) > 0, "At equal quality, higher specificity should come out greater")
	assert.True(t, lesser.CompareTo(greater) < 0, "Comparing in opposite direction should provide opposite result")
}
Exemplo n.º 7
0
func TestAcceptEntry_Quality(t *testing.T) {
	greater := &AcceptEntry{
		Quality:          0.8,
		specificityCount: 0,
	}
	lesser := &AcceptEntry{
		Quality:          0.3,
		specificityCount: 10,
	}
	assert.True(t, greater.CompareTo(lesser) > 0, "Higher quality should come out greater")
	assert.True(t, lesser.CompareTo(greater) < 0, "Comparing in opposite direction should provide opposite result")
}
Exemplo n.º 8
0
func Test_Mock_AssertNumberOfCalls(t *testing.T) {

	var mockedService *TestExampleImplementation = new(TestExampleImplementation)

	mockedService.Mock.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7)

	mockedService.Mock.Called(1, 2, 3)
	assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1))

	mockedService.Mock.Called(1, 2, 3)
	assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2))

}
Exemplo n.º 9
0
func TestMapStatic(t *testing.T) {

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

	h.MapStatic("/static", "/location/of/static")

	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/some/deep/file.dat")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

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

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

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

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

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

	ctx = context_test.MakeTestContextWithPath("/static/doc.go")
	willHandle, _ = staticHandler.WillHandle(ctx)
	_, staticHandleErr := staticHandler.Handle(ctx)

	if assert.NoError(t, staticHandleErr) {

	}

}
Exemplo n.º 10
0
func TestSimpleExample(t *testing.T) {

	// build a map from a JSON object
	o := MustFromJSON(`{"name":"Mat","foods":["indian","chinese"], "location":{"county":"hobbiton","city":"the shire"}}`)

	// Map can be used as a straight map[string]interface{}
	assert.Equal(t, o["name"], "Mat")

	// Get an Value object
	v := o.Get("name")
	assert.Equal(t, v, &Value{data: "Mat"})

	// Test the contained value
	assert.False(t, v.IsInt())
	assert.False(t, v.IsBool())
	assert.True(t, v.IsStr())

	// Get the contained value
	assert.Equal(t, v.Str(), "Mat")

	// Get a default value if the contained value is not of the expected type or does not exist
	assert.Equal(t, 1, v.Int(1))

	// Get a value by using array notation
	assert.Equal(t, "indian", o.Get("foods[0]").Data())

	// Set a value by using array notation
	o.Set("foods[0]", "italian")
	assert.Equal(t, "italian", o.Get("foods[0]").Str())

	// Get a value by using dot notation
	assert.Equal(t, "hobbiton", o.Get("location.county").Str())

}
Exemplo n.º 11
0
func Test_Arguments_Assert(t *testing.T) {

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

	assert.True(t, args.Assert(t, "string", 123, true))

}
Exemplo n.º 12
0
// AssertCalled asserts that the method was called.
func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool {
	if !assert.True(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method should have been called with %d argument(s), but was not.", methodName, len(arguments))) {
		t.Logf("%s", m.ExpectedCalls)
		return false
	}
	return true
}
Exemplo n.º 13
0
func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) {

	var mockedService *TestExampleImplementation = new(TestExampleImplementation)

	mockedService.Mock.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once()
	mockedService.Mock.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once()

	mockedService.Mock.Called(1, 2, 3)
	mockedService.Mock.Called(2, 3, 4)

	tt := new(testing.T)
	assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3))
	assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4))
	assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5))

}
Exemplo n.º 14
0
func TestPathMatchHandler_BreakCurrentPipeline(t *testing.T) {

	pathPattern, _ := paths.NewPathPattern("collection/{id}/name")
	h := NewPathMatchHandler(pathPattern, HandlerExecutionFunc(func(c context.Context) error {
		return nil
	}))
	h.BreakCurrentPipeline = true

	ctx1 := context_test.MakeTestContextWithPath("/collection/123/name")

	breakCurrentPipeline, _ := h.Handle(ctx1)

	assert.True(t, breakCurrentPipeline)

	h = NewPathMatchHandler(pathPattern, HandlerExecutionFunc(func(c context.Context) error {
		return nil
	}))
	h.BreakCurrentPipeline = false

	ctx1 = context_test.MakeTestContextWithPath("/collection/123/name")

	breakCurrentPipeline, _ = h.Handle(ctx1)

	assert.False(t, breakCurrentPipeline)

}
Exemplo n.º 15
0
func Test_Arguments_Is(t *testing.T) {

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

	assert.True(t, args.Is("string", 123, true))
	assert.False(t, args.Is("wrong", 456, false))

}
Exemplo n.º 16
0
func TestNewPathMatchHandler(t *testing.T) {

	pathPattern, _ := paths.NewPathPattern("collection/{id}/name")
	var called bool = false
	h := NewPathMatchHandler(pathPattern, HandlerExecutionFunc(func(c context.Context) error {
		called = true
		return nil
	}))

	ctx1 := context_test.MakeTestContextWithPath("/collection/123/name")
	will, _ := h.WillHandle(ctx1)
	assert.True(t, will)
	h.Handle(ctx1)
	assert.True(t, called, "Method should be called")
	assert.Equal(t, "123", ctx1.Data().Get(context.DataKeyPathParameters).ObjxMap().Get("id").Data())

}
Exemplo n.º 17
0
func TestHas(t *testing.T) {

	m := New(TestMap)

	assert.True(t, m.Has("name"))
	assert.True(t, m.Has("address.state"))
	assert.True(t, m.Has("numbers[4]"))

	assert.False(t, m.Has("address.state.nope"))
	assert.False(t, m.Has("address.nope"))
	assert.False(t, m.Has("nope"))
	assert.False(t, m.Has("numbers[5]"))

	m = nil
	assert.False(t, m.Has("nothing"))

}
Exemplo n.º 18
0
func TestPathPattern_GetPathMatch_Extensions(t *testing.T) {

	gp, _ := NewPathPattern("/people/{id}/books/{title}/chapters/{chapter}")
	m := gp.GetPathMatch(NewPath("people/123/books/origin.of.species/chapters/2.json"))

	assert.True(t, m.Matches)
	assert.Equal(t, m.Parameters["id"], "123")
	assert.Equal(t, m.Parameters["title"], "origin.of.species")
	assert.Equal(t, m.Parameters["chapter"], "2")

	gp, _ = NewPathPattern("/places/{ipaddress}/something")
	m = gp.GetPathMatch(NewPath("places/10.0.0.1/something"))

	assert.True(t, m.Matches)
	assert.Equal(t, m.Parameters["ipaddress"], "10.0.0.1")

}
Exemplo n.º 19
0
func TestIssue81(t *testing.T) {
	p, _ := NewPathPattern("/prefix/static/***")
	assert.NotPanics(t, func() {
		assert.False(t, p.GetPathMatch(NewPath("/prefix/")).Matches)
	})
	assert.True(t, p.GetPathMatch(NewPath("/prefix/static")).Matches)
	assert.False(t, p.GetPathMatch(NewPath("/static")).Matches)
}
Exemplo n.º 20
0
func TestPipe_WillHandle(t *testing.T) {

	p := new(Pipe)

	handle, _ := p.WillHandle(nil)
	assert.True(t, handle, "Pipes always will handle")

}
Exemplo n.º 21
0
func TestPathPattern_GetPathMatch_Parameters(t *testing.T) {

	gp, _ := NewPathPattern("/people/{id}/books/{title}/chapters/{chapter}")
	m := gp.GetPathMatch(NewPath("people/123/books/origin-of-species/chapters/2"))

	assert.True(t, m.Matches)
	assert.Equal(t, m.Parameters["id"], "123")
	assert.Equal(t, m.Parameters["title"], "origin-of-species")
	assert.Equal(t, m.Parameters["chapter"], "2")

}
Exemplo n.º 22
0
func TestMap_WithSpecificMethod(t *testing.T) {

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

	called := false
	handler.Map("GET", "/people/{id}", func(c context.Context) error {
		called = true
		return nil
	})

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

	ctx := context_test.MakeTestContextWithPath("people/123")
	handler.Handlers.Handle(ctx)

	assert.True(t, called)
	assert.Equal(t, "GET", handler.HandlersPipe()[0].(*PathMatchHandler).HttpMethods[0])
	assert.True(t, handler.HandlersPipe()[0].(*PathMatchHandler).BreakCurrentPipeline)

}
func TestWrapCodec_ContentType(t *testing.T) {
	codec := new(json.JsonCodec)
	testContentType := "application/vnd.stretchr.test+json"
	var target interface{} = wrapCodecWithContentType(codec, testContentType)

	wrappedCodec, ok := target.(codecs.Codec)
	assert.True(t, ok, "A wrapped codec should still be a Codec")

	if ok {
		assert.Equal(t, testContentType, wrappedCodec.ContentType())
	}
}
Exemplo n.º 24
0
func Test_Mock_AssertCalled_WithArguments(t *testing.T) {

	var mockedService *TestExampleImplementation = new(TestExampleImplementation)

	mockedService.Mock.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7)

	mockedService.Mock.Called(1, 2, 3)

	tt := new(testing.T)
	assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3))
	assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4))

}
Exemplo n.º 25
0
func TestMap_CatchAllAssumption(t *testing.T) {

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

	called := false
	handler.Map(func(c context.Context) error {
		called = true
		return nil
	})

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

	ctx := context_test.MakeTestContextWithPath("people/123")
	handler.Handlers.Handle(ctx)
	assert.True(t, called)

	called = false
	ctx = context_test.MakeTestContextWithPath("something-else")
	handler.Handlers.Handle(ctx)
	assert.True(t, called)

}
Exemplo n.º 26
0
func Test_Mock_AssertExpectations(t *testing.T) {

	var mockedService *TestExampleImplementation = new(TestExampleImplementation)

	mockedService.Mock.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7)

	tt := new(testing.T)
	assert.False(t, mockedService.AssertExpectations(tt))

	// make the call now
	mockedService.Mock.Called(1, 2, 3)

	// now assert expectations
	assert.True(t, mockedService.AssertExpectations(tt))

}
Exemplo n.º 27
0
func TestParseContentType_WithParams(t *testing.T) {
	contentTypeString := "application/xml; q=0.7; test=hello"
	expectedMimeType := "application/xml"
	expectedParams := map[string]string{
		"q":    "0.7",
		"test": "hello",
	}
	contentType, err := ParseContentType(contentTypeString)
	assert.NoError(t, err)
	assert.Equal(t, expectedMimeType, contentType.MimeType)
	for index, value := range expectedParams {
		parsedValue, ok := contentType.Parameters[index]
		assert.True(t, ok, "All expected values should have been parsed as params")
		assert.Equal(t, parsedValue, value)
	}
}
Exemplo n.º 28
0
func Test_Mock_AssertExpectationsCustomType(t *testing.T) {

	var mockedService *TestExampleImplementation = new(TestExampleImplementation)

	mockedService.Mock.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once()

	tt := new(testing.T)
	assert.False(t, mockedService.AssertExpectations(tt))

	// make the call now
	mockedService.TheExampleMethod3(&ExampleType{})

	// now assert expectations
	assert.True(t, mockedService.AssertExpectations(tt))

}
Exemplo n.º 29
0
func Test_AssertExpectationsForObjects_Helper(t *testing.T) {

	var mockedService1 *TestExampleImplementation = new(TestExampleImplementation)
	var mockedService2 *TestExampleImplementation = new(TestExampleImplementation)
	var mockedService3 *TestExampleImplementation = new(TestExampleImplementation)

	mockedService1.Mock.On("Test_AssertExpectationsForObjects_Helper", 1).Return()
	mockedService2.Mock.On("Test_AssertExpectationsForObjects_Helper", 2).Return()
	mockedService3.Mock.On("Test_AssertExpectationsForObjects_Helper", 3).Return()

	mockedService1.Called(1)
	mockedService2.Called(2)
	mockedService3.Called(3)

	assert.True(t, AssertExpectationsForObjects(t, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock))

}
Exemplo n.º 30
0
func TestPathPattern_GetPathMatchCatchallPrefixSuffix_Matches(t *testing.T) {
	// ***/literal/***
	gp, _ := NewPathPattern("/***/books/***")

	assert.True(t, gp.GetPathMatch(NewPath("/people/123/books")).Matches)
	assert.True(t, gp.GetPathMatch(NewPath("/PEOPLE/123/BOOKS")).Matches)
	assert.True(t, gp.GetPathMatch(NewPath("/People/123/Books")).Matches)
	assert.True(t, gp.GetPathMatch(NewPath("people/123/books")).Matches)
	assert.True(t, gp.GetPathMatch(NewPath("people/123/books/")).Matches)
	assert.True(t, gp.GetPathMatch(NewPath("/people/123/books/lotr/chapters/one")).Matches)
	assert.True(t, gp.GetPathMatch(NewPath("/people/123/books/hello")).Matches)
	assert.True(t, gp.GetPathMatch(NewPath("/books")).Matches)

	assert.False(t, gp.GetPathMatch(NewPath("people/123/[books]/")).Matches)
	assert.False(t, gp.GetPathMatch(NewPath("people/123/{books}/")).Matches)
	assert.False(t, gp.GetPathMatch(NewPath("/people/123/novels/lotr/chapters/one")).Matches)
	assert.False(t, gp.GetPathMatch(NewPath("/people/123/novels/hello")).Matches)

}