示例#1
0
func equalNodes(expected, actual *node) error {
	if ec, ac := len(expected.children), len(actual.children); ec != ac {
		return fmt.Errorf("Children count is not the same\n\tExpected: %d\n\tActual: %d", ec, ac)
	}

	if len(expected.children) == 0 {
		if !assert.ObjectsAreEqualValues(expected.value, actual.value) {
			return fmt.Errorf("Node values not equal\n\tExpected: %T %v\n\tActual: %T %v", expected.value, expected.value, actual.value, actual.value)
		}
		return nil
	}

	for child, n := range expected.children {
		n2, ok := actual.children[child]
		if !ok {
			return fmt.Errorf("Expected node to have child: %s", child)
		}

		err := equalNodes(n, n2)
		if err != nil {
			return err
		}
	}
	return nil
}
示例#2
0
func TestParseValidCases(t *testing.T) {
	// Valid Request
	src := `
		package test
		// @GET("/photos/{id}")
		type GetPhotoDetailsRequestBuilder interface {
			// @PATH("id")
			PhotoID(id string) GetPhotoDetailsRequestBuilder

			// @QUERY("image_size")
			ImageSize(size int) GetPhotoDetailsRequestBuilder

			// @FIELD("body")
			Body(body string) GetPhotoDetailsRequestBuilder

			// @HEADER("x-type")
			Type(t string) GetPhotoDetailsRequestBuilder

			// @PART("data")
			Data(d []byte) GetPhotoDetailsRequestBuilder

			// @SYNC("GetPhotoDetailsResponse")
			Run() (GetPhotoDetailsResponse, error)

			// @ASYNC("GetPhotoDetailsCallback")
			RunAsync(callback GetPhotoDetailsCallback)
		}
		`
	expectedResult := &ParseResult{
		PackageName:         "test",
		PathSubstitutions:   make(map[string]*ast.Field),
		QueryParams:         make(map[string]*ast.Field),
		PostFormParams:      make(map[string]*ast.Field),
		PostMultiPartParams: make(map[string]*ast.Field),
		PostParams:          make(map[string]*ast.Field),
		HeaderParams:        make(map[string]*ast.Field),
		RequestType:         "GetPhotoDetailsRequestBuilder",
		ApiEndpoint:         "/photos/{id}",
		HttpMethod:          "GET",
	}

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "input.go", src, parser.ParseComments)
	assert.NoError(t, err)

	interfaceDecl := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type.(*ast.InterfaceType)
	expectedResult.PathSubstitutions["id"] = interfaceDecl.Methods.List[0]
	expectedResult.QueryParams["image_size"] = interfaceDecl.Methods.List[1]
	expectedResult.PostFormParams["body"] = interfaceDecl.Methods.List[2]
	expectedResult.HeaderParams["x-type"] = interfaceDecl.Methods.List[3]
	expectedResult.PostMultiPartParams["data"] = interfaceDecl.Methods.List[4]
	expectedResult.SyncResponse = interfaceDecl.Methods.List[5]
	expectedResult.AsyncResponse = interfaceDecl.Methods.List[6]
	p := NewParser(f, "")
	actualResult := p.Parse()
	assert.ObjectsAreEqualValues(expectedResult, actualResult)
}
示例#3
0
func TestWinnowing(t *testing.T) {
	input := []uint32{77, 72, 42, 17, 98, 50, 17, 98, 8, 88, 67, 39, 77, 72, 42, 17, 98}
	expected := []uint32{17, 17, 8, 39, 17}
	winnowing := Winnowing{4}
	fp, err := winnowing.processTokensToFingerPrint(input)
	if err != nil || !assert.ObjectsAreEqualValues(expected, fp.FingerPrint) {
		t.Errorf("TestWinnowing - Arrays not equal: %s %s", expected, fp.FingerPrint)
	}

}
func TestParseSearchStringDifferentURL(t *testing.T) {
	t.Parallel()
	resource.Require(t, resource.UnitTest)
	input := "http://demo.redhat.io"
	op, _ := parseSearchString(input)
	expectedSearchRes := searchKeyword{
		id:    nil,
		words: []string{"demo.redhat.io:*"},
	}
	assert.True(t, assert.ObjectsAreEqualValues(expectedSearchRes, op))
}
func TestParseSearchString(t *testing.T) {
	t.Parallel()
	resource.Require(t, resource.UnitTest)
	input := "user input for search string with some ids like id:99 and id:400 but this is not id like 800"
	op, _ := parseSearchString(input)
	expectedSearchRes := searchKeyword{
		id:    []string{"99:*A", "400:*A"},
		words: []string{"user:*", "input:*", "for:*", "search:*", "string:*", "with:*", "some:*", "ids:*", "like:*", "and:*", "but:*", "this:*", "is:*", "not:*", "id:*", "like:*", "800:*"},
	}
	assert.True(t, assert.ObjectsAreEqualValues(expectedSearchRes, op))
}
func TestParseSearchStringCombination(t *testing.T) {
	t.Parallel()
	resource.Require(t, resource.UnitTest)
	// do combination of ID, full text and URLs
	// check if it works as expected.
	input := "http://general.url.io http://demo.almighty.io/work-item/list/detail/100 id:300 golang book and           id:900 \t \n unwanted"
	op, _ := parseSearchString(input)
	expectedSearchRes := searchKeyword{
		id:    []string{"300:*A", "900:*A"},
		words: []string{"general.url.io:*", "(100:* | demo.almighty.io/work-item/list/detail/100:*)", "golang:*", "book:*", "and:*", "unwanted:*"},
	}
	assert.True(t, assert.ObjectsAreEqualValues(expectedSearchRes, op))
}
示例#7
0
// SQL tests that the given Compiles instance matches the expected string for
// the current dialect.
func (t *sqlTest) SQL(expect string, stmt Compiles, ps ...interface{}) {
	// Get caller information in case of failure
	caller := callerInfo()

	// Start a new parameters instance
	params := Params()

	// Compile the given stmt with the tester's dialect
	actual, err := stmt.Compile(t.dialect, params)
	if err != nil {
		t.t.Errorf("%s: unexpected error from Compile(): %s", caller, err)
		return
	}

	// Also test that the string output does not panic
	// TODO do we care about output?
	stmt.String()

	if expect != actual {
		t.t.Errorf(
			"%s: unexpected SQL from Compile(): expect %s, got %s",
			caller,
			expect,
			actual,
		)
	}
	// Test that the parameters are equal
	if params.Len() != len(ps) {
		t.t.Errorf(
			"%s: unexpected number of parameters for %s: expect %d, got %d",
			caller,
			actual,
			params.Len(),
			len(ps),
		)
		return
	}

	// Examine individual parameters for equality
	for i, param := range params.Args() {
		if !assert.ObjectsAreEqualValues(ps[i], param) {
			t.t.Errorf(
				"%s: unequal parameters at index %d: expect %#v, got %#v",
				caller,
				i,
				ps[i],
				param,
			)
		}
	}
}
func TestRegisterAsKnownURL(t *testing.T) {
	resource.Require(t, resource.UnitTest)
	// build 2 fake urls and cross check against RegisterAsKnownURL
	urlRegex := `(?P<domain>google.me.io)(?P<path>/everything/)(?P<param>.*)`
	routeName := "custom-test-route"
	RegisterAsKnownURL(routeName, urlRegex)
	compiledRegex := regexp.MustCompile(urlRegex)
	groupNames := compiledRegex.SubexpNames()
	var expected = make(map[string]KnownURL)
	expected[routeName] = KnownURL{
		URLRegex:          urlRegex,
		compiledRegex:     regexp.MustCompile(urlRegex),
		groupNamesInRegex: groupNames,
	}
	assert.True(t, assert.ObjectsAreEqualValues(expected[routeName], knownURLs[routeName]))
	//cleanup
	delete(knownURLs, routeName)
}
func TestParseSearchStringURL(t *testing.T) {
	t.Parallel()
	resource.Require(t, resource.UnitTest)
	inputSet := []searchTestData{{
		query: "http://demo.almighty.io/work-item/list/detail/100",
		expected: searchKeyword{
			id:    nil,
			words: []string{"(100:* | demo.almighty.io/work-item/list/detail/100:*)"},
		},
	}, {
		query: "http://demo.almighty.io/work-item/board/detail/100",
		expected: searchKeyword{
			id:    nil,
			words: []string{"(100:* | demo.almighty.io/work-item/board/detail/100:*)"},
		},
	}}

	for _, input := range inputSet {
		op, _ := parseSearchString(input.query)
		assert.True(t, assert.ObjectsAreEqualValues(input.expected, op))
	}
}
示例#10
0
func TestParseInvalidCases(t *testing.T) {
	type testCase struct {
		pkg string
		src string
	}

	var testCases = []struct {
		input  testCase
		output *ParseResult
	}{
		// Empty file
		{
			testCase{
				"main",
				`
				package main
				`,
			},
			newParseResult(""),
		},
		// File containing nothing to parse
		{
			testCase{
				"main",
				`
				package main
				func main() {
					println("Hello, World!")
				}
				`,
			},
			newParseResult("main"),
		},
		// File containing interface with missing http annotaiton
		{
			testCase{
				"test",
				`
				package test
				type InvalidRequest interface {
				}
				`,
			},
			newParseResult("test"),
		},
		// Invalid annotation
		{
			testCase{
				"test",
				`
				package test
				// @INVALID("invalid")
				type InvalidRequest interface {
				}
				`,
			},
			newParseResult("test"),
		},
		// Valid http request annotation
		{
			testCase{
				"test",
				`
				package test
				// @GET("/photos")
				type GetPhotosRequestBuilder interface {
				}
				`,
			},
			&ParseResult{
				PackageName:         "test",
				PathSubstitutions:   make(map[string]*ast.Field),
				QueryParams:         make(map[string]*ast.Field),
				PostFormParams:      make(map[string]*ast.Field),
				PostMultiPartParams: make(map[string]*ast.Field),
				PostParams:          make(map[string]*ast.Field),
				HeaderParams:        make(map[string]*ast.Field),
				RequestType:         "GetPhotosRequestBuilder",
				ApiEndpoint:         "/photos",
				HttpMethod:          "GET",
			},
		},
		// Invalid request annotation
		{
			testCase{
				"test",
				`
				package test
				// @GET("/photos")
				type GetPhotosRequestBuilder interface {
					// @INVALID("invalid")
					InvalidOp(i int) GetPhotosRequestBuilder
				}
				`,
			},
			&ParseResult{
				PackageName:         "test",
				PathSubstitutions:   make(map[string]*ast.Field),
				QueryParams:         make(map[string]*ast.Field),
				PostFormParams:      make(map[string]*ast.Field),
				PostMultiPartParams: make(map[string]*ast.Field),
				PostParams:          make(map[string]*ast.Field),
				HeaderParams:        make(map[string]*ast.Field),
				RequestType:         "GetPhotosRequestBuilder",
				ApiEndpoint:         "/photos",
				HttpMethod:          "GET",
			},
		},
	}

	for _, tc := range testCases {
		fset := token.NewFileSet()
		f, err := parser.ParseFile(fset, "input.go", tc.input.src, parser.ParseComments)
		assert.NoError(t, err)
		p := NewParser(f, "")
		result := p.Parse()
		assert.ObjectsAreEqualValues(tc.output, result)
	}
}