예제 #1
0
func (goPackage *GoPackage) measureCyclomaticComplexity(upperLimit int) error {
	for filePath, goFile := range goPackage.Pack.Files {
		srcFile, err := ioutil.ReadFile(filePath)
		if err != nil {
			return err
		}

		complexity, err := ccomplexity.GetCyclomaticComplexityFunctionLevel(filePath, srcFile)
		if err != nil {
			return err
		}

		for _, funCC := range complexity {
			if funCC.Complexity > upperLimit {

				goFile := &GoFile{
					FilePath:   filePath,
					goFileNode: goFile,
				}
				goFile.countLinesInFile()

				goFile.Violations = append(goFile.Violations, &Violation{
					Type:    CYCLOMATIC_COMPLEXITY,
					SrcLine: funCC.SrcLine,
					Description: fmt.Sprintf("Cyclomatic complexity in %s() is %d, upper limit is %d.",
						funCC.Name, funCC.Complexity, upperLimit),
				})
				goPackage.Violations = append(goPackage.Violations, goFile)
			}
		}
	}
	return nil
}
예제 #2
0
func TestIfElseComplexityFunctionLevel(t *testing.T) {
	filePath := "./testcode/_ifelse.go"
	srcFile, err := ioutil.ReadFile(filePath)
	if err != nil {
		t.Fatal(err)
	}
	expectedCyclomaticComplexity, err := ccomplexity.GetCyclomaticComplexityFunctionLevel(filePath, srcFile)
	if err != nil {
		t.Fatal(err)
	}

	correctCyclomaticComplexity := []ccomplexity.FunctionComplexity{
		{Name: "main", Complexity: 2},
	}

	if err := verifyCyclomaticComplexity(expectedCyclomaticComplexity, correctCyclomaticComplexity); err != nil {
		t.Error(err)
	}
}
예제 #3
0
func TestSwitcherComplexity(t *testing.T) {
	filePath := "./testcode/_switcher.go"
	srcFile, err := ioutil.ReadFile(filePath)
	if err != nil {
		t.Fatal(err)
	}
	expectedCyclomaticComplexity, err := ccomplexity.GetCyclomaticComplexityFunctionLevel(filePath, srcFile)
	if err != nil {
		t.Fatal(err)
	}

	correctCyclomaticComplexity := []ccomplexity.FunctionComplexity{
		{Name: "main", Complexity: 1},
		{Name: "monthNumberToString", Complexity: 14},
	}

	if err := verifyCyclomaticComplexity(expectedCyclomaticComplexity, correctCyclomaticComplexity); err != nil {
		t.Error(err)
	}
}