org.sonar.squidbridge.api.SourceFile Java Examples

The following examples show how to use org.sonar.squidbridge.api.SourceFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute(SensorContext context) {
  FileSystem fileSystem = context.fileSystem();
  FilePredicates predicates = fileSystem.predicates();
  List<SquidAstVisitor<LexerlessGrammar>> visitors = new ArrayList<>(checks.all());
  visitors.add(new FileLinesVisitor(fileLinesContextFactory, fileSystem));
  LuaConfiguration configuration = new LuaConfiguration(fileSystem.encoding());

  scanner = LuaAstScanner.create(configuration, visitors);

  Iterable<java.io.File> files = fileSystem.files(
    predicates.and(
      predicates.hasType(InputFile.Type.MAIN),
      predicates.hasLanguage(Lua.KEY),
      inputFile -> !inputFile.absolutePath().endsWith("mxml")
    ));
  scanner.scanFiles(ImmutableList.copyOf(files));

  Collection<SourceCode> squidSourceFiles = scanner.getIndex().search(new QueryByType(SourceFile.class));
  save(context, squidSourceFiles);
}
 
Example #2
Source File: NodeAstScanner.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Helper method for testing checks without having to deploy them on a Sonar instance.
 */
public static SourceFile scanSingleFile(File file, Collection<FlowCheck> nodeChecks,
    List<SquidAstVisitor<Grammar>> metrics) {
  if (!file.isFile()) {
    throw new IllegalArgumentException("File '" + file + "' not found.");
  }

  AstScanner<Grammar> scanner = create(new FlowConfiguration(Charsets.UTF_8), nodeChecks,
      metrics);
  scanner.scanFile(file);
  Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
  if (sources.size() != 1) {
    throw new IllegalStateException(
        "Only one SourceFile was expected whereas " + sources.size() + " has been returned.");
  }
  return (SourceFile) sources.iterator().next();
}
 
Example #3
Source File: LineLengthCheckTest.java    From sonar-lua with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void test() {
	LineLengthCheck check = new LineLengthCheck();
	check.maximumLineLength = 80;

	SourceFile file = LuaAstScanner.scanSingleFile(new File(
			"src/test/resources/checks/lineLength.lua"), check);
	CheckMessagesVerifier
			.verify(file.getCheckMessages())
			
			
			.next().atLine(5).withMessage("Split this 94 characters long line (which is greater than 80 authorized).")
			.next().atLine(29).withMessage("Split this 99 characters long line (which is greater than 80 authorized).")
			 .next().atLine(30).withMessage("Split this 99 characters long line (which is greater than 80 authorized).")
			.noMore();
}
 
Example #4
Source File: ApexSquidSensor.java    From enforce-sonarqube-plugin with MIT License 6 votes vote down vote up
/**
 * Saves issues form input file and source file.
 *
 * @param sonarFile input file.
 * @param squidFile source file.
 */
private void saveIssues(InputFile sonarFile, SourceFile squidFile) {
    Collection<CheckMessage> messages = squidFile.getCheckMessages();
    messages.forEach(message -> {
        RuleKey ruleKey = checks.ruleKey((SquidAstVisitor<Grammar>) message.getCheck());
        Issuable issuable = resourcePerspectives.as(Issuable.class, sonarFile);

        if (issuable != null) {
            Issue issue = issuable.newIssueBuilder()
                    .ruleKey(ruleKey)
                    .line(message.getLine())
                    .message(message.getText(Locale.ENGLISH))
                    .build();
            issuable.addIssue(issue);
        }
    });
}
 
Example #5
Source File: EmptyFlowCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void emptyFlowCheck() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new EmptyFlowCheck());

  String invalidPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkEmptyFlowInvalid/flow.xml";
  String expectedMessage 
      = "Service doesn't contain any flow steps. Remove service or add flow steps.";

  SourceFile sfViolation = FlowAstScanner.scanSingleFile(new File(invalidPath), checks, metrics);
  List<CheckMessage> violationMessages = new ArrayList<CheckMessage>(
      sfViolation.getCheckMessages());
  assertEquals(1, violationMessages.size());
  assertTrue("Returned check message not as expected",
      expectedMessage.equals(violationMessages.get(0).getDefaultMessage()));
}
 
Example #6
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void saveViolations(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<CheckMessage> messages = squidFile.getCheckMessages();
  logger.debug("+++Nr of violations found: " + messages.size());
  if (messages != null) {
    for (CheckMessage message : messages) {
      Object c = message.getCheck();
      if (c instanceof FlowCheck) {
        FlowCheck fc = (FlowCheck) c;
        if (squidFile.getInt(FlowMetric.IS_TOP_LEVEL) != 1 && fc.isTopLevelCheck()) {
          logger.debug("+++Ignoring toplevelCheck for file: " + squidFile.getKey());
        } else {
          RuleKey ruleKey;
          if (fc.isNodeCheck()) {
            ruleKey = nodeChecks.ruleKey(fc);
          } else {
            ruleKey = flowChecks.ruleKey(fc);
          }
          FlowIssue.create(context, ruleKey, message.getCost())
              .setPrimaryLocation(inputFile, message).save();
        }
      }
    }
  }
}
 
Example #7
Source File: BranchPropertiesCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void branchPropertiesCheckInvalidA() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new BranchPropertiesCheck());

  final String expectedMessageA 
      = "Both switch and evaluate labels are defined in properties of BRANCH";

  // Check violation flow A: both switch and evaluate labels defined
  SourceFile sfViolationA = FlowAstScanner
      .scanSingleFile(new File("src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
          + "/pub/checkBranchPropertiesInvalidA/flow.xml"), checks, metrics);
  List<CheckMessage> violationAMessages = new ArrayList<CheckMessage>(
      sfViolationA.getCheckMessages());
  assertEquals(1, violationAMessages.size());
  assertTrue("Returned check message not as expected",
      expectedMessageA.equals(violationAMessages.get(0).getDefaultMessage()));
}
 
Example #8
Source File: BranchPropertiesCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void branchPropertiesCheckInvalidB() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new BranchPropertiesCheck());

  final String expectedMessageB 
      = "Evaluate labels must be true when no switch parameter is defined in BRANCH";

  // Check violation flow B: neither switch nor evaluate labels defined
  SourceFile sfViolationB = FlowAstScanner
      .scanSingleFile(new File("src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
          + "/pub/checkBranchPropertiesInvalidB/flow.xml"), checks, metrics);
  List<CheckMessage> violationBMessages = new ArrayList<CheckMessage>(
      sfViolationB.getCheckMessages());
  assertEquals(1, violationBMessages.size());
  assertTrue("Returned check message not as expected",
      expectedMessageB.equals(violationBMessages.get(0).getDefaultMessage()));
}
 
Example #9
Source File: TryCatchCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void tryCatchCheckInvalid() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new TryCatchCheck());

  // check invalid flow
  String invalidFlowPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkTryCatchInvalid/flow.xml";
  String expectedMessage = "Create try-catch sequence";

  SourceFile sfViolation = FlowAstScanner.scanSingleFile(new File(invalidFlowPath), checks,
      metrics);
  List<CheckMessage> violationMessages = new ArrayList<CheckMessage>(
      sfViolation.getCheckMessages());
  assertEquals(1, violationMessages.size());
  assertTrue("Returned check message not as expected",
      expectedMessage.equals(violationMessages.get(0).getDefaultMessage()));

}
 
Example #10
Source File: QualifiedNameCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void qualifiedNameCheckValid() {
  Configuration cfg = mock(Configuration.class);
  Mockito.when(cfg.get(QualifiedNameCheck.QUALIFIED_NAME_KEY)).thenReturn(Optional.of(QualifiedNameCheck.QUALIFIED_NAME_DEFVALUE));
  FlowLanguage.setConfig(cfg);
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  QualifiedNameCheck qnc = new QualifiedNameCheck();
  checks.add(qnc);
  String validPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkQualityNameInvalid/flow.xml";

  SourceFile sfCorrect = FlowAstScanner.scanSingleFile(new File(validPath), checks, metrics);
  Set<CheckMessage> scmCorrect = sfCorrect.getCheckMessages();
  assertEquals(0, scmCorrect.size());  
}
 
Example #11
Source File: QualifiedNameCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void qualifiedNameCheckInvalid() {
  Configuration cfg = mock(Configuration.class);
  Mockito.when(cfg.get(QualifiedNameCheck.QUALIFIED_NAME_KEY)).thenReturn(Optional.of("test.*"));
  FlowLanguage.setConfig(cfg);
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  QualifiedNameCheck qnc = new QualifiedNameCheck();
  checks.add(qnc);
  String validPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkQualityNameInvalid/flow.xml";

  SourceFile sfCorrect = FlowAstScanner.scanSingleFile(new File(validPath), checks, metrics);
  Set<CheckMessage> scmCorrect = sfCorrect.getCheckMessages();
  assertEquals(1, scmCorrect.size());  
}
 
Example #12
Source File: SavePipelineCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void savePipelineCheck() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new SavePipelineCheck());

  String invalidPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkSavePipelineInvalid/flow.xml";
  String expectedMessage = "Remove service pub.flow:savePipeline";

  SourceFile sfViolation = FlowAstScanner.scanSingleFile(new File(invalidPath), checks, metrics);
  List<CheckMessage> violationMessages = new ArrayList<CheckMessage>(
      sfViolation.getCheckMessages());
  assertEquals(1, violationMessages.size());
  assertTrue("Returned check message not as expected",
      expectedMessage.equals(violationMessages.get(0).getDefaultMessage()));

}
 
Example #13
Source File: EmptyMapCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void emptyMapCheckInvalid() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new EmptyMapCheck());

  // Invalid
  String invalidPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkEmptyMapInvalid/flow.xml";
  String expectedMessage 
      = "This map step in the flow is empty, create content or remove the map.";

  SourceFile sfViolation = FlowAstScanner.scanSingleFile(new File(invalidPath), checks, metrics);
  List<CheckMessage> violationMessages = new ArrayList<CheckMessage>(
      sfViolation.getCheckMessages());
  assertEquals(1, violationMessages.size());
  assertTrue("Returned check message not as expected",
      expectedMessage.equals(violationMessages.get(0).getDefaultMessage()));
}
 
Example #14
Source File: EmptyMapCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void emptyMapCheckValid() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new EmptyMapCheck());

  // Valid
  String invalidPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkEmptyMapValid/flow.xml";

  SourceFile sfViolation = FlowAstScanner.scanSingleFile(new File(invalidPath), checks, metrics);
  List<CheckMessage> violationMessages = new ArrayList<CheckMessage>(
      sfViolation.getCheckMessages());
  assertEquals(0, violationMessages.size());
}
 
Example #15
Source File: ExitCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void exitCheck() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new ExitCheck());

  String invalidPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkExitStepInvalid/flow.xml";

  SourceFile sfViolation = FlowAstScanner.scanSingleFile(new File(invalidPath), checks, metrics);
  List<CheckMessage> violationMessages = new ArrayList<CheckMessage>(
      sfViolation.getCheckMessages());
  assertEquals(2, violationMessages.size());
  // TODO check both violation messages
}
 
Example #16
Source File: DisabledCheckTest.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void disabledCheck() {
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  checks.add(new DisabledCheck());

  String invalidPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkDisabledInvalid/flow.xml";
  String expectedMessage = "Remove disabled code";

  SourceFile sfViolation = FlowAstScanner.scanSingleFile(new File(invalidPath), checks, metrics);
  List<CheckMessage> violationMessages = new ArrayList<CheckMessage>(
      sfViolation.getCheckMessages());
  assertEquals(1, violationMessages.size());
  assertTrue("Returned check message not as expected",
      expectedMessage.equals(violationMessages.get(0).getDefaultMessage()));
}
 
Example #17
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void saveViolations(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<CheckMessage> messages = squidFile.getCheckMessages();
  if (messages != null) {

    for (CheckMessage message : messages) {
      RuleKey ruleKey = checks.ruleKey((SquidCheck<LexerlessGrammar>) message.getCheck());
      NewIssue newIssue = context.newIssue()
        .forRule(ruleKey)
        .gap(message.getCost());
      Integer line = message.getLine();
      NewIssueLocation location = newIssue.newLocation()
        .on(inputFile)
        .message(message.getText(Locale.ENGLISH));
      if (line != null) {
        location.at(inputFile.selectLine(line));
      }
      newIssue.at(location);
      newIssue.save();
    }
  }
}
 
Example #18
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void saveFunctionsComplexityDistribution(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<SourceCode> squidFunctionsInFile = scanner.getIndex().search(new QueryByParent(squidFile), new QueryByType(SourceFunction.class));
  RangeDistributionBuilder complexityDistribution = new RangeDistributionBuilder(FUNCTIONS_DISTRIB_BOTTOM_LIMITS);
  for (SourceCode squidFunction : squidFunctionsInFile) {
    complexityDistribution.add(squidFunction.getDouble(LuaMetric.COMPLEXITY));
  }
  context.<String>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION)
    .withValue(complexityDistribution.build())
    .save();
}
 
Example #19
Source File: MethodComplexityCheckTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void test() {
  MethodComplexityCheck check = new MethodComplexityCheck();
  check.setMaximumFunctionComplexityThreshold(0);

  SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/methodComplexity.lua"), check);

  CheckMessagesVerifier.verify(file.getCheckMessages())
     .next().atLine(1).withMessage("Method has a complexity of 6 which is greater than 0 authorized.")
      .next().atLine(3).withMessage("Method has a complexity of 2 which is greater than 0 authorized.") 
        .next().atLine(4).withMessage("Method has a complexity of 1 which is greater than 0 authorized.")
     .next().atLine(11).withMessage("Method has a complexity of 1 which is greater than 0 authorized.")

      .noMore();
}
 
Example #20
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void saveMeasures(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  context.<Integer>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.NCLOC)
    .withValue(squidFile.getInt(LuaMetric.LINES_OF_CODE))
    .save();
  context.<Integer>newMeasure()
  .on(inputFile)
  .forMetric(CoreMetrics.CLASSES)
  .withValue(squidFile.getInt(LuaMetric.TABLECONSTRUCTORS))
  .save();
  context.<Integer>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.COMMENT_LINES)
    .withValue(squidFile.getInt(LuaMetric.COMMENT_LINES))
    .save();
  
  context.<Integer>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.FUNCTIONS)
    .withValue(squidFile.getInt(LuaMetric.FUNCTIONS))
    .save();
  context.<Integer>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.STATEMENTS)
    .withValue(squidFile.getInt(LuaMetric.STATEMENTS))
    .save();
  context.<Integer>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.COMPLEXITY)
    .withValue(squidFile.getInt(LuaMetric.COMPLEXITY))
    .save();
}
 
Example #21
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void save(SensorContext context, Collection<SourceCode> squidSourceFiles) {
  FileSystem fileSystem = context.fileSystem();
  for (SourceCode squidSourceFile : squidSourceFiles) {
    SourceFile squidFile = (SourceFile) squidSourceFile;

    InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(squidFile.getKey()));

    saveClassComplexity(context, inputFile, squidFile);
    saveMeasures(context, inputFile, squidFile);
    saveFunctionsComplexityDistribution(context, inputFile, squidFile);
    saveFilesComplexityDistribution(context, inputFile, squidFile);
    visitors.add(new LuaTokensVisitor(context, LuaLexer.create(configuration)));
    saveViolations(context, inputFile, squidFile);
  }
}
 
Example #22
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void saveFilesComplexityDistribution(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  String distribution = new RangeDistributionBuilder(FILES_DISTRIB_BOTTOM_LIMITS)
    .add(squidFile.getDouble(LuaMetric.COMPLEXITY))
    .build();
  context.<String>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION)
    .withValue(distribution)
    .save();
}
 
Example #23
Source File: CommentRegularExpressionCheckTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void test() {
  CommentRegularExpressionCheck check = new CommentRegularExpressionCheck();

  check.regularExpression = "(?i).*TODO.*";
  check.message = "Avoid TODO";

  SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/commentRegularExpression.lua"), check);
  CheckMessagesVerifier.verify(file.getCheckMessages())
      .next().atLine(2).withMessage("Avoid TODO")
      .noMore();
}
 
Example #24
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void saveClassComplexity(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<SourceCode> classes = scanner.getIndex().search(new QueryByParent(squidFile), new QueryByType(SourceClass.class));
  int complexityInClasses = 0;
  for (SourceCode squidClass : classes) {
    int classComplexity = squidClass.getInt(LuaMetric.COMPLEXITY);
    complexityInClasses += classComplexity;
  }
  context.<Integer>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.COMPLEXITY_IN_CLASSES)
    .withValue(complexityInClasses)
    .save();
}
 
Example #25
Source File: FileComplexityCheck.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void leaveFile(AstNode astNode) {
  SourceFile sourceFile = (SourceFile) getContext().peekSourceCode();
  int complexity = ChecksHelper.getRecursiveMeasureInt(sourceFile, LuaMetric.COMPLEXITY);
  if (complexity > maximumFileComplexityThreshold) {
    getContext().createFileViolation(this,
        "File has a complexity of {0,number,integer} which is greater than {1,number,integer} authorized.",
        complexity,
        maximumFileComplexityThreshold);
  }
}
 
Example #26
Source File: FileComplexityCheckTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void test() {
  check.setMaximumFileComplexityThreshold(0);

  SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/fileComplexity.lua"), check);
  CheckMessagesVerifier.verify(file.getCheckMessages())
      .next().withMessage("File has a complexity of 1 which is greater than 0"+ " authorized.")
      .noMore();
}
 
Example #27
Source File: LocalFunctionComplexityCheckTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void test() {
 LocalFunctionComplexityCheck check = new LocalFunctionComplexityCheck();
  check.setMaximumFunctionComplexityThreshold(0);

  SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/localFunctionComplexity.lua"), check);

  CheckMessagesVerifier.verify(file.getCheckMessages())

     .next().atLine(1).withMessage("LocalFunction has a complexity of 6 which is greater than 0 authorized.") 
        .next().atLine(2).withMessage("LocalFunction has a complexity of 3 which is greater than 0 authorized.")
     
      .noMore();
}
 
Example #28
Source File: TableComplexityCheckTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void test() {
  TableComplexityCheck check = new TableComplexityCheck();
  check.setMaximumTableComplexityThreshold(0);

  SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/tableComplexity.lua"), check);

  CheckMessagesVerifier.verify(file.getCheckMessages())
     .next().atLine(1).withMessage("Table has a complexity of 1 which is greater than 0 authorized.")
     
      .noMore();
}
 
Example #29
Source File: NestedControlFlowDepthCheckTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testDefault() {
  SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/nestedControlFlowStmt.lua"), check);
  CheckMessagesVerifier.verify(file.getCheckMessages())
    .next().atLine(7).withMessage("Refactor this code to not nest more than 3 if/for/while/ statements.")
    .next().atLine(16).withMessage("Refactor this code to not nest more than 3 if/for/while/ statements.")
    .noMore();
}
 
Example #30
Source File: NestedTablesDepthCheckTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testDefault() {
  SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/nestedTable.lua"), check);
  CheckMessagesVerifier.verify(file.getCheckMessages())
    .next().atLine(4).withMessage("Refactor this code to not nest more than 3 tables.")
    
    .noMore();
}