diff --git a/.ci/travis.sh b/.ci/travis.sh new file mode 100755 index 0000000000..eda7a5040d --- /dev/null +++ b/.ci/travis.sh @@ -0,0 +1,100 @@ +#!/bin/bash +# Attention, there is no "-x" to avoid problems on Travis +set -e + +case $1 in + +pr-description) + .ci/xtr_pr-description.sh + ;; + +eclipse-cs) + cd sevntu-checks + mvn -e clean install -Dmaven.test.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true + cd .. + git clone https://github.com/checkstyle/eclipse-cs.git + cd eclipse-cs/ + git checkout 8.10.0 + mvn -e install + cd ../ + cd eclipsecs-sevntu-plugin + mvn -e verify + mvn -e javadoc:javadoc + ;; + +maven-plugin) + cd sevntu-checks + mvn -e clean install -Dmaven.test.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true + cd .. + cd sevntu-checkstyle-maven-plugin + mvn -e verify + mvn -e javadoc:javadoc + ;; + +idea-extension) + cd sevntu-checks + mvn -e clean install -Dmaven.test.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true + cd .. + cd sevntu-checkstyle-idea-extension + mvn -e verify + mvn -e javadoc:javadoc + ;; + +sonar-plugin) + cd sevntu-checks + mvn -e clean install -Dmaven.test.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true + cd .. + cd sevntu-checkstyle-sonar-plugin + mvn -e verify + mvn -e javadoc:javadoc + ;; + +sevntu-checks) + cd sevntu-checks + mvn -e -Pcoverall install + mvn -e verify -Pno-validations,selftesting + mvn -e javadoc:javadoc + if [[ $TRAVIS == 'true' ]]; then + mvn -e -Pcoverall jacoco:report coveralls:report + fi + ;; + +all-sevntu-checks-contribution) + wget -q \ + https://raw.githubusercontent.com/checkstyle/contribution/master/checkstyle-tester/checks-sevntu-error.xml + xmlstarlet sel --net --template -m .//module -v "@name" -n checks-sevntu-error.xml \ + | grep -vE "Checker|TreeWalker|Filter|Holder" | grep -v "^$" \ + | sed "s/com\.github\.sevntu\.checkstyle\.checks\..*\.//" \ + | sort | uniq | sed "s/Check$//" > web.txt + xmlstarlet sel --net --template -m .//module -v "@name" -n sevntu-checks/sevntu-checks.xml \ + | grep -vE "Checker|TreeWalker|Filter|Holder" | grep -v "^$" \ + | sed "s/com\.github\.sevntu\.checkstyle\.checks\..*\.//" \ + | sort | uniq | sed "s/Check$//" > file.txt + diff -u web.txt file.txt + ;; + +checkstyle-regression) + git clone https://github.com/checkstyle/checkstyle + cd sevntu-checks + mvn -e install -DskipTests -Dcheckstyle.skip=true -Dcobertura.skip=true + mvn -e test -Dtest=CheckstyleRegressionTest#setupFiles -Dregression-path=../ + cd ../ + cd checkstyle + mvn -e clean verify -e -DskipTests -DskipITs -Dpmd.skip=true \ + -Dfindbugs.skip=true -Dcobertura.skip=true \ + -Dmaven.sevntu-checkstyle-check.checkstyle.version=8.10 + ;; + +eclipse-analysis) + cd sevntu-checks + mvn -e clean compile exec:exec -Peclipse-compiler + ;; + + +*) + echo "Unexpected argument: $1" + sleep 5s + false + ;; + +esac diff --git a/.ci/xtr_pr-description.sh b/.ci/xtr_pr-description.sh new file mode 100755 index 0000000000..bfaebb6e11 --- /dev/null +++ b/.ci/xtr_pr-description.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# Attention, there is no "-x" to avoid problems on Travis +set -e + +if [[ ! $TRAVIS_PULL_REQUEST =~ ^([0-9]*)$ ]]; then exit 0; fi +LINK_COMMITS=https://api.github.com/repos/sevntu-checkstyle/sevntu.checkstyle/pulls/$TRAVIS_PULL_REQUEST/commits +COMMITS=$(curl -s -H "Authorization: token $READ_ONLY_TOKEN" $LINK_COMMITS | jq '.[0] | .commit.message') +echo 'Commit messages from github: '${COMMITS:0:60}... +ISSUE_NUMBER=$(echo $COMMITS | sed -e 's/^.*Issue //' | sed -e 's/:.*//') +echo 'Issue number: '$ISSUE_NUMBER && RESULT=0 +if [[ $ISSUE_NUMBER =~ ^#[0-9]+$ ]]; then + LINK_PR=https://api.github.com/repos/sevntu-checkstyle/sevntu.checkstyle/pulls/$TRAVIS_PULL_REQUEST + LINK_ISSUE=https://api.github.com/repos/sevntu-checkstyle/sevntu.checkstyle/issues/${ISSUE_NUMBER:1} + REGEXP=($ISSUE_NUMBER\|https://github.com/sevntu-checkstyle/sevntu.checkstyle/issues/${ISSUE_NUMBER:1}) + PR_DESC=$(curl -s -H "Authorization: token $READ_ONLY_TOKEN" $LINK_PR | jq '.body' | grep -E $REGEXP | cat ) + echo 'PR Description grepped:'${PR_DESC:0:80} + if [[ -z $PR_DESC ]]; then + echo 'Please put a reference to an Issue in the PR description, this will bind the Issue to your PR in Github' && RESULT=1; + fi + LABEL_APRV=$(curl -s -H "Authorization: token $READ_ONLY_TOKEN" $LINK_ISSUE | jq '.labels [] | .name' | grep approved | cat | wc -l ) + if [[ $LABEL_APRV == 0 ]]; then + echo 'You are providing a PR for an Issue that is not approved yet, please ask admins to approve your Issue first' && RESULT=1; + fi + fi +if [[ $RESULT == 0 ]]; then + echo 'PR validation succeeded.'; +else + echo 'PR validation failed.' && false; +fi diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000000..508ae63860 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,11 @@ +Please read http://checkstyle.sourceforge.net/report_issue.html + +**Note:** Sevntu checks are in a different JAR from the main Checkstyle JAR and cannot be run without the main JAR. +The command to run sevntu in the Command Line Interface (CLI) is slightly different as noted below: +``` +java -classpath sevntu-checks-X.XX.X.jar;checkstyle-X.XX-all.jar com.puppycrawl.tools.checkstyle.Main -c config.xml YOUR_FILE.java +``` + +Please provide issue report in format that we request, EACH DETAIL MAKE A HUGE HELP. + +Issues that are not following the guidelines, will be processed with last priority. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000..04fbe2217f --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,29 @@ +/var/tmp $ javac YOUR_FILE.java + +[[PLACE YOUR OUTPUT HERE]] + +/var/tmp $ cat YOUR_FILE.java + +[[PLACE YOU OUTPUT HERE]] + +/var/tmp $ cat config.xml + +[[PLACE YOUR OUTPUT HERE]] + +For Linux users: + +`/var/tmp $ java -classpath sevntu-checks-X.XX.X.jar:checkstyle-X.XX-all.jar com.puppycrawl.tools.checkstyle.Main -c config.xml YOUR_FILE.java` + +For Windows users: + +`C:\tmp> java -classpath sevntu-checks-X.XX.X.jar;checkstyle-X.XX-all.jar com.puppycrawl.tools.checkstyle.Main -c config.xml YOUR_FILE.java` + +[[PLACE YOUR OUTPUT HERE]] + +--------------- + +Describe what you expect in detail. + +-------------- + +Still not clear ??? - see example - https://github.com/sevntu-checkstyle/sevntu.checkstyle/wiki/How-to-report-the-issue-(example) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000..ab236e32fa --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,16 @@ +Mandatory to understand and do: +0) Issue you are trying to fix/resolve has to have "approved" label. +1) Put in description of Pull Request reference to issue if it exists. Example: "Issue: #XXXXXX" +2) Commit message should adhere to the following rules: + a) Must match one of the following patterns:\n" + ^Issue #\\d+: .*$ + ^Pull #\\d+: .*$ + ^(minor|config|infra|doc|spelling): .*$ + b) It contains only one line of text + c) Must not end with a period, space, or tab + +To avoid multiple iterations of fixes and CIs failures, please read http://checkstyle.sourceforge.net/contributing.html + +ATTENTION: We are not merging Pull Requests that not passing our CIs, but we help to resolve issues. + +Thanks for reading, remove whole this message and type what you need. diff --git a/.gitignore b/.gitignore index f9ce6766f6..1c9d6f1567 100644 --- a/.gitignore +++ b/.gitignore @@ -5,9 +5,11 @@ bin/ # No Github Pages gh-pages/ -# No Eclipse settings +# No Eclipse files .settings/ .checkstyle +.classpath +.project # No IntelliJ Idea project files .idea/ diff --git a/.travis.yml b/.travis.yml index fb8534f514..ad00bba2ad 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,31 +1,102 @@ language: java sudo: false -jdk: - - oraclejdk8 - -before_install: git clone git://git.code.sf.net/p/eclipse-cs/git eclipse-cs-git - && cd eclipse-cs-git/ && git checkout 7.2.0 - && cd net.sf.eclipsecs.parent/ && mvn install - && cd ../../ - -install: cd sevntu-checks && mvn clean install && mvn javadoc:javadoc - && cd ../eclipsecs-sevntu-plugin && mvn verify && mvn javadoc:javadoc - && cd ../sevntu-checkstyle-maven-plugin && mvn verify && mvn javadoc:javadoc - && cd ../sevntu-checkstyle-idea-extension && mvn verify && mvn javadoc:javadoc - && cd ../sevntu-checkstyle-sonar-plugin && mvn verify && mvn javadoc:javadoc - && cd ../sevntu-checks && mvn jacoco:report coveralls:jacoco - && cd ../sevntu-checks && mvn verify -Pselftesting - -after_success: - cache: directories: - ~/.m2 +addons: + apt: + packages: + - xmlstarlet + branches: only: - master +install: + - + matrix: fast_finish: true + include: + # eclipse-cs + - jdk: oraclejdk8 + env: + - DESC="eclipse-cs" + - CMD="./.ci/travis.sh eclipse-cs" + + # maven-plugin + - jdk: oraclejdk8 + env: + - DESC="maven-plugin" + - CMD="./.ci/travis.sh maven-plugin" + + # idea-extension + - jdk: oraclejdk8 + env: + - DESC="idea-extension" + - CMD="./.ci/travis.sh idea-extension" + + # sonar-plugin + - jdk: oraclejdk8 + env: + - DESC="sonar-plugin" + - CMD="./.ci/travis.sh sonar-plugin" + + # checks + - jdk: oraclejdk8 + env: + - DESC="checks" + - CMD="./.ci/travis.sh sevntu-checks" + + # Ensure that all sevntu checks are used in contribution + - jdk: oraclejdk8 + env: + - DESC="All sevntu checks should be used in contribution" + - CMD="./.ci/travis.sh all-sevntu-checks-contribution" + + # regression on checkstyle + - jdk: oraclejdk8 + env: + - DESC="checkstyle-regression" + - CMD="./.ci/travis.sh checkstyle-regression" + + # eclipse static analysis + - jdk: oraclejdk8 + env: + - DESC="eclipse-analysis" + - CMD="./.ci/travis.sh eclipse-analysis" + + # testing of PR format + - env: + - DESC="test Issue ref in PR description" + - CMD="./.ci/travis.sh pr-description" + + +script: + - SKIP_FILES1=".github|codeship-*|buddy.yml|appveyor.yml|circleci|distelli-manifest.yml" + - SKIP_FILES2="|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr" + - SKIP_FILES3="|shippable.yml|shippable.sh|wercker.yml|wercker.sh|intellij-idea-inspections.xml" + - SKIP_FILES=$SKIP_FILES1$SKIP_FILES2$SKIP_FILES3 + - | + if [[ $SKIP_CI != 'false' ]]; then + if [[ $(git diff --name-only HEAD HEAD~1 | grep -vE "$SKIP_FILES" \ + | cat | wc -c | sed 's/^ *//' ) > 0 ]]; then + SKIP_CI="false" + else + SKIP_CI="true" + fi + fi + - echo "SKIP_CI="$SKIP_CI + - | + set -e + if [[ $SKIP_CI == 'false' ]]; + then + eval $CMD; + echo "eval of CMD is completed" + else + echo "CI is skipped" + fi + +after_success: diff --git a/README.textile b/README.textile index 16b23b159a..0582db5eb8 100644 --- a/README.textile +++ b/README.textile @@ -1,11 +1,20 @@ -h3. Information "!https://secure.travis-ci.org/sevntu-checkstyle/sevntu.checkstyle.png!":http://travis-ci.org/sevntu-checkstyle/sevntu.checkstyle/builds !https://coveralls.io/repos/sevntu-checkstyle/sevntu.checkstyle/badge.svg?branch=master&service=github(Coverage Status)!:https://coveralls.io/github/sevntu-checkstyle/sevntu.checkstyle?branch=master !https://img.shields.io/sonar/http/sonarqube.com/com.github.sevntu.checkstyle:sevntu-checks/tech_debt.svg?label=SonarQube%20tech%20debt!:https://sonarqube.com/overview?id=com.github.sevntu.checkstyle%3Asevntu-checks +h3. Information "!https://secure.travis-ci.org/sevntu-checkstyle/sevntu.checkstyle.png!":http://travis-ci.org/sevntu-checkstyle/sevntu.checkstyle/builds !https://coveralls.io/repos/sevntu-checkstyle/sevntu.checkstyle/badge.svg?branch=master&service=github(Coverage Status)!:https://coveralls.io/github/sevntu-checkstyle/sevntu.checkstyle?branch=master !https://sonarcloud.io/api/project_badges/measure?project=com.github.sevntu.checkstyle%3Asevntu-checks&metric=sqale_index!:https://sonarqube.com/dashboard?id=com.github.sevntu.checkstyle%3Asevntu-checks + +sevntu-checks: !https://maven-badges.herokuapp.com/maven-central/com.github.sevntu-checkstyle/sevntu-checks/badge.svg!:https://search.maven.org/#search|gav|1|g%3A%22com.github.sevntu-checkstyle%22%20AND%20a%3A%22sevntu-checks%22 +sevntu-checkstyle-idea-extension:!https://maven-badges.herokuapp.com/maven-central/com.github.sevntu-checkstyle/sevntu-checkstyle-idea-extension/badge.svg!:https://search.maven.org/#search|gav|1|g%3A%22com.github.sevntu-checkstyle%22%20AND%20a%3A%22sevntu-checkstyle-idea-extension%22 +sevntu-checkstyle-maven-plugin:!https://maven-badges.herokuapp.com/maven-central/com.github.sevntu-checkstyle/sevntu-checkstyle-maven-plugin/badge.svg!:https://search.maven.org/#search|gav|1|g%3A%22com.github.sevntu-checkstyle%22%20AND%20a%3A%22sevntu-checkstyle-maven-plugin%22 +sevntu-checkstyle-sonar-plugin:!https://maven-badges.herokuapp.com/maven-central/com.github.sevntu-checkstyle/sevntu-checkstyle-sonar-plugin/badge.svg!:https://search.maven.org/#search|gav|1|g%3A%22com.github.sevntu-checkstyle%22%20AND%20a%3A%22sevntu-checkstyle-sonar-plugin%22 +eclipsecs-sevntu-plugin: "all versions":https://github.com/sevntu-checkstyle/sevntu.checkstyle/tree/gh-pages/update-site/plugins + +All sevntu artifact on maven repo: https://repo1.maven.org/maven2/com/github/sevntu-checkstyle/ + Additional(non-standard) checks for Checkstyle that are compiled as: - extension to "maven-checkstyle-plugin":http://maven.apache.org/plugins/maven-checkstyle-plugin/ (how to use: "in general":http://maven.apache.org/plugins/maven-checkstyle-plugin/examples/custom-developed-checkstyle.html, "maven, ant, gradle example":https://github.com/sevntu-checkstyle/checkstyle-samples). - extension to "Sonar Checkstyle Plugin":http://docs.codehaus.org/display/SONAR/Checkstyle+Plugin (how to use: "instructions with pictures":https://github.com/sevntu-checkstyle/sevntu.checkstyle/wiki/How-to-integrate-sevntu-checks-into-SonarQubeTM-%28user%27s-guide%29). - extension to "CheckStyle-IDEA":http://plugins.jetbrains.com/plugin/1065 (how to use: "instructions with pictures":https://github.com/sevntu-checkstyle/sevntu.checkstyle/wiki/How-to-use-SevNTU-Checkstyle-in-Intellij-IDEA). - extension to "Checkstyle Beans, NetBeans":http://plugins.netbeans.org/plugin/3413/checkstyle-beans (how to use: "instructions with pictures":https://github.com/sevntu-checkstyle/sevntu.checkstyle/wiki/How-to-use-SevNTU-Checkstyle-in-NetBeans). -- extension to "Checkstyle Eclipse plugin":http://eclipse-cs.sourceforge.net/ how to use: install from EclipseCS "update site": +- extension to "Checkstyle Eclipse plugin":http://eclipse-cs.sourceforge.net/ how to use: install from EclipseCS "update site": !https://cloud.githubusercontent.com/assets/812984/2935361/20e479c8-d805-11e3-9391-f41cc4aa979c.png! h3. Related Projects @@ -14,7 +23,7 @@ h3. Related Projects h3. Contributors -"Roman Ivanov":https://github.com/romani, "Ivan Sopov":https://github.com/isopov, "Ruslan Diachenko":https://github.com/rdiachenko, Danil Lopatin, "Daniil Yaroslavtsev":https://github.com/daniilyar, "Yuriy Balahonov":https://github.com/balakhonov, Dmitriy Antonenko, +"Roman Ivanov":https://github.com/romani, "Ivan Sopov":https://github.com/isopov, "Ruslan Diachenko":https://github.com/rdiachenko, Danil Lopatin, "Daniil Yaroslavtsev":https://github.com/daniilyar, "Yuriy Balakhonov":https://github.com/balakhonov, Dmitriy Antonenko, Hidoyatov Victor, Troshin Sergey, Svinukhov Vladimir, "Ilia Dubinin":https://github.com/sabaka, Dmitry Gridyushko, "Vadym Chekrii":https://github.com/vchekrii, "Vadim Panasiuk":https://github.com/VadimPanasiuk, "Aleksey Grigirov":https://github.com/KTannenberg, Alexander Berezovsky, "Sergey Burtsev":https://github.com/burtsevsergey, "Baratali Izmailov":https://github.com/baratali, "Max Vetrenko":https://github.com/maxvetrenko, "Pavel Baranchikov":https://github.com/pbaranchikov , "Ashutosh Agarwal":https://github.com/Radsaggi, "Alexey Nesterenko":https://github.com/alexkravin. , ...... for whole list please look at "contributors list":https://github.com/sevntu-checkstyle/sevntu.checkstyle/network/members . diff --git a/deploy-all.sh b/deploy-all.sh index ae43129a1b..e43f538b1d 100755 --- a/deploy-all.sh +++ b/deploy-all.sh @@ -1,2 +1,4 @@ -#!/bin/sh -sh deploy.sh --all +#!/usr/bin/env bash + +CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +$CURRENT_DIR/deploy.sh --all diff --git a/deploy.sh b/deploy.sh index dab444d2a9..f39722354e 100755 --- a/deploy.sh +++ b/deploy.sh @@ -1,7 +1,10 @@ -#!/bin/sh +#!/usr/bin/env bash -EXEC_DIR=`dirname $0` -REPO_HOME_DIR=`cd "$EXEC_DIR" ; pwd` +SEVNTU_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +GH_SEVNTU_DIR="/tmp/sevntu.checkstyle.gh" +PROJECT_NAME="sevntu.checkstyle" +GH_SEVNTU_HOMR_DIR="$GH_SEVNTU_DIR/$PROJECT_NAME" +GITHUB_PROJECT="sevntu-checkstyle/$PROJECT_NAME" usage="$(basename "$0") [--help --all --eclipse-cs --sonar --maven --idea] where: @@ -12,6 +15,8 @@ where: --sonar deploy only 'sevntu-checkstyle-sonar-plugin' project; --maven deploy only 'sevntu-checkstyle-maven-plugin' project; --idea deploy only 'sevntu-checkstyle-idea-extension' project; + --maven-central deploy to maven central; + --gh-pages deploy only gh-pages binaries with version argument; " @@ -23,112 +28,164 @@ For new version deploy please do: prepareForDeploy() { - #clean - rm -rf $REPO_HOME_DIR/gh-pages + echo "Preparing for Deployment" + if [ ! -d $GH_SEVNTU_DIR ]; then + mkdir $GH_SEVNTU_DIR + fi + + cd $GH_SEVNTU_DIR - #prepare folders for update-site and our release maven repository - mkdir $REPO_HOME_DIR/gh-pages - cd $REPO_HOME_DIR/gh-pages + if [ ! -d "$GH_SEVNTU_DIR/$PROJECT_NAME/.git" ]; then + git clone https://github.com/$GITHUB_PROJECT.git - git init - git remote add origin https://github.com/sevntu-checkstyle/sevntu.checkstyle.git - git fetch origin gh-pages:refs/remotes/origin/gh-pages - git checkout gh-pages + cd $GH_SEVNTU_HOMR_DIR + else + cd $GH_SEVNTU_HOMR_DIR + + git fetch origin + fi - cd $REPO_HOME_DIR + git reset --hard HEAD + git clean -f -d + git checkout origin/gh-pages return } deployIdea() { - cd $REPO_HOME_DIR/sevntu-checkstyle-idea-extension/ - mvn clean deploy + echo "Deploying Idea" + cd $SEVNTU_DIR/sevntu-checkstyle-idea-extension/ + mvn clean deploy -Plocal-deploy -DdeployDir=$GH_SEVNTU_HOMR_DIR if [ "$?" != "0" ] then - echo "build for $REPO_HOME_DIR/sevntu-checkstyle-idea-extension/" + echo "build for $SEVNTU_DIR/sevntu-checkstyle-idea-extension/" exit 1 fi - cd $REPO_HOME_DIR/gh-pages + cd $GH_SEVNTU_HOMR_DIR echo "$manualDeploy" return } deployEclipse() { - cd $REPO_HOME_DIR - #echo -n "Enter version number: " - #read version - #mvn org.eclipse.tycho:tycho-versions-plugin:set-version -DnewVersion=$version -f eclipse-pom.xml - mvn clean install -f eclipse-pom.xml + echo "Deploying Eclipse" + cd $SEVNTU_DIR + #echo -n "Enter version number: " + #read version + #mvn org.eclipse.tycho:tycho-versions-plugin:set-version -DnewVersion=$version -f eclipse-pom.xml + mvn clean install -f eclipse-pom.xml -Plocal-deploy if [ "$?" != "0" ] then echo "build for eclipse-pom.xml." exit 1 fi - cd $REPO_HOME_DIR/update-site - mvn wagon:upload - cd ../gh-pages + cd $SEVNTU_DIR/update-site + mvn wagon:upload -DdeployDir=$GH_SEVNTU_HOMR_DIR + cd $GH_SEVNTU_HOMR_DIR echo "$manualDeploy" return } deployMavenLibrary() { - # As we do not use SNAPSHOT qualifier for developemnt in pom.xml - # we have to deploy library sevntu-checks always even it overides existing binaries in maven repository - # for relase build - it will not override binaries + echo "Deploying Sevntu Checks" + # As we do not use SNAPSHOT qualifier for development in pom.xml + # we have to deploy library sevntu-checks always even it overrides existing binaries in maven repository + # for release build - it will not override binaries # for test build - it will override as we need to be sure that in repository, # we have previous release version but compiled with from new code - cd $REPO_HOME_DIR/sevntu-checks - mvn clean javadoc:javadoc deploy + cd $SEVNTU_DIR/sevntu-checks + mvn clean javadoc:javadoc deploy -Plocal-deploy -DdeployDir=$GH_SEVNTU_HOMR_DIR if [ "$?" != "0" ] then - echo "build for $REPO_HOME_DIR/sevntu-checks." + echo "build for $SEVNTU_DIR/sevntu-checks." exit 1 fi # deployment of Javadoc to static site - cp -rf target/site/apidocs ../gh-pages - - cd $REPO_HOME_DIR + cp -rf target/site/apidocs $GH_SEVNTU_HOMR_DIR # no need push to repository only library it should be done together with IDE plugins release - #cd ../gh-pages + #cd $GH_SEVNTU_HOMR_DIR #echo "$manualDeploy" return } +deployToMavenCentral() + { + echo "Deploying All to Maven Central" + # As we do not use SNAPSHOT qualifier for development in pom.xml + # we have to deploy library sevntu-checks always even it overrides existing binaries in maven repository + # for release build - it will not override binaries + # for test build - it will override as we need to be sure that in repository, + # we have previous release version but compiled with from new code + cd $SEVNTU_DIR/sevntu-checks + mvn clean deploy -DskipStaging=false -Pgpg + if [ "$?" != "0" ] + then + echo "build for $SEVNTU_DIR/sevntu-checks." + exit 1 + fi + + cd $SEVNTU_DIR/sevntu-checkstyle-maven-plugin/ + mvn clean deploy -DskipStaging=false -Pgpg + + cd $SEVNTU_DIR/sevntu-checkstyle-idea-extension/ + mvn clean deploy -DskipStaging=false -Pgpg + + cd $SEVNTU_DIR/sevntu-checkstyle-sonar-plugin/ + mvn clean deploy -DskipStaging=false -Pgpg + + return + } + deployMavenPlugin() { - cd $REPO_HOME_DIR/sevntu-checkstyle-maven-plugin/ - mvn clean deploy + echo "Deploying Maven Plugin" + cd $SEVNTU_DIR/sevntu-checkstyle-maven-plugin/ + mvn clean deploy -Plocal-deploy -DdeployDir=$GH_SEVNTU_HOMR_DIR if [ "$?" != "0" ] then - echo "build for $REPO_HOME_DIR/sevntu-checkstyle-maven-plugin/." + echo "build for $SEVNTU_DIR/sevntu-checkstyle-maven-plugin/." exit 1 fi - cd $REPO_HOME_DIR/gh-pages + cd $GH_SEVNTU_HOMR_DIR echo "$manualDeploy" return } deploySonar() { - cd $REPO_HOME_DIR/sevntu-checkstyle-sonar-plugin/ - mvn clean install wagon:upload-single + echo "Deploying Sonar" + cd $SEVNTU_DIR/sevntu-checkstyle-sonar-plugin/ + mvn clean install wagon:upload-single -DdeployDir=$GH_SEVNTU_HOMR_DIR if [ "$?" != "0" ] then - echo "build for $REPO_HOME_DIR/sevntu-checkstyle-sonar-plugin/" + echo "build for $SEVNTU_DIR/sevntu-checkstyle-sonar-plugin/" exit 1 fi - cd $REPO_HOME_DIR/gh-pages + cd $GH_SEVNTU_HOMR_DIR echo "$manualDeploy" return } +deployToGhPages() + { + echo "Deploying GH Pages" + cd $GH_SEVNTU_HOMR_DIR + + sed -i "/

New and noteworthy<\/h2>/ r $2" index.html + + git add . + git commit -m "binaries for $1 release" + CURRENT_COMMIT=$(git rev-parse HEAD) + git push origin $CURRENT_COMMIT:gh-pages + return + } + if [ $# -eq 0 ] then echo "$usage" @@ -175,6 +232,20 @@ do deployIdea shift 1 ;; + --gh-pages) + if [ $# -eq 0 ] + then + echo "$usage" + shift 1 + else + deployToGhPages $2 $3 + shift 3 + fi + ;; + --maven-central) + deployToMavenCentral + shift 1 + ;; --) # End of all options shift diff --git a/eclipse-pom.xml b/eclipse-pom.xml index daf1f68323..2a5625177a 100644 --- a/eclipse-pom.xml +++ b/eclipse-pom.xml @@ -1,14 +1,20 @@ - + 4.0.0 - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle parent - 1.22.0 + 1.30.0 pom + + + LGPL-2.1+ + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + + eclipsecs-sevntu-plugin eclipsecs-sevntu-plugin-feature diff --git a/eclipsecs-sevntu-plugin-feature/feature.xml b/eclipsecs-sevntu-plugin-feature/feature.xml index 20e36f294f..172e9adee4 100644 --- a/eclipsecs-sevntu-plugin-feature/feature.xml +++ b/eclipsecs-sevntu-plugin-feature/feature.xml @@ -1,5 +1,5 @@ - + http://sevntu-checkstyle.github.io/sevntu.checkstyle/ @@ -20,6 +20,6 @@ Eclipse Public License - Version 1.0 - + diff --git a/eclipsecs-sevntu-plugin-feature/pom.xml b/eclipsecs-sevntu-plugin-feature/pom.xml index dbd76812ee..28dd54bbe8 100644 --- a/eclipsecs-sevntu-plugin-feature/pom.xml +++ b/eclipsecs-sevntu-plugin-feature/pom.xml @@ -1,19 +1,25 @@ - + 4.0.0 ../eclipse-pom.xml - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle parent - 1.22.0 + 1.30.0 - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle com.github.sevntu.checkstyle.checks.feature eclipse-feature Extension for eclipse-cs Plugin with additional Checks + + + LGPL-2.1+ + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + + diff --git a/eclipsecs-sevntu-plugin/.classpath b/eclipsecs-sevntu-plugin/.classpath deleted file mode 100644 index 793d12c5d0..0000000000 --- a/eclipsecs-sevntu-plugin/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/eclipsecs-sevntu-plugin/.project b/eclipsecs-sevntu-plugin/.project deleted file mode 100644 index 3f16447c1c..0000000000 --- a/eclipsecs-sevntu-plugin/.project +++ /dev/null @@ -1,34 +0,0 @@ - - - eclipsecs-sevntu-plugin - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/eclipsecs-sevntu-plugin/META-INF/MANIFEST.MF b/eclipsecs-sevntu-plugin/META-INF/MANIFEST.MF index d43188284e..f5d518c9f0 100644 --- a/eclipsecs-sevntu-plugin/META-INF/MANIFEST.MF +++ b/eclipsecs-sevntu-plugin/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Sevntu eclipse-cs Extension Plugin Bundle-SymbolicName: eclipsecs-sevntu-plugin;singleton:=true -Bundle-Version: 1.22.0 +Bundle-Version: 1.30.0 Require-Bundle: net.sf.eclipsecs.checkstyle, net.sf.eclipsecs.core, net.sf.eclipsecs.ui diff --git a/eclipsecs-sevntu-plugin/pom.xml b/eclipsecs-sevntu-plugin/pom.xml index aaac8586ff..10051c6a44 100644 --- a/eclipsecs-sevntu-plugin/pom.xml +++ b/eclipsecs-sevntu-plugin/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -8,24 +7,31 @@ ../eclipse-pom.xml - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle parent - 1.22.0 + 1.30.0 - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle eclipsecs-sevntu-plugin eclipse-plugin eclipse-cs Sevntu Checkstyle Plugin + + + LGPL-2.1+ + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + + - 7.2.0-SNAPSHOT + 8.10.0-SNAPSHOT - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle sevntu-checks ${project.version} @@ -79,7 +85,7 @@ - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle sevntu-checks ${sevntu.checks.version} jar diff --git a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/annotation/checkstyle-metadata.xml b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/annotation/checkstyle-metadata.xml index 035b57660a..c2f55ecdac 100755 --- a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/annotation/checkstyle-metadata.xml +++ b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/annotation/checkstyle-metadata.xml @@ -1,7 +1,7 @@ +"http://checkstyle.org/eclipse-cs/dtds/checkstyle-metadata_1_1.dtd"> diff --git a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/coding/checkstyle-metadata.properties b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/coding/checkstyle-metadata.properties index 00b4db3fb4..a78fe970b7 100755 --- a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/coding/checkstyle-metadata.properties +++ b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/coding/checkstyle-metadata.properties @@ -25,7 +25,7 @@ AvoidModifiersForTypesCheck.forbiddenClassesRegexpProtected = The regexp defines AvoidModifiersForTypesCheck.forbiddenClassesRegexpPublic = The regexp defines the names of classes, that could not have 'public' modifier. CustomDeclarationOrderCheck.name = Custom Declaration Order -CustomDeclarationOrderCheck.desc =

Checks that the parts of a class(main, nested, member inner) declaration appear in the rules order set by user using regular expressions.

The check forms line which consists of class member annotations, modifiers,type and name from your code and compares it with your RegExp.

The rule consists of:*
ClassMember(RegExp)

To set class order use the following notation of the class members (case insensitive):

  1. "Field" to denote the Fields
  2. "DeclareAnnonClassField" to denote the fields keeping objects of anonymous classes
  3. "Ctor" to denote the Constructors
  4. "Method" to denote the Methods
  5. "GetterSetter" to denote the group of getter and setter methods
  6. "MainMethod" to denote the main method
  7. "InnerClass" to denote the Inner Classes
  8. "InnerInterface" to denote the Inner Interfaces
  9. "InnerEnum" to denote the Inner Enums

RegExp can include:

  1. Annotations
  2. Modifiers(public, protected, private, abstract, static,final)
  3. Type
  4. Name

ATTENTION!

Use separator ' ', '.', '\s' between declaration in the RegExp. Whitespace should be added after each modifier.

Example:     Field(public .*final .*)     Field(public final .*)     Field(public\s*final .*)
NOTICE!

It is important to write exact order of modifiers in rules. So ruleField(public final) does not match to final public value;.ModifierOrderCheckis recommended to use.

If you set empty RegExp e.g. Field(), it means that class member doesn't have modifiers(default modifier) and checking the type and name of member doesn't occur.

Between the declaration of a array and generic can't be whitespaces.E.g.: ArrayList<String[]> someName

Use the separator '###' between the class declarations.

For Example:

Field(private static final long serialVersionUID) ###Field(public static final .*) ### Field(.*private .*) ### Ctor(.*) ###GetterSetter(.*) ### Method(.*public .*final .*|@Ignore.*public .*) ###Method(public static .*(final|(new|edit|create).*).*) ###InnerClass(public abstract .*) ### InnerInterface(.*) ### InnerEnum(.*)

*

What is group of getters and setters(GetterSetter)?

It is ordered sequence of getters and setters like:

public int getValue() {    log.info("Getting value");    return value;} *public void setValue(int newValue) {    value = newValue;} *public Object getObj() {   return obj;} *public void setObj(Object obj) {   if (obj != null) {     this.obj = obj;   } else {     throw new IllegalArgumentException("Null value");   }} *...

Getter is public method that returns class field. Name of getter should be'getFieldName' in camel case.

Setter is public method with one parameter that assigns this parameter to class field. Name of setter should be 'setFieldName' in camel case.

Setter of field X should be right after getter of field X.

*@author Danil Lopatin@author Baratali Izmailov +CustomDeclarationOrderCheck.desc =

Checks that the parts of a class(main, nested, member inner) declaration appear in the rules order set by user using regular expressions.

The check forms line which consists of class member annotations, modifiers,type and name from your code and compares it with your RegExp.

The rule consists of:*
ClassMember(RegExp)

To set class order use the following notation of the class members (case insensitive):

  1. "Field" to denote the Fields
  2. "DeclareAnonClassField" to denote the fields keeping objects of anonymous classes
  3. "Ctor" to denote the Constructors
  4. "Method" to denote the Methods
  5. "GetterSetter" to denote the group of getter and setter methods
  6. "MainMethod" to denote the main method
  7. "InnerClass" to denote the Inner Classes
  8. "InnerInterface" to denote the Inner Interfaces
  9. "InnerEnum" to denote the Inner Enums

RegExp can include:

  1. Annotations
  2. Modifiers(public, protected, private, abstract, static,final)
  3. Type
  4. Name

ATTENTION!

Use separator ' ', '.', '\s' between declaration in the RegExp. Whitespace should be added after each modifier.

Example:     Field(public .*final .*)     Field(public final .*)     Field(public\s*final .*)
NOTICE!

It is important to write exact order of modifiers in rules. So ruleField(public final) does not match to final public value;.ModifierOrderCheckis recommended to use.

If you set empty RegExp e.g. Field(), it means that class member doesn't have modifiers(default modifier) and checking the type and name of member doesn't occur.

Between the declaration of a array and generic can't be whitespaces.E.g.: ArrayList<String[]> someName

Use the separator '###' between the class declarations.

For Example:

Field(private static final long serialVersionUID) ###Field(public static final .*) ### Field(.*private .*) ### Ctor(.*) ###GetterSetter(.*) ### Method(.*public .*final .*|@Ignore.*public .*) ###Method(public static .*(final|(new|edit|create).*).*) ###InnerClass(public abstract .*) ### InnerInterface(.*) ### InnerEnum(.*)

*

What is group of getters and setters(GetterSetter)?

It is ordered sequence of getters and setters like:

public int getValue() {    log.info("Getting value");    return value;} *public void setValue(int newValue) {    value = newValue;} *public Object getObj() {   return obj;} *public void setObj(Object obj) {   if (obj != null) {     this.obj = obj;   } else {     throw new IllegalArgumentException("Null value");   }} *...

Getter is public method that returns class field. Name of getter should be'getFieldName' in camel case.

Setter is public method with one parameter that assigns this parameter to class field. Name of setter should be 'setFieldName' in camel case.

Setter of field X should be right after getter of field X.

*@author Danil Lopatin@author Baratali Izmailov CustomDeclarationOrderCheck.fieldPrefix = Prefix of field's name. CustomDeclarationOrderCheck.customDeclarationOrder = Regular expression, which sets the order of the parts of a class(main, nested, member inner). CustomDeclarationOrderCheck.caseSensitive = Set false to ignore case. @@ -52,6 +52,11 @@ ForbidCertainImportsCheck.packageNameRegexp = Package name regexp. ForbidCertainImportsCheck.forbiddenImportsRegexp = Regexp for matching forbidden imports ForbidCertainImportsCheck.forbiddenImportsExcludesRegexp = Regexp for excluding imports from checking +ForbidCertainMethodCheck.name = Forbid Certain Method +ForbidCertainMethodCheck.desc = Forbids certain method usage.

You can configure this check using following parameters:
  1. Method name regexp;
  2. Argument count range;
This check reads method & constructor names without class/object name, so, please, do NOT include class/variable name in your regular expressions when configuring.

Real-life example of usage: forbid to use all "exit" method, forbid use of assertTrue/assertFalse with 1 parameter. For doing that, you should use the following check parameters:

  • Method name regexp = "assert(True|False)"
  • Argument count range = "1"


  • . Argument count can be bounded range(e.g.: 2-4) or unbounded range(e.g.: -5, 6-). Unbounded range can be unbounded only on one side. Multiple ranges must be comma separated. Author: Raghav Kumar Gautam +ForbidCertainMethodCheck.methodName = Regex to match name of the forbidden method. When blank or unspecified, all the methods will be allowed. +ForbidCertainMethodCheck.argumentCount = Number or range to match number of arguments the forbidden method takes. Multiple ranges are separated by comma. When unspecified, only method name will be used for check. + ForbidInstantiationCheck.name = Forbid Instantiation ForbidInstantiationCheck.desc = Forbids instantiation of certain object types by their full classname.

    For example:
    "java.lang.NullPointerException" will forbid the NPE instantiation.

    Note: className should to be full: use "java.lang.NullPointerException" instead of "NullpointerException".

    ForbidInstantiationCheck.forbiddenClasses = ClassNames for objects that are forbidden to instantiate. @@ -95,10 +100,10 @@ MultipleStringLiteralsExtendedCheck.desc = Checks for multiple occurrences of th MultipleStringLiteralsExtendedCheck.ignoreOccurrenceContext = Token type names where duplicate strings are ignored even if they don't match ignoredStringsRegexp. This allows you to exclude syntactical contexts like Annotations or static initializers from the check. MultipleStringLiteralsExtendedCheck.ignoreStringsRegexp = Regexp pattern for ignored strings (with quotation marks) MultipleStringLiteralsExtendedCheck.name = Multiple String Literals Extended -MultipleStringLiteralsExtendedCheck.highlightAllDuplicates = Check to highlight all dublicates +MultipleStringLiteralsExtendedCheck.highlightAllDuplicates = Check to highlight all duplicates TernaryPerExpressionCountCheck.name = Ternary Per Expression Count -TernaryPerExpressionCountCheck.desc = Restricts the number of ternary operators in expression to a specific limit.

    Rationale: This Check helps to improve code readability by pointing developer on
    expressions which contain more than user-defined count of ternary operators.

    It points to complicated ternary expressions. Reason:
    - Complicated ternary expressions are not easy to read.
    - Complicated ternary expressions could lead to ambiguous result if user
    does not know Java's operators priority well, e.g.:

    String str = null;
    String x = str != null ? "A" : "B" + str == null ? "C" : "D";
    System.out.println(x);

    Output for code above is "D", but more obvious would be "BC".

    Check has following properties:
    • maxTernaryPerExpressionCount - limit of ternary operators perexpression
    • ignoreTernaryOperatorsInBraces - if true Check will ignore ternary operators
      in braces (braces explicitly set priority level)
    • ignoreIsolatedTernaryOnLine - if true Check will ignore one line ternary operators,
      if only it is places in line alone.
    Options ignoreTernaryOperatorsInBraces and ignoreIsolatedTernaryOnLine can
    make Check less strict, e.g.:
    Using ignoreTernaryOperatorsInBraces option (value = true)
    does not put violation on code below:

    callString = "{? = call " +
    (StringUtils.hasLength(catalogNameToUse) ? catalogNameToUse + "." : "") +
    (StringUtils.hasLength(schemaNameToUse) ? schemaNameToUse + "." : "") +
    procedureNameToUse + "(";

    When using ignoreIsolatedTernaryOnLine (value = true), even without
    ignoreTernaryOperatorsInBraces option Check won't warn on code below:

    int a = (d == 5) ? d : f
    +
    ((d == 6) ? g : k);

    @author Aleksey Nesterenko +TernaryPerExpressionCountCheck.desc = Restricts the number of ternary operators in expression to a specific limit.

    Rationale: This Check helps to improve code readability by pointing developer on
    expressions which contain more than user-defined count of ternary operators.

    It points to complicated ternary expressions. Reason:
    - Complicated ternary expressions are not easy to read.
    - Complicated ternary expressions could lead to ambiguous result if user
    does not know Java's operators priority well, e.g.:

    String str = null;
    String x = str != null ? "A" : "B" + str == null ? "C" : "D";
    System.out.println(x);

    Output for code above is "D", but more obvious would be "BC".

    Check has following properties:
    • maxTernaryPerExpressionCount - limit of ternary operators per expression
    • ignoreTernaryOperatorsInBraces - if true Check will ignore ternary operators
      in braces (braces explicitly set priority level)
    • ignoreIsolatedTernaryOnLine - if true Check will ignore one line ternary operators,
      if only it is places in line alone.
    Options ignoreTernaryOperatorsInBraces and ignoreIsolatedTernaryOnLine can
    make Check less strict, e.g.:
    Using ignoreTernaryOperatorsInBraces option (value = true)
    does not put violation on code below:

    callString = "{? = call " +
    (StringUtils.hasLength(catalogNameToUse) ? catalogNameToUse + "." : "") +
    (StringUtils.hasLength(schemaNameToUse) ? schemaNameToUse + "." : "") +
    procedureNameToUse + "(";

    When using ignoreIsolatedTernaryOnLine (value = true), even without
    ignoreTernaryOperatorsInBraces option Check won't warn on code below:

    int a = (d == 5) ? d : f
    +
    ((d == 6) ? g : k);

    @author Aleksey Nesterenko TernaryPerExpressionCountCheck.maxTernaryPerExpressionCount = Maximum number of ternary operators in expression TernaryPerExpressionCountCheck.ignoreTernaryOperatorsInBraces = Ignore ternary operators in expression in case if priority level is set explicitly TernaryPerExpressionCountCheck.ignoreIsolatedTernaryOnLine = Ignore ternary operators in expression in case if ternary operator is isolated in line @@ -166,7 +171,7 @@ UselessSingleCatchCheck.desc =

    Checks for the presence of useless single catc UselessSingleCatchCheck.name = Useless single catch check UselessSuperCtorCallCheck.name = Useless super constructor call -UselessSuperCtorCallCheck.desc =

    Checks for useless "super()" calls in ctors.

    "super()" call could be considered by Check as "useless" in two cases:

    Case 1. no-argument "super()" is called from class ctor if class is not derived, for example:

    class Dummy {
    Dummy() {
    super();

    }
    "super()" call is useless because class "Dummy" is not derived.

    Case 2. no-argument "super()" is called without parameters from class ctor if class is derived, for example:

    class Derived extends Base {
    Derived() {
    super();
    }
    }
    Java compiler automatically inserts a call to the no-args constructor of the super class, so there is no need to call super ctor explicitly. Check has options "allowCallToNoArgsSuperCtor" and "allowCallToNoArgsSuperCtorIfMultiplePublicCtor" to adjust check behavior for such cases(see Check`s options description for details).

    Check has following options:

    "allowCallToNoArgsSuperCtor" - if this option set to true, Check will not generate violations when "super()" called inside derived class. This option defaults to "false". If for example this option set to "true", then Check will not generate violation for cases like following:

    class Base {
    public Base() {
    }
    }

    class Derived extends Base {
    public Derived() {
    super();
    }
    }

    "allowCallToNoArgsSuperCtorIfMultiplePublicCtor" - if this option set to "true",then Check will not generate violation when "super()" called inside class ctor when class has multiple public ctors(however, setting this option to"true" will not prevent Check from logging violation if class does not extend anything). This option defaults to "false". This option may be usefull for cases in which class`s ctors just forward its arguments to super ctors, thus removing "super()" in this case will make default ctors look not like others.For example:

    class Base {
    public Base() {
    }

    public Base(int i) {
    }
    }

    class Derived extends Base {
    public Derived() {
    super(); // this "super()" will not be considered useless if option is set to true,
    // because "Derived" has multiple public ctors.
    }

    public Derived(int i) {
    super(i); // this "super()" will not be considered useless if option is set to true,
    // because "Derived" has multiple public ctors.
    }
    }

    class NotDerived{
    public NotDerived() {
    super(); // this "super()" will be considered useless regardless of option value,
    // because "NotDerived" does not extend anything.
    }
    public NotDerived(int i) {
    super(); // this "super()" will be considered useless regardless of option value,
    // because "NotDerived" does not extend anything.
    }
    }

    @author Zuy Alexey +UselessSuperCtorCallCheck.desc =

    Checks for useless "super()" calls in ctors.

    "super()" call could be considered by Check as "useless" in two cases:

    Case 1. no-argument "super()" is called from class ctor if class is not derived, for example:

    class Dummy {
    Dummy() {
    super();

    }
    "super()" call is useless because class "Dummy" is not derived.

    Case 2. no-argument "super()" is called without parameters from class ctor if class is derived, for example:

    class Derived extends Base {
    Derived() {
    super();
    }
    }
    Java compiler automatically inserts a call to the no-args constructor of the super class, so there is no need to call super ctor explicitly. Check has options "allowCallToNoArgsSuperCtor" and "allowCallToNoArgsSuperCtorIfMultiplePublicCtor" to adjust check behavior for such cases(see Check`s options description for details).

    Check has following options:

    "allowCallToNoArgsSuperCtor" - if this option set to true, Check will not generate violations when "super()" called inside derived class. This option defaults to "false". If for example this option set to "true", then Check will not generate violation for cases like following:

    class Base {
    public Base() {
    }
    }

    class Derived extends Base {
    public Derived() {
    super();
    }
    }

    "allowCallToNoArgsSuperCtorIfMultiplePublicCtor" - if this option set to "true",then Check will not generate violation when "super()" called inside class ctor when class has multiple public ctors(however, setting this option to"true" will not prevent Check from logging violation if class does not extend anything). This option defaults to "false". This option may be useful for cases in which class`s ctors just forward its arguments to super ctors, thus removing "super()" in this case will make default ctors look not like others.For example:

    class Base {
    public Base() {
    }

    public Base(int i) {
    }
    }

    class Derived extends Base {
    public Derived() {
    super(); // this "super()" will not be considered useless if option is set to true,
    // because "Derived" has multiple public ctors.
    }

    public Derived(int i) {
    super(i); // this "super()" will not be considered useless if option is set to true,
    // because "Derived" has multiple public ctors.
    }
    }

    class NotDerived{
    public NotDerived() {
    super(); // this "super()" will be considered useless regardless of option value,
    // because "NotDerived" does not extend anything.
    }
    public NotDerived(int i) {
    super(); // this "super()" will be considered useless regardless of option value,
    // because "NotDerived" does not extend anything.
    }
    }

    @author Zuy Alexey UselessSuperCtorCallCheck.allowCallToNoArgsSuperCtor = Allow calls to no-arguments super constructor from derived class. UselessSuperCtorCallCheck.allowCallToNoArgsSuperCtorIfMultiplePublicCtor = Allow calls to no-arguments super constructor from derived class if it has multiple public constructors. @@ -180,3 +185,9 @@ WhitespaceBeforeArrayInitializerCheck.desc = This checks enforces whitespace bef EnumTrailingCommaAndSemicolonCheck.name = Enum Trailing Comma EnumTrailingCommaAndSemicolonCheck.desc = This checks enforces a trailing comma at the end of a line in an enum constant definition. + +MoveVariableInsideIfCheck.name = Move Variable Inside If Check +MoveVariableInsideIfCheck.desc = Checks if a variable is only used inside if statements and asks for it's declaration to be moved there too. + +RequireFailForTryCatchInJunitCheck.name = Require Fail For Try/Catch in JUnit Check +RequireFailForTryCatchInJunitCheck.desc = Checks if a try/catch block has a junit fail assertion inside the try for a junit method. diff --git a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/coding/checkstyle-metadata.xml b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/coding/checkstyle-metadata.xml index 3455bd9e37..19351db51c 100644 --- a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/coding/checkstyle-metadata.xml +++ b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/coding/checkstyle-metadata.xml @@ -1,7 +1,7 @@ +"http://checkstyle.org/eclipse-cs/dtds/checkstyle-metadata_1_1.dtd"> @@ -179,6 +179,19 @@ + + + %ForbidCertainMethodCheck.desc + + %ForbidCertainMethodCheck.methodName + + + %ForbidCertainMethodCheck.argumentCount + + + + + %ForbidInstantiationCheck.desc @@ -431,6 +444,7 @@ + @@ -528,6 +542,20 @@ + + + %MoveVariableInsideIfCheck.desc + + + + + + + %RequireFailForTryCatchInJunitCheck.desc + + + + %EnumTrailingCommaAndSemicolonCheck.desc diff --git a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/design/checkstyle-metadata.properties b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/design/checkstyle-metadata.properties index 88a66b4609..3fb1fc557d 100644 --- a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/design/checkstyle-metadata.properties +++ b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/design/checkstyle-metadata.properties @@ -15,7 +15,7 @@ ChildBlockLengthCheck.maxChildBlockPercentage = Maximum percentage ratio between ChildBlockLengthCheck.ignoreBlockLinesCount = Maximum number of lines of which block body may consist to be skipped by check. NoMainMethodInAbstractClassCheck.name = No Main Method In Abstract Class -NoMainMethodInAbstractClassCheck.desc = Forbids main methods in abstract classes. Rationale: existance of 'main' method can mislead a developer to consider this class as a ready-to-use implementation. +NoMainMethodInAbstractClassCheck.desc = Forbids main methods in abstract classes. Rationale: existence of 'main' method can mislead a developer to consider this class as a ready-to-use implementation. ForbidWildcardAsReturnTypeCheck.name = Forbid Wildcard As Return Type ForbidWildcardAsReturnTypeCheck.desc = Prevents using wildcards as return type of methods.

    Joshua Bloch, "Effective Java (2nd edition)" Item 28: page 137 :

    "Do not use wildcard types as return types. Rather than providing additional flexibility for your users, it would force them to use wildcard types in client code. Properly used, wildcard types are nearly invisible to users of a class. They cause methods to accept the parameters they should accept and reject those they should reject. If the user of a class has to think about wildcard types, there is probably something wrong with the class\u2019s API."

    @@ -50,3 +50,8 @@ HideUtilityClassConstructorCheck.desc = Make sure that utility classes (classes InnerClassCheck.name = Inner Class InnerClassCheck.desc = Check nested (internal) classes to be declared at the bottom of the class after all methods (fields) declaration. + +CheckstyleTestMakeupCheck.name = Checkstyle Test Makeup +CheckstyleTestMakeupCheck.desc = Custom check to ensure Checkstyle tests are designed correctly. +CheckstyleTestMakeupCheck.createMethodRegexp = Regular expression for matching a create configuration method by name. +CheckstyleTestMakeupCheck.verifyMethodRegexp = Regular expression for matching a verify method by name. diff --git a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/design/checkstyle-metadata.xml b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/design/checkstyle-metadata.xml index 15f325fdc0..b55cc10551 100644 --- a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/design/checkstyle-metadata.xml +++ b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/design/checkstyle-metadata.xml @@ -1,7 +1,7 @@ +"http://checkstyle.org/eclipse-cs/dtds/checkstyle-metadata_1_1.dtd"> @@ -160,5 +160,24 @@
    + + + %CheckstyleTestMakeupCheck.desc + + + %CheckstyleTestMakeupCheck.createMethodRegexp + + + + %CheckstyleTestMakeupCheck.verifyMethodRegexp + + + + + + + + +
    diff --git a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/naming/checkstyle-metadata.properties b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/naming/checkstyle-metadata.properties index 82007098cb..fb0b53dc8c 100644 --- a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/naming/checkstyle-metadata.properties +++ b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/naming/checkstyle-metadata.properties @@ -3,11 +3,9 @@ InterfaceTypeParameterNameCheck.desc = Checks that interface type parameter name InterfaceTypeParameterNameCheck.format = Regex that interface type parameter names must to conform EnumValueNameCheck.name = Enum values name -EnumValueNameCheck.desc =

    Check forces enum values to match the specific pattern. According to "Java Coding Style" by Achut Reddy p 3.3 constants include "all static final object reference types that are never followed by " ." (dot).", i.e. enums, which are followed by dot while used in the code are to be treated as static object references, while enums, that are not used with following dot, should be treated as constants.

    Enums are defined to be used as class have some own methods. This condition is used to distinguish between Values Enumeration and Class Enumeration. Values Enumeration looks like the following:

    enum SimpleErrorEnum\n  {\n      FIRST_SIMPLE, SECOND_SIMPLE, THIRD_SIMPLE;\n  }

    While Class Enumeration has some methods, for example:

     enum SimpleErrorEnum\n   {\n       FIRST_SIMPLE, SECOND_SIMPLE, THIRD_SIMPLE;\n \n       public String toString() {\n           return Integer.toString(ordinal() + 10);\n       }\n   }

    Name format for Class Enumeration is specified with setObjFormat(String) , while format for enum constants - with setConstFormat(String)

    To avoid assuming enum as static object reference, while using some specific methods, setExcludes(List) can be used. For example to make enum in the previous example a constant set Excludes property to a value toString

    By default toString is used as an exclusion.

    -EnumValueNameCheck.constFormat = Regex for Values Enumeration names to conform -EnumValueNameCheck.objFormat = Regex for Class Enumeration names to conform -EnumValueNameCheck.excludes = Exclude method and field names regexp list (comma-separated) +EnumValueNameCheck.desc = Checks that enumeration value names conform to a format specified by the format property. +EnumValueNameCheck.format = Regex for enumeration value names to conform -UniformEnumConstantNameCheck.name = Enum values name +UniformEnumConstantNameCheck.name = Uniform Enum values name UniformEnumConstantNameCheck.desc = Check forces enum values to match one of the specified patterns and forces all the values to follow only one of the specified patterns. UniformEnumConstantNameCheck.formats = Regex list that enum value names should conform diff --git a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/naming/checkstyle-metadata.xml b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/naming/checkstyle-metadata.xml index 7cfc921795..d96cd7fce5 100644 --- a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/naming/checkstyle-metadata.xml +++ b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/naming/checkstyle-metadata.xml @@ -1,7 +1,7 @@ +"http://checkstyle.org/eclipse-cs/dtds/checkstyle-metadata_1_1.dtd"> @@ -20,18 +20,11 @@ %EnumValueNameCheck.desc - - %EnumValueNameCheck.constFormat - - - %EnumValueNameCheck.objFormat - - - %EnumValueNameCheck.excludes + + %EnumValueNameCheck.format - - + diff --git a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/sizes/checkstyle-metadata.xml b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/sizes/checkstyle-metadata.xml index ae410ca4fd..d76ad4d19c 100755 --- a/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/sizes/checkstyle-metadata.xml +++ b/eclipsecs-sevntu-plugin/src/com/github/sevntu/checkstyle/checks/sizes/checkstyle-metadata.xml @@ -1,7 +1,7 @@ +"http://checkstyle.org/eclipse-cs/dtds/checkstyle-metadata_1_1.dtd"> diff --git a/pom-version-bump.sh b/pom-version-bump.sh index 7251f2f3e7..cf70d257ed 100755 --- a/pom-version-bump.sh +++ b/pom-version-bump.sh @@ -40,7 +40,7 @@ do mv $i.new $i done -#aditional version reference in dependency +#additional version reference in dependency FILE=sevntu-checkstyle-maven-plugin/pom.xml echo "Updating: "$FILE xmlstarlet ed --ps -N pom="http://maven.apache.org/POM/4.0.0" \ @@ -48,7 +48,7 @@ xmlstarlet ed --ps -N pom="http://maven.apache.org/POM/4.0.0" \ $FILE > $FILE.new mv $FILE.new $FILE -#aditional version reference, eclipse file +#additional version reference, eclipse file FILE=eclipsecs-sevntu-plugin-feature/feature.xml echo "Updating: "$FILE xmlstarlet ed --ps \ diff --git a/release.sh b/release.sh new file mode 100755 index 0000000000..301c43f492 --- /dev/null +++ b/release.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +set -e + +CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +# Ex: 0.0.0 +OLD_VERSION=$1 +# Ex: 0.1.0 +NEW_VERSION=$2 +# Ex: 0.2.0 +NEXT_VERSION=$3 + +ECLIPSE_CS_DIR="/tmp/eclipse-cs" +CONTRIBUTION_DIR="/tmp/checkstyle.contribution" + +GITHUB_PROJECT="sevntu-checkstyle/sevntu.checkstyle" + +# https://github.com/settings/tokens +# SEVNTU_GITHUB_TOKEN="" + +if [[ -z "$OLD_VERSION" || -z "$NEW_VERSION" || -z "$NEXT_VERSION" ]] +then + echo "Old and New and Next version needs to be specified in the arguments" + exit 1 +fi +if [[ -z "$SEVNTU_GITHUB_TOKEN" ]] +then + echo "Github token needs to be specified in the script or as an environment variable 'SEVNTU_GITHUB_TOKEN'" + exit 1 +fi + +# require git, xmlstarlet (xml parsing) and jq (json parsing) +if ! [ -x "$(command -v git)" ]; then + echo "Error: git is not installed" + exit 1 +fi +if ! [ -x "$(command -v xmlstarlet)" ]; then + echo "Error: xmlstarlet is not installed" + exit 1 +fi +if ! [ -x "$(command -v jq)" ]; then + echo "Error: jq is not installed" + exit 1 +fi + +# fetch latest origin from server +echo "Resetting repository to origin" +git fetch origin +git reset --hard HEAD +git clean -f -d +git checkout origin/master + +cd sevntu-checks +ECLIPSE_CS_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) +cd .. + +# bring in and run release notes builder +echo "Cloning and installing ReleaseNotes builder" + +if [ ! -d $CONTRIBUTION_DIR ]; then + mkdir $CONTRIBUTION_DIR +fi + +cd $CONTRIBUTION_DIR + +if [ ! -d "$CONTRIBUTION_DIR/contribution/.git" ]; then + git clone https://github.com/checkstyle/contribution.git + + cd contribution +else + cd contribution + + git fetch origin +fi + +git reset --hard HEAD +git clean -f -d +git checkout origin/master + +cd releasenotes-builder +mvn package -DskipTests +cd target + +java -jar releasenotes-builder-1.0-all.jar -localRepoPath $CURRENT_DIR -remoteRepoPath $GITHUB_PROJECT -startRef $OLD_VERSION -releaseNumber $NEW_VERSION -githubAuthToken $SEVNTU_GITHUB_TOKEN -generateXdoc -xdocTemplate $CURRENT_DIR/sevntu_xdoc_freemarker.template + +# bring in eclipse-cs version in-use +echo "Cloning and installing Eclipse CS version $ECLIPSE_CS_VERSION" + +if [ ! -d $ECLIPSE_CS_DIR ]; then + mkdir $ECLIPSE_CS_DIR +fi + +cd $ECLIPSE_CS_DIR + +if [ ! -d "$ECLIPSE_CS_DIR/eclipse-cs/.git" ]; then + git clone https://github.com/checkstyle/eclipse-cs.git + + cd eclipse-cs +else + cd eclipse-cs + + git fetch origin +fi + +git reset --hard HEAD +git clean -f -d +git checkout tags/$ECLIPSE_CS_VERSION.0 + +mvn clean install + +# update versions in all files +echo "Bumping all versions from $OLD_VERSION to $NEW_VERSION" +cd $CURRENT_DIR +./pom-version-bump.sh $OLD_VERSION $NEW_VERSION + +# test and prepare for deployment +echo "Prepare for deployment" + +$CURRENT_DIR/deploy-all.sh +cd $CURRENT_DIR + +echo "" +read -p "Press enter to continue before committing" + +# commit version bump +echo "Committing version bump" +git add . +git commit -m "config: version bump to $NEW_VERSION" +CURRENT_COMMIT=$(git rev-parse HEAD) +git push origin $CURRENT_COMMIT:master + +# create new release tag +echo "Pushing new tag $NEW_VERSION" +git tag -a $NEW_VERSION -m "release $NEW_VERSION" +git push --tags + +# deploy gh-pages +echo "Updating gh-pages" + +$CURRENT_DIR/deploy.sh --gh-pages $NEW_VERSION $CONTRIBUTION_DIR/contribution/releasenotes-builder/target/xdoc.xml + +# deploy to maven central +echo "Deploying to maven central" +$CURRENT_DIR/deploy.sh --maven-central + +# dropped support for gh-pages/sevntu-checkstyle-default-configuration.xml + +# retrieve old milestone number +# https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository +OLD_MILESTONE_NUMBER=$(curl --silent --show-error --fail \ + -H "Authorization: token $SEVNTU_GITHUB_TOKEN" \ + https://api.github.com/repos/$GITHUB_PROJECT/milestones?state=open \ + | jq '.[0].number') + +echo "" +read -p "Press enter to continue before closing and creating new milestone" + +# close old milestone +# https://developer.github.com/v3/issues/milestones/#update-a-milestone +echo "Closing old milestone $OLD_MILESTONE_NUMBER" +curl --silent --show-error --fail -H "Authorization: token $SEVNTU_GITHUB_TOKEN" \ + -d "{ \"state\": \"closed\" }" \ + -X PATCH https://api.github.com/repos/$GITHUB_PROJECT/milestones/$OLD_MILESTONE_NUMBER + +# create new milestone +# https://developer.github.com/v3/issues/milestones/#create-a-milestone +echo "Creating new milestone for $NEXT_VERSION" +curl --silent --show-error --fail -H "Authorization: token $SEVNTU_GITHUB_TOKEN" \ + -d "{ \"title\": \"$NEXT_VERSION\", \ + \"state\": \"open\", \ + \"description\": \"\" }" \ + -X POST https://api.github.com/repos/$GITHUB_PROJECT/milestones + +echo "Done" diff --git a/sevntu-checks/.ci/eclipse-compiler-javac.sh b/sevntu-checks/.ci/eclipse-compiler-javac.sh new file mode 100755 index 0000000000..256e3e03ec --- /dev/null +++ b/sevntu-checks/.ci/eclipse-compiler-javac.sh @@ -0,0 +1,42 @@ +#!/bin/bash +set -e + +if [ -z "$1" ]; then + echo "No parameters supplied!" + echo " The classpath of the project and it's libraries to compile must be supplied." + exit 1 +fi +if [ -z "$2" ]; then + echo "Second parameter not supplied!" + echo " The checkstyle release name must be supplied as the second parameter." + exit 1 +fi + +ECJ_JAR="ecj-4.7.jar" +ECJ_MAVEN_VERSION="R-4.7-201706120950" +ECJ_PATH=~/.m2/repository/$ECJ_MAVEN_VERSION/$ECJ_JAR + +if [ ! -f $ECJ_PATH ]; then + echo "$ECJ_PATH is not found, downloading ..." + mkdir -p $(dirname "$ECJ_PATH") + wget http://ftp-stud.fht-esslingen.de/pub/Mirrors/eclipse/eclipse/downloads/drops4/$ECJ_MAVEN_VERSION/$ECJ_JAR -O $ECJ_PATH +fi + +wget https://github.com/checkstyle/checkstyle/blob/checkstyle-$2/config/org.eclipse.jdt.core.prefs + +mkdir -p target/classes +mkdir -p target/eclipse + +RESULT_FILE=target/eclipse/report.txt + +echo "Executing eclipse compiler, output is redirected to $RESULT_FILE..." +java -jar $ECJ_PATH -target 1.8 -source 1.8 -cp $1 \ + -d target/eclipse-compile \ + -enableJavadoc src/main/java src/test/java -properties org.eclipse.jdt.core.prefs \ + > $RESULT_FILE 2>&1 | true + +echo "Checking for ERROR|WARNING|INFO in $RESULT_FILE ..." +if [[ $(grep -E "ERROR|WARNING|INFO" $RESULT_FILE | cat | wc -l) > 0 ]]; then + cat $RESULT_FILE + false +fi diff --git a/sevntu-checks/.ci/wercker.sh b/sevntu-checks/.ci/wercker.sh new file mode 100755 index 0000000000..218e0027cf --- /dev/null +++ b/sevntu-checks/.ci/wercker.sh @@ -0,0 +1,188 @@ +#!/bin/bash +# Attention, there is no "-x" to avoid problems on Wercker +set -e + +function checkout_from { + CLONE_URL=$1 + PROJECT=$(echo "$CLONE_URL" | sed -nE 's/.*\/(.*).git/\1/p') + mkdir -p .ci-temp + cd .ci-temp + if [ -d "$PROJECT" ]; then + echo "Target project $PROJECT is already cloned, latest changes will be fetched" + cd $PROJECT + git fetch + cd ../ + else + for i in 1 2 3 4 5; do git clone $CLONE_URL && break || sleep 15; done + fi + cd ../ +} + +case $1 in + +no-exception-struts) + CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + SEVNTU_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo CS_version: ${CS_POM_VERSION} + echo SEVNTU_version: ${SEVNTU_POM_VERSION} + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-for-wercker.properties + sed -i'' 's/#apache-struts/apache-struts/' projects-for-wercker.properties + groovy ./launch.groovy --listOfProjects projects-for-wercker.properties \ + --config checks-sevntu-error.xml --checkstyleVersion ${CS_POM_VERSION} \ + --sevntuVersion ${SEVNTU_POM_VERSION} + cd ../../ + rm -rf contribution + ;; + +no-exception-guava) + CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + SEVNTU_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo CS_version: ${CS_POM_VERSION} + echo SEVNTU_version: ${SEVNTU_POM_VERSION} + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-for-wercker.properties + sed -i'' 's/#guava/guava/' projects-for-wercker.properties + groovy ./launch.groovy --listOfProjects projects-for-wercker.properties \ + --config checks-sevntu-error.xml --checkstyleVersion ${CS_POM_VERSION} \ + --sevntuVersion ${SEVNTU_POM_VERSION} + cd ../../ + rm -rf contribution + ;; + +no-exception-hibernate-orm) + CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + SEVNTU_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo CS_version: ${CS_POM_VERSION} + echo SEVNTU_version: ${SEVNTU_POM_VERSION} + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#hibernate-orm/hibernate-orm/' projects-to-test-on.properties + groovy ./launch.groovy --listOfProjects projects-for-wercker.properties \ + --config checks-sevntu-error.xml --checkstyleVersion ${CS_POM_VERSION} \ + --sevntuVersion ${SEVNTU_POM_VERSION} + cd ../../ + rm -rf contribution + ;; + +no-exception-spotbugs) + CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + SEVNTU_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo CS_version: ${CS_POM_VERSION} + echo SEVNTU_version: ${SEVNTU_POM_VERSION} + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#spotbugs/spotbugs/' projects-to-test-on.properties + groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ + --config checks-sevntu-error.xml --checkstyleVersion ${CS_POM_VERSION} \ + --sevntuVersion ${SEVNTU_POM_VERSION} + cd ../../ + rm -rf contribution + ;; + +no-exception-spring-framework) + CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + SEVNTU_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo CS_version: ${CS_POM_VERSION} + echo SEVNTU_version: ${SEVNTU_POM_VERSION} + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties + groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ + --config checks-sevntu-error.xml --checkstyleVersion ${CS_POM_VERSION} \ + --sevntuVersion ${SEVNTU_POM_VERSION} + cd ../../ + rm -rf contribution + ;; + +no-exception-hbase) + CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + SEVNTU_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo CS_version: ${CS_POM_VERSION} + echo SEVNTU_version: ${SEVNTU_POM_VERSION} + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#Hbase/Hbase/' projects-to-test-on.properties + groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ + --config checks-sevntu-error.xml --checkstyleVersion ${CS_POM_VERSION} \ + --sevntuVersion ${SEVNTU_POM_VERSION} + cd ../../ + rm -rf contribution + ;; + +no-exception-Pmd-elasticsearch-lombok-ast) + CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + SEVNTU_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo CS_version: ${CS_POM_VERSION} + echo SEVNTU_version: ${SEVNTU_POM_VERSION} + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#pmd/pmd/' projects-to-test-on.properties + sed -i.'' 's/#elasticsearch/elasticsearch/' projects-to-test-on.properties + sed -i.'' 's/#lombok-ast/lombok-ast/' projects-to-test-on.properties + groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ + --config checks-sevntu-error.xml --checkstyleVersion ${CS_POM_VERSION} \ + --sevntuVersion ${SEVNTU_POM_VERSION} + cd ../../ + rm -rf contribution + ;; + +no-exception-alot-of-projects) + CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.eclipse-cs.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + SEVNTU_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo CS_version: ${CS_POM_VERSION} + echo SEVNTU_version: ${SEVNTU_POM_VERSION} + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#RxJava/RxJava/' projects-to-test-on.properties + sed -i.'' 's/#java-design-patterns/java-design-patterns/' projects-to-test-on.properties + sed -i.'' 's/#MaterialDesignLibrary/MaterialDesignLibrary/' projects-to-test-on.properties + sed -i.'' 's/#apache-ant/apache-ant/' projects-to-test-on.properties + sed -i.'' 's/#apache-jsecurity/apache-jsecurity/' projects-to-test-on.properties + sed -i.'' 's/#android-launcher/android-launcher/' projects-to-test-on.properties + groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ + --config checks-sevntu-error.xml --checkstyleVersion ${CS_POM_VERSION} \ + --sevntuVersion ${SEVNTU_POM_VERSION} + cd ../../ + rm -rf contribution + ;; + +*) + echo "Unexpected argument: $1" + sleep 5s + false + ;; + +esac diff --git a/sevntu-checks/.classpath b/sevntu-checks/.classpath deleted file mode 100644 index 4f3ccaa157..0000000000 --- a/sevntu-checks/.classpath +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sevntu-checks/.project b/sevntu-checks/.project deleted file mode 100644 index 865b916f72..0000000000 --- a/sevntu-checks/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - sevntu-checks - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/sevntu-checks/checkstyle.properties b/sevntu-checks/checkstyle.properties index 6b8f3fc973..b33a3850a5 100644 --- a/sevntu-checks/checkstyle.properties +++ b/sevntu-checks/checkstyle.properties @@ -1,4 +1,6 @@ checkstyle.suppressions.file=suppressions.xml +checkstyle.suppressions-xpath.file=suppressions.xml checkstyle.header.file=https://raw.githubusercontent.com/checkstyle/checkstyle/master/config/java.header checkstyle.regexp.header.file=https://raw.githubusercontent.com/checkstyle/checkstyle/master/config/java_regexp.header checkstyle.importcontrol.file=import-control.xml +checkstyle.importcontroltest.file=import-control-test.xml diff --git a/sevntu-checks/import-control-test.xml b/sevntu-checks/import-control-test.xml new file mode 100644 index 0000000000..198bbedf39 --- /dev/null +++ b/sevntu-checks/import-control-test.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/sevntu-checks/import-control.xml b/sevntu-checks/import-control.xml index 20c6d84be5..d1b80f02db 100644 --- a/sevntu-checks/import-control.xml +++ b/sevntu-checks/import-control.xml @@ -77,7 +77,7 @@ - + @@ -91,16 +91,16 @@ - + - + - + diff --git a/sevntu-checks/pom.xml b/sevntu-checks/pom.xml index ff86817128..54b1de47b1 100644 --- a/sevntu-checks/pom.xml +++ b/sevntu-checks/pom.xml @@ -1,21 +1,34 @@ - + 4.0.0 - com.github.sevntu.checkstyle + + + org.sonatype.oss + oss-parent + 9 + + + com.github.sevntu-checkstyle sevntu-checks - 1.22.0 + 1.30.0 iso-8859-1 - 7.3 - - 7.2 + + 8.10 + https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-${checkstyle.eclipse-cs.version}/config/checkstyle_checks.xml 2.17 RELEASE + + + LGPL-2.1+ + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + + com.puppycrawl.tools @@ -62,14 +75,6 @@ - - - com.github.sevntu.checkstyle - sevntu-checks - file://${basedir}/../gh-pages/maven2/ - - - @@ -81,6 +86,53 @@ 1.8
    + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + package + + jar + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + package + + jar + + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + + sonatype-nexus-staging + https://oss.sonatype.org/ + true + true + + + org.apache.maven.plugins maven-surefire-plugin @@ -118,7 +170,7 @@ com.puppycrawl.tools checkstyle - ${checkstyle.version} + ${checkstyle.eclipse-cs.version}
    @@ -131,7 +183,7 @@ check - https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-${checkstyle.version}/config/checkstyle_checks.xml + ${checkstyle.configLocation} true false checkstyle.properties @@ -148,48 +200,20 @@ true - 100 100 88 96 - .*.checks.annotation.ForbidAnnotationCheck7096 - .*.checks.coding.AvoidConstantAsFirstOperandInConditionCheck87100 - .*.checks.coding.ConfusingConditionCheck82100 .*.checks.coding.CustomDeclarationOrderCheck.*8183 - .*.checks.coding.DiamondOperatorForVariableDefinitionCheck90100 .*.checks.coding.EitherLogOrThrowCheck8899 - .*.checks.coding.EmptyPublicCtorInClassCheck8995 - .*.checks.coding.FinalizeImplementationCheck6892 - .*.checks.coding.ForbidCertainImportsCheck6184 - .*.checks.coding.ForbidInstantiationCheck9491 .*.checks.coding.ForbidThrowAnonymousExceptionsCheck8197 - .*.checks.coding.IllegalCatchExtendedCheck8897 .*.checks.coding.MapIterationInForEachLoopCheck9098 - .*.checks.coding.MultipleStringLiteralsExtendedCheck9296 - .*.checks.coding.MultipleVariableDeclarationsExtendedCheck95100 - .*.checks.coding.NameConventionForJunit4TestClassesCheck8696 .*.checks.coding.NoNullForCollectionReturnCheck8596 - .*.checks.coding.OverridableMethodInConstructorCheck8899 - .*.checks.coding.RedundantReturnCheck9897 - .*.checks.coding.ReturnBooleanFromTernaryCheck75100 - .*.checks.coding.ReturnCountExtendedCheck91100 - .*.checks.coding.ReturnNullInsteadOfBooleanCheck8088 - .*.checks.coding.SimpleAccessorNameNotationCheck72100 - .*.checks.coding.UnnecessaryParenthesesExtendedCheck90100 - .*.checks.design.AvoidConditionInversionCheck9796 - .*.checks.design.CauseParameterInExceptionCheck9698 - .*.checks.design.ChildBlockLengthCheck89100 - .*.checks.design.ForbidWildcardAsReturnTypeCheck98100 + .*.checks.coding.OverridableMethodInConstructorCheck9499 .*.checks.design.HideUtilityClassConstructorCheck94100 - .*.checks.design.InnerClassCheck91100 - .*.checks.design.NoMainMethodInAbstractClassCheck9298 - .*.checks.design.PublicReferenceToPrivateTypeCheck9790 - .*.checks.naming.EnumValueNameCheck86100 - .*.checks.sizes.LineLengthExtendedCheck1006 - com.github.sevntu.checkstyle.Utils00 @@ -207,13 +231,7 @@ - travis - - - env.TRAVIS - true - - + coverall @@ -222,34 +240,62 @@ 0.7.1.201405082137 - prepare-agent + pre-unit-test prepare-agent - report + post-unit-test report - prepare-package + test org.eluder.coveralls coveralls-maven-plugin - 2.2.0 + 4.3.0 - selftesting + eclipse-compiler + + + org.eclipse.jdt + org.eclipse.jdt.annotation + 2.1.0 + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + .ci/eclipse-compiler-javac.sh + test + + + ${checkstyle.eclipse-cs.version} + + + + + + + + no-validations true true true + true true true true @@ -257,6 +303,12 @@ true true + + + selftesting + + false + @@ -267,11 +319,11 @@ com.puppycrawl.tools checkstyle - ${checkstyle.version} + ${checkstyle.eclipse-cs.version} - + - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle sevntu-checks ${project.version} @@ -298,6 +350,41 @@ + + + local-deploy + + + com.github.sevntu-checkstyle + sevntu-checks + file://${deployDir}/maven2/ + + + + + + + gpg + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + + + diff --git a/sevntu-checks/sevntu-checks.xml b/sevntu-checks/sevntu-checks.xml index c0c99166db..96c0a4edd2 100644 --- a/sevntu-checks/sevntu-checks.xml +++ b/sevntu-checks/sevntu-checks.xml @@ -1,77 +1,75 @@  - + - - - - - - - - + + + + + + + - + - + - - + + - - + + - + - - - + + - + - + - - - - - + + + + + @@ -82,26 +80,30 @@ - + + + + + - - + + - + - - + + - + @@ -109,38 +111,38 @@ - - + + - - + + - + - - + + - + - + - + - - + + @@ -149,23 +151,24 @@ - - - - - - + + + + + + + + - - + - + @@ -176,37 +179,35 @@ - - - + + + - - + + - - - - - + + + + + + - + - - - - + + - + - - + @@ -218,7 +219,7 @@ diff --git a/sevntu-checks/sevntu-suppressions.xml b/sevntu-checks/sevntu-suppressions.xml index cbae892d82..f9d655405f 100644 --- a/sevntu-checks/sevntu-suppressions.xml +++ b/sevntu-checks/sevntu-suppressions.xml @@ -7,4 +7,12 @@ + + + + + + + + \ No newline at end of file diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/Utils.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/Utils.java index eb11c22945..8d7726c4ac 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/Utils.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/Utils.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -29,6 +29,7 @@ * @author Damian Szczepanik */ public final class Utils { + /** Prevent instances. */ private Utils() { } @@ -74,4 +75,5 @@ public static DetailAST getNextSubTreeNode(DetailAST node, DetailAST subTreeRoot } return toVisitAst; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationCheck.java index a1fc4bf525..e98d0bc71a 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -38,6 +38,7 @@ * value="METHOD_DEF,CLASS_DEF"/> </module> * * @author Hidoyatov Victor + * @since 1.12.0 */ public class ForbidAnnotationCheck extends AbstractCheck { @@ -88,8 +89,17 @@ public int[] getDefaultTokens() { } @Override - public void visitToken(DetailAST annotation) { + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override + public void visitToken(DetailAST annotation) { final String annotationName = getAnnotationName(annotation); // first parent - 'MODIFIERS', second parent - annotation's target final DetailAST annotationTarget = annotation.getParent().getParent(); @@ -98,10 +108,9 @@ public void visitToken(DetailAST annotation) { if (isRequiredAnnotationName(annotationName) && isForbiddenAnnotationTarget(targetType)) { - final String currentTarget = annotationTarget.getText(); - log(annotation.getLineNo(), MSG_KEY, + log(annotation, MSG_KEY, currentTarget, annotationName); } } @@ -113,15 +122,18 @@ && isForbiddenAnnotationTarget(targetType)) { * @return The name of the annotation. */ private static String getAnnotationName(DetailAST annotation) { + final String result; final DetailAST directname = annotation.findFirstToken(TokenTypes.IDENT); if (directname != null) { - return directname.getText(); + result = directname.getText(); } else { //This means that annotation is specified with the full package name - return annotation.findFirstToken(TokenTypes.DOT).getLastChild().getText(); + result = annotation.findFirstToken(TokenTypes.DOT).getLastChild().getText(); } + + return result; } /** @@ -130,8 +142,7 @@ private static String getAnnotationName(DetailAST annotation) { * @return boolean */ private boolean isRequiredAnnotationName(String annotationName) { - return annotationName != null - && annotationNames.contains(annotationName); + return annotationNames.contains(annotationName); } /** @@ -142,4 +153,5 @@ private boolean isRequiredAnnotationName(String annotationName) { private boolean isForbiddenAnnotationTarget(int targetType) { return Arrays.binarySearch(annotationTargets, targetType) > -1; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationElementValueCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationElementValueCheck.java index 3747633bbb..09112c5c4a 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationElementValueCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationElementValueCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -86,7 +86,7 @@ * @SuppressWarnings("unchecked") * *

    - * To forbid any array-valued element, frobiddenElementValueRegexp option should be: "\{.*\}". + * To forbid any array-valued element, forbiddenElementValueRegexp option should be: "\{.*\}". *

    *

    * Config @@ -110,8 +110,10 @@ * * @author Sergey Drozd * @author Richard Veach + * @since 1.22.0 */ public class ForbidAnnotationElementValueCheck extends AbstractCheck { + /** Message key. */ public static final String MSG_KEY = "annotation.forbid.element.value"; @@ -165,6 +167,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { if (getAnnotationName(ast).equals(annotationName)) { @@ -322,7 +334,7 @@ private static String getExpressionText(DetailAST expression) { } /** - * Gets String-represented array from provided left brace + * Gets String-represented array from provided left brace. * * @param brace * DetailAST node of type {@link TokenTypes#ANNOTATION_ARRAY_INIT} @@ -386,4 +398,5 @@ private static String getElementName(DetailAST memberValuePair) { final DetailAST elementName = memberValuePair.findFirstToken(TokenTypes.IDENT); return elementName.getText(); } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/RequiredParameterForAnnotationCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/RequiredParameterForAnnotationCheck.java index 02b3533382..219f9adfbc 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/RequiredParameterForAnnotationCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/RequiredParameterForAnnotationCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -95,9 +95,11 @@ * * * @author Andrew Uljanenko + * @since 1.13.0 */ public class RequiredParameterForAnnotationCheck extends AbstractCheck { + /** * Key for error message. */ @@ -145,12 +147,16 @@ public int[] getRequiredTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST annotationNode) { final String annotationNameCheck = getAnnotationName(annotationNode); if (annotationNameCheck.equals(this.annotationName)) { - final Set missingParameters = Sets.difference(requiredParameters, getAnnotationParameters(annotationNode)); diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/package-info.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/package-info.java index 6649775703..b1e3918c31 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/package-info.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/annotation/package-info.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidConstantAsFirstOperandInConditionCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidConstantAsFirstOperandInConditionCheck.java index cd02d115f4..b1fd0ac57d 100755 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidConstantAsFirstOperandInConditionCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidConstantAsFirstOperandInConditionCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -27,17 +27,20 @@ import com.puppycrawl.tools.checkstyle.utils.TokenUtils; /** - * If comparing values, C(C++) developers prefer to put the constant first in the equality check, - * to prevent situations of assignment rather than equality checking. + * Checks that constants do not appear in the first operand of any condition. * *

    - * But in Java, in IF condition it is impossible to use assignment, - * so that habit become unnecessary and do damage readability of code. + * If comparing values, C(C++) developers prefer to put the constant first in the equality check, + * to prevent situations of assignment rather than equality checking. It is easy to write "=" + * instead of "==", and no compile error will be produced but condition will work in a different + * way then intended. However, in Java it is impossible to use assignment inside the + * if condition, so that habit becomes unnecessary and does damage to the readability + * of the code. *

    * *

    - * In C(C++), comparison for null is tricky, and it is easy to write "=" instead of "==", - * and no complication error will be but condition will work in different way + * This check was extended to include all equality checks like ">", ">=", "<", "<=" + * for users who prefer constants always be on the right-hand side for any condition. *

    * *

    @@ -51,8 +54,10 @@ *

    * * @author Sergey Burtsev + * @since 1.9.0 */ public class AvoidConstantAsFirstOperandInConditionCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. @@ -92,13 +97,27 @@ public int[] getDefaultTokens() { return new int[] { TokenTypes.EQUAL, TokenTypes.NOT_EQUAL, + TokenTypes.LT, + TokenTypes.LE, + TokenTypes.GT, + TokenTypes.GE, }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST detailAST) { if (isRefactoringRequired(detailAST)) { - log(detailAST.getLineNo(), MSG_KEY, + log(detailAST, MSG_KEY, detailAST.getText()); } } @@ -117,8 +136,7 @@ private boolean isRefactoringRequired(DetailAST logicNode) { final int constantType = firstOperand.getType(); return isTargetConstantType(constantType) - && firstOperand.branchContains(constantType) - && !secondOperand.branchContains(constantType); + && secondOperand.getType() != firstOperand.getType(); } /** @@ -149,4 +167,5 @@ private static DetailAST[] getBothChildren(DetailAST logicNode) { private boolean isTargetConstantType(int targetType) { return Arrays.binarySearch(targetConstantTypes, targetType) > -1; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidDefaultSerializableInInnerClassesCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidDefaultSerializableInInnerClassesCheck.java index 5cfd82fb2b..058572ffa2 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidDefaultSerializableInInnerClassesCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidDefaultSerializableInInnerClassesCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -33,8 +33,10 @@ * "Effective Java (2nd edition)" chapter 11, item 74, page 294. *

    * @author Ilia Dubinin + * @since 1.8.0 */ public class AvoidDefaultSerializableInInnerClassesCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. @@ -64,6 +66,16 @@ public int[] getDefaultTokens() { return new int[] {TokenTypes.CLASS_DEF }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST detailAST) { final boolean topLevelClass = detailAST.getParent() == null; @@ -72,7 +84,7 @@ public void visitToken(DetailAST detailAST) { && !hasSerialazableMethods(detailAST)) { final DetailAST implementsBlock = detailAST .findFirstToken(TokenTypes.IMPLEMENTS_CLAUSE); - log(implementsBlock.getLineNo(), + log(implementsBlock, MSG_KEY); } } @@ -97,10 +109,9 @@ private static boolean isStatic(DetailAST classNode) { } /** - *

    - * Return true, if inner class contain override method readObject() and - * writeObject(); - *

    + * Return {@code true}, if inner class contain override method {@code readObject()} and + * {@code writeObject()}. + * * @param classNode * the start node of class definition. * @return The boolean value. True, if method was override. @@ -188,9 +199,8 @@ private static boolean hasCorrectParameter(DetailAST methodNode, } /** - *

    - * Return true, if class implement Serializable interface; - *

    + * Return {@code true}, if class implement Serializable interface. + * * @param classDefNode * - the start node for class definition. * @return boolean value. True, if class implements Serializable interface. @@ -218,6 +228,7 @@ private static boolean isSerializable(DetailAST classDefNode) { * */ private final class SiblingIterator { + /** * *Next. @@ -262,5 +273,7 @@ public DetailAST nextSibling() { } return result; } + } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidHidingCauseExceptionCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidHidingCauseExceptionCheck.java index 970933cea9..2b9d316891 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidHidingCauseExceptionCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidHidingCauseExceptionCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -63,8 +63,10 @@ * @author Daniil * Yaroslavtsev * @author Ilja Dubinin + * @since 1.8.0 */ public class AvoidHidingCauseExceptionCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. @@ -79,8 +81,17 @@ public int[] getDefaultTokens() { } @Override - public void visitToken(DetailAST detailAST) { + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + + @Override + public void visitToken(DetailAST detailAST) { final String originExcName = detailAST .findFirstToken(TokenTypes.PARAMETER_DEF).getLastChild() .getText(); @@ -132,7 +143,6 @@ private static boolean isContainsCaughtExc(List throwParamNamesList, private List buildThrowParamNamesList(DetailAST startNode, List paramNamesAST) { for (DetailAST currentNode : getChildNodes(startNode)) { - if (currentNode.getType() == TokenTypes.IDENT) { paramNamesAST.add(currentNode); } @@ -142,7 +152,6 @@ private List buildThrowParamNamesList(DetailAST startNode, && currentNode.getNumberOfChildren() > 0) { buildThrowParamNamesList(currentNode, paramNamesAST); } - } return paramNamesAST; } @@ -156,10 +165,8 @@ private List buildThrowParamNamesList(DetailAST startNode, * @return null-safe list of LITERAL_THROW literals */ private List makeThrowList(DetailAST parentAST) { - final List throwList = new LinkedList<>(); for (DetailAST currentNode : getChildNodes(parentAST)) { - if (currentNode.getType() == TokenTypes.LITERAL_THROW) { throwList.add(currentNode); } @@ -170,7 +177,6 @@ private List makeThrowList(DetailAST parentAST) { && currentNode.getNumberOfChildren() > 0) { throwList.addAll(makeThrowList(currentNode)); } - } return throwList; } @@ -191,11 +197,9 @@ private List makeExceptionsList(DetailAST currentCatchAST, final List wrapExcNames = new LinkedList<>(); for (DetailAST currentNode : getChildNodes(parentAST)) { - if (currentNode.getType() == TokenTypes.IDENT && currentNode.getText().equals(currentExcName) && currentNode.getParent().getType() != TokenTypes.DOT) { - DetailAST temp = currentNode; while (!temp.equals(currentCatchAST) @@ -211,7 +215,9 @@ private List makeExceptionsList(DetailAST currentCatchAST, else { convertedExc = temp.findFirstToken(TokenTypes.IDENT); } - wrapExcNames.add(convertedExc.getText()); + if (convertedExc != null) { + wrapExcNames.add(convertedExc.getText()); + } } } @@ -220,7 +226,6 @@ private List makeExceptionsList(DetailAST currentCatchAST, wrapExcNames.addAll(makeExceptionsList(currentCatchAST, currentNode, currentExcName)); } - } return wrapExcNames; } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidModifiersForTypesCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidModifiersForTypesCheck.java index 4a9b705094..9d19e18dd9 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidModifiersForTypesCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidModifiersForTypesCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -35,9 +35,11 @@ /** *

    * Disallow some set of modifiers for Java types specified by regexp. + *

    *

    * Field modifiers types according to Java Spec: * (https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1) + *

    *
      *
    • Annotation: using the 'forbiddenClassesRegexpAnnotation' option. *
    • final: using the 'forbiddenClassesRegexpFinal' option. @@ -52,16 +54,20 @@ *

      * Example 1: Forbid use of 'static' modifiers for 'ULCComponents' * (http://ulc.canoo.com/ulccommunity/Contributions/Extensions/GoodPractices.html) + *

      * *

      * Never keep instances of ULC classes in static variables (ULCIcons neither!). They cannot be * shared between different sessions. + *

      *

      * So we can disallow "static" modifier for all ULC* components by setting up an * "forbiddenClassesRegexpStatic" option to "ULC.+" regexp String. + *

      * *

      * Configuration: + *

      *
        * <module name="TreeWalker">
        *      <module name="AvoidModifiersForTypesCheck">
      @@ -74,15 +80,17 @@
        * Example 2: Forbid using annotation for fields: (e.g. @Autowired ). This
        * can be done by setting up the "forbiddenClassesRegexpAnnotation" option to "Person" regexp
        * String.
      + * 

      * *

      * Configuration: + *

      *
        * <module name="TreeWalker">
        *      <module name="AvoidModifiersForTypesCheck">
        *          <property name="forbiddenClassesRegexpAnnotation" value="Person"/>
        *      </module>
      - * <module>
      + * </module>
        * 
      * *
      @@ -102,13 +110,16 @@
        * produce logs that are hard to investigate as logging class does not contains that code and search
        * should be done in other classes or in hierarchy (if filed is public or accessible by other
        * protected or package).
      + * 

      *

      * This check can be activated by setting up the "forbiddenClassesRegexpPublic", * "forbiddenClassesRegexpPackagePrivate" and "forbiddenClassesRegexpProtected" options to "Logger" * regexp String. + *

      * *

      * Configuration: + *

      *
        * <module name="TreeWalker">
        *      <module name="AvoidModifiersForTypesCheck">
      @@ -116,7 +127,7 @@
        *          <property name="forbiddenClassesRegexpPublic" value="Logger"/>
        *          <property name="forbiddenClassesRegexpPackagePrivate" value="Logger"/>
        *      <module>
      - * <module>
      + * </module>
        * 
      * *
      @@ -132,9 +143,10 @@
        *
        * }
        * 
      - *

      + * * @author Daniil Yaroslavtsev * @author Yasser Aziza + * @since 1.8.0 */ public class AvoidModifiersForTypesCheck extends AbstractCheck { @@ -384,12 +396,21 @@ public int[] getDefaultTokens() { return new int[] {TokenTypes.VARIABLE_DEF }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { final String classNameAndPath = getClassNameAndPath(ast); if (classNameAndPath != null) { - final String className = getClassName(classNameAndPath); final Set modifiersSet = getModifiers(ast); @@ -516,7 +537,7 @@ private static String getClassName(final String classNameAndPath) { * Gets the modifiers of the defined variable (annotation, public, private, final, static, * transient or volatile). * @param variableDefAst - * A DeatilAST node is related to the variable definition + * A DetailAST node is related to the variable definition * (VARIABLE_DEF type) * @return List of token types is related to the given variable modifiers. */ diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidNotShortCircuitOperatorsForBooleanCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidNotShortCircuitOperatorsForBooleanCheck.java index 489f7d6532..87df5a07e9 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidNotShortCircuitOperatorsForBooleanCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/AvoidNotShortCircuitOperatorsForBooleanCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -69,6 +69,7 @@ *

      * @author Daniil * Yaroslavtsev + * @since 1.8.0 */ public class AvoidNotShortCircuitOperatorsForBooleanCheck extends AbstractCheck { @@ -101,12 +102,25 @@ public final int[] getDefaultTokens() { } @Override - public final void visitToken(final DetailAST detailAST) { + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override + public final void visitToken(final DetailAST detailAST) { DetailAST currentNode = detailAST; // look for EXPR which is always around BOR/BAND... operators while (currentNode != null && currentNode.getType() != TokenTypes.EXPR) { currentNode = currentNode.getParent(); + + if (currentNode.getType() == TokenTypes.PARAMETER_DEF) { + currentNode = null; + } } if (currentNode != null && isBooleanExpression(currentNode)) { @@ -144,7 +158,10 @@ public final boolean isBooleanExpression(final DetailAST node) { while (curNode.getType() != TokenTypes.CTOR_DEF && curNode.getType() != TokenTypes.METHOD_DEF - && curNode.getType() != TokenTypes.CLASS_DEF) { + && curNode.getType() != TokenTypes.CLASS_DEF + && curNode.getType() != TokenTypes.INTERFACE_DEF + && curNode.getType() != TokenTypes.ANNOTATION_DEF + && curNode.getType() != TokenTypes.ENUM_DEF) { curNode = curNode.getParent(); } @@ -152,7 +169,6 @@ public final boolean isBooleanExpression(final DetailAST node) { for (DetailAST currentNode : getChildren(curNode.getLastChild())) { if (currentNode.getLineNo() < line && currentNode.getType() == TokenTypes.VARIABLE_DEF) { - if (isBooleanType(currentNode)) { booleanVariablesNames.add(currentNode.findFirstToken( TokenTypes.IDENT).getText()); @@ -161,7 +177,6 @@ public final boolean isBooleanExpression(final DetailAST node) { } boolean result = false; - for (String name : childNames) { if (booleanVariablesNames.contains(name)) { result = true; @@ -180,9 +195,7 @@ public final boolean isBooleanExpression(final DetailAST node) { */ public final List getSupportedOperandsNames( final DetailAST exprParentAST) { - for (DetailAST currentNode : getChildren(exprParentAST)) { - if (currentNode.getNumberOfChildren() > 0 && currentNode.getType() != TokenTypes.METHOD_CALL) { getSupportedOperandsNames(currentNode); @@ -192,10 +205,6 @@ public final List getSupportedOperandsNames( && currentNode.getParent().getType() != TokenTypes.DOT) { supportedOperands.add(currentNode.getText()); } - - if (currentNode.getNextSibling() != null) { - currentNode = currentNode.getNextSibling(); - } } return supportedOperands; } @@ -208,9 +217,7 @@ public final List getSupportedOperandsNames( * "true" or "false" keywords and false otherwise. */ public final boolean hasTrueOrFalseLiteral(final DetailAST parentAST) { - for (DetailAST currentNode : getChildren(parentAST)) { - if (currentNode.getNumberOfChildren() > 0) { hasTrueOrFalseLiteral(currentNode); } @@ -221,10 +228,6 @@ public final boolean hasTrueOrFalseLiteral(final DetailAST parentAST) { hasTrueOrFalseLiteral = true; } - if (currentNode.getNextSibling() != null) { - currentNode = currentNode.getNextSibling(); - } - if (hasTrueOrFalseLiteral) { break; } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ConfusingConditionCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ConfusingConditionCheck.java index 4f1a893b79..c1dea6c8ba 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ConfusingConditionCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ConfusingConditionCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -48,7 +48,7 @@ * and swapped code in "if" and "else" block: *

      *
      - *  if (a == b && c == d)
      + *  if (a == b || c == d)
        *      {
        *          smth2();
        *      }
      @@ -59,8 +59,10 @@
        * 
      * * @author Vadim Panasiuk + * @since 1.9.0 */ public class ConfusingConditionCheck extends AbstractCheck { + /** * The key is pointing to the message text String in * "messages.properties file".This message used for common cases. @@ -157,6 +159,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST literalIf) { if (isIfEndsWithElse(literalIf) @@ -166,7 +178,7 @@ public void visitToken(DetailAST literalIf) { if (isRatioBetweenIfAndElseBlockSuitable(literalIf) && !(ignoreNullCaseInIf && isIfWithNull(literalIf)) && isConditionAllNegative(literalIf)) { - log(literalIf.getLineNo(), MSG_KEY); + log(literalIf, MSG_KEY); } } } @@ -231,9 +243,9 @@ private boolean isRatioBetweenIfAndElseBlockSuitable(DetailAST literalIf) { boolean result = true; final DetailAST lastChildAfterIf = literalIf.getLastChild(); - final int linesOfCodeInIfBlock = getAmounOfCodeRowsInBlock(literalIf); - final int linesOfCodeInElseBlock = getAmounOfCodeRowsInBlock(lastChildAfterIf); + final int linesOfCodeInElseBlock = getAmountOfCodeRowsInBlock(lastChildAfterIf); if (linesOfCodeInElseBlock > 0) { + final int linesOfCodeInIfBlock = getAmountOfCodeRowsInBlock(literalIf); result = linesOfCodeInIfBlock / linesOfCodeInElseBlock < multiplyFactorForElseBlocks; } return result; @@ -245,23 +257,51 @@ private boolean isRatioBetweenIfAndElseBlockSuitable(DetailAST literalIf) { * @param detailAST The token to examine. * @return linesOfCodeInIfBlock line of code in block. */ - private static int getAmounOfCodeRowsInBlock(DetailAST detailAST) { + private static int getAmountOfCodeRowsInBlock(DetailAST detailAST) { + final DetailAST firstBrace = getFirstBrace(detailAST); + int linesOfCodeInIfBlock; + + if (firstBrace == null) { + linesOfCodeInIfBlock = 0; + } + else { + final DetailAST lastBrace = firstBrace.getLastChild(); + linesOfCodeInIfBlock = lastBrace.getLineNo() + - firstBrace.getLineNo(); + // If the closing brace on a separate line - ignore this line. + if (lastBrace.getLineNo() != lastBrace.getParent().getLineNo()) { + linesOfCodeInIfBlock -= 1; + } + } + + return linesOfCodeInIfBlock; + } + + /** + * Retrieves the first, opening brace of an {@code if} or {@code else} statement. + * @param detailAST The token to examine. + * @return The opening brace token or {@code null} if it doesn't exist. + */ + private static DetailAST getFirstBrace(DetailAST detailAST) { DetailAST firstBrace = null; + if (detailAST.getType() == TokenTypes.LITERAL_ELSE) { firstBrace = detailAST.getFirstChild(); + + if (firstBrace.getType() == TokenTypes.LITERAL_IF) { + firstBrace = getFirstBrace(firstBrace); + } } - else if (detailAST.getType() == TokenTypes.LITERAL_IF) { + else { firstBrace = detailAST.getFirstChild().getNextSibling() .getNextSibling().getNextSibling(); } - final DetailAST lastBrace = firstBrace.getLastChild(); - int linesOfCodeInIfBlock = lastBrace.getLineNo() - - firstBrace.getLineNo(); - // If the closing brace on a separate line - ignore this line. - if (lastBrace.getLineNo() != lastBrace.getParent().getLineNo()) { - linesOfCodeInIfBlock -= 1; + + if (firstBrace != null && firstBrace.getType() != TokenTypes.SLIST) { + firstBrace = null; } - return linesOfCodeInIfBlock; + + return firstBrace; } /** diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/CustomDeclarationOrderCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/CustomDeclarationOrderCheck.java index e95b2e7635..63ef20bd58 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/CustomDeclarationOrderCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/CustomDeclarationOrderCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -32,8 +32,6 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -import org.apache.commons.beanutils.ConversionException; - import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; @@ -42,6 +40,7 @@ *

      * Checks that the parts of a class(main, nested, member inner) declaration * appear in the rules order set by user using regular expressions. + *

      *

      * The check forms line which consists of class member annotations, modifiers, * type and name from your code and compares it with your RegExp. @@ -55,7 +54,7 @@ * insensitive): *

        *
      1. "Field" to denote the Fields
      2. - *
      3. "DeclareAnnonClassField" to denote the fields keeping objects of anonymous classes
      4. + *
      5. "DeclareAnonClassField" to denote the fields keeping objects of anonymous classes
      6. *
      7. "Ctor" to denote the Constructors
      8. *
      9. "Method" to denote the Methods
      10. *
      11. "GetterSetter" to denote the group of getter and setter methods
      12. @@ -116,8 +115,11 @@ *

        * *

        What is group of getters and setters(GetterSetter)?

        + * *

        * It is ordered sequence of getters and setters like: + *

        + * *
          * public int getValue() {
          *     log.info("Getting value");
        @@ -150,8 +152,10 @@
          *
          * @author Danil Lopatin
          * @author Baratali Izmailov
        + * @since 1.8.0
          */
         public class CustomDeclarationOrderCheck extends AbstractCheck {
        +
             /**
              * A key is pointing to the warning message text in "messages.properties"
              * file.
        @@ -194,28 +198,40 @@ public class CustomDeclarationOrderCheck extends AbstractCheck {
              */
             public static final String MSG_KEY_INVALID_SETTER = "custom.declaration.order.invalid.setter";
         
        +    /** Macro string for inner enumeration. */
             private static final String INNER_ENUM_MACRO = "InnerEnum";
         
        +    /** Macro string for inner interface. */
             private static final String INNER_INTERFACE_MACRO = "InnerInterface";
         
        +    /** Macro string for inner class. */
             private static final String INNER_CLASS_MACRO = "InnerClass";
         
        +    /** Macro string for constructor. */
             private static final String CTOR_MACRO = "Ctor";
         
        +    /** Macro string for method. */
             private static final String METHOD_MACRO = "Method";
         
        -    private static final String ANNON_CLASS_FIELD_MACRO = "DeclareAnnonClassField";
        +    /** Macro string for anonymous class field. */
        +    private static final String ANON_CLASS_FIELD_MACRO = "DeclareAnonClassField";
         
        +    /** Macro string for field. */
             private static final String FIELD_MACRO = "Field";
         
        +    /** Macro string for getter and setter. */
             private static final String GETTER_SETTER_MACRO = "GetterSetter";
         
        +    /** Macro string for main method. */
             private static final String MAIN_METHOD_MACRO = "MainMethod";
         
        +    /** Prefix for boolean getter method name. */
             private static final String BOOLEAN_GETTER_PREFIX = "is";
         
        +    /** Prefix for getter method name. */
             private static final String GETTER_PREFIX = "get";
         
        +    /** Prefix for setter method name. */
             private static final String SETTER_PREFIX = "set";
         
             /** Default format for custom declaration check. */
        @@ -335,14 +351,22 @@ else if (currentRule.hasRule(GETTER_SETTER_MACRO)) {
                 return tokenTypes;
             }
         
        +    @Override
        +    public int[] getAcceptableTokens() {
        +        return getDefaultTokens();
        +    }
        +
        +    @Override
        +    public int[] getRequiredTokens() {
        +        return getDefaultTokens();
        +    }
        +
             @Override
             public void visitToken(DetailAST ast) {
                 switch (ast.getType()) {
        -
                     case TokenTypes.CLASS_DEF:
                         if (!isClassDefInMethodDef(ast)) {
                             if (checkInnerClasses && !classDetails.isEmpty()) {
        -
                                 final int position = getPositionInOrderDeclaration(ast);
         
                                 if (position != -1) {
        @@ -363,7 +387,6 @@ public void visitToken(DetailAST ast) {
                         final DetailAST objBlockAst = ast.getParent();
                         if (objBlockAst != null
                             && objBlockAst.getType() == TokenTypes.OBJBLOCK) {
        -
                             final DetailAST classDefAst = objBlockAst.getParent();
         
                             if (classDefAst.getType() == TokenTypes.CLASS_DEF
        @@ -384,7 +407,6 @@ public void visitToken(DetailAST ast) {
                                 }
                             }
                         }
        -
                 }
             }
         
        @@ -392,10 +414,11 @@ public void visitToken(DetailAST ast) {
             public void leaveToken(DetailAST ast) {
                 if (ast.getType() == TokenTypes.CLASS_DEF
                         && !isClassDefInMethodDef(ast)) {
        +            // -@cs[MoveVariableInsideIf] assignment value is a modification
        +            // call so it can't be moved
                     final ClassDetail classDetail = classDetails.pop();
         
                     if (checkGettersSetters) {
        -
                         final Map gettersSetters =
                                 classDetail.getWrongOrderedGettersSetters();
         
        @@ -406,7 +429,7 @@ public void leaveToken(DetailAST ast) {
         
             /**
              * Parse input current declaration rule and create new instance of
        -     * FormatMather with matcher
        +     * FormatMather with matcher.
              *
              * @param currentState input string with MemberDefinition and RegExp.
              * @return new FormatMatcher with parsed and compile rule
        @@ -418,7 +441,7 @@ private FormatMatcher parseInputDeclarationRule(final String currentState) {
                 final int classMember = convertMacroToTokenType(macro);
                 if (classMember == -1) {
                     // if Class Member has been specified wrong
        -            throw new ConversionException("Unable to parse " + macro);
        +            throw new IllegalArgumentException("Unable to parse " + macro);
                 }
         
                 // parse regExp
        @@ -448,7 +471,7 @@ private static int convertMacroToTokenType(
                     String inputMemberName) {
                 int result = -1;
                 if (FIELD_MACRO.equalsIgnoreCase(inputMemberName)
        -                || ANNON_CLASS_FIELD_MACRO.equalsIgnoreCase(inputMemberName)) {
        +                || ANON_CLASS_FIELD_MACRO.equalsIgnoreCase(inputMemberName)) {
                     result = TokenTypes.VARIABLE_DEF;
                 }
                 else if (GETTER_SETTER_MACRO.equalsIgnoreCase(inputMemberName)
        @@ -549,11 +572,10 @@ private boolean isWrongPosition(final int position) {
              */
             private void logWrongOrderedSetters(Map gettersSetters) {
                 for (Entry entry: gettersSetters.entrySet()) {
        -
                     final DetailAST setterAst = entry.getKey();
                     final DetailAST getterAst = entry.getValue();
         
        -            log(setterAst.getLineNo(),
        +            log(setterAst,
                             MSG_KEY_INVALID_SETTER,
                             getIdentifier(setterAst),
                             getIdentifier(getterAst));
        @@ -600,10 +622,9 @@ private int getPositionInOrderDeclaration(final DetailAST ast) {
                     final FormatMatcher currentRule = customOrderDeclaration.get(index);
                     if (currentRule.getClassMember() == ast.getType()
                             && currentRule.getRegexp().matcher(modifiers).find()) {
        -                if (currentRule.hasRule(ANNON_CLASS_FIELD_MACRO)
        +                if (currentRule.hasRule(ANON_CLASS_FIELD_MACRO)
                                 || currentRule.hasRule(GETTER_SETTER_MACRO)
                                 || currentRule.hasRule(MAIN_METHOD_MACRO)) {
        -
                             final String methodName = getIdentifier(ast);
                             final ClassDetail classDetail = classDetails.peek();
         
        @@ -689,14 +710,10 @@ private static boolean isSetterName(String methodName) {
             private boolean isGetterCorrect(DetailAST methodDef, String methodPrefix) {
                 boolean result = false;
         
        -        final String methodName = getIdentifier(methodDef);
        -        final String methodNameWithoutPrefix = getNameWithoutPrefix(methodName, methodPrefix);
        -
                 final DetailAST parameters = methodDef.findFirstToken(TokenTypes.PARAMETERS);
         
                 // no parameters
                 if (parameters.getChildCount() == 0) {
        -
                     final DetailAST statementsAst = methodDef.findFirstToken(TokenTypes.SLIST);
                     if (statementsAst != null) {
                         final DetailAST returnStatementAst = statementsAst
        @@ -705,6 +722,9 @@ private boolean isGetterCorrect(DetailAST methodDef, String methodPrefix) {
                         if (returnStatementAst != null) {
                             final DetailAST exprAst = returnStatementAst.getFirstChild();
                             final String returnedFieldName = getNameOfGetterField(exprAst);
        +                    final String methodName = getIdentifier(methodDef);
        +                    final String methodNameWithoutPrefix = getNameWithoutPrefix(methodName,
        +                            methodPrefix);
                             if (returnedFieldName != null
                                     && !localVariableHidesField(statementsAst, returnedFieldName)
                                     && verifyFieldAndMethodName(returnedFieldName,
        @@ -750,15 +770,13 @@ private static boolean localVariableHidesField(DetailAST slist,
             private boolean isSetterCorrect(DetailAST methodDefAst, String methodPrefix) {
                 boolean result = false;
         
        -        final String methodName = getIdentifier(methodDefAst);
        -        final String setterFieldName = fieldPrefix
        -                + getNameWithoutPrefix(methodName, methodPrefix);
        -
                 final DetailAST methodTypeAst = methodDefAst.findFirstToken(TokenTypes.TYPE);
         
        -        if (methodTypeAst.branchContains(TokenTypes.LITERAL_VOID)) {
        -
        +        if (methodTypeAst.findFirstToken(TokenTypes.LITERAL_VOID) != null) {
                     final DetailAST statementsAst = methodDefAst.findFirstToken(TokenTypes.SLIST);
        +            final String methodName = getIdentifier(methodDefAst);
        +            final String setterFieldName = fieldPrefix
        +                    + getNameWithoutPrefix(methodName, methodPrefix);
         
                     result = statementsAst != null
                             && !localVariableHidesField(statementsAst, setterFieldName)
        @@ -801,7 +819,7 @@ private static String getCombinedModifiersList(final DetailAST ast) {
                 }
         
                 while (astNode.getType() != TokenTypes.IDENT) {
        -            if (astNode != null && astNode.getFirstChild() != null) {
        +            if (astNode.getFirstChild() != null) {
                         modifiers.append(getModifiersAsText(astNode.getFirstChild()));
                         modifiers.append(" ");
                     }
        @@ -868,11 +886,12 @@ private static String getNameWithoutPrefix(String name, String prefix) {
              * @return identifier of AST, null if AST does not have name.
              */
             private static String getIdentifier(final DetailAST ast) {
        +        String result = null;
                 final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
                 if (ident != null) {
        -            return ident.getText();
        +            result = ident.getText();
                 }
        -        return null;
        +        return result;
             }
         
             /**
        @@ -886,7 +905,6 @@ private static boolean isFieldUpdate(DetailAST statementsAst, String fieldName)
                 DetailAST currentStatement = statementsAst.getFirstChild();
         
                 while (currentStatement != null && currentStatement != statementsAst) {
        -
                     String nameOfSetterField = null;
                     if (currentStatement.getType() == TokenTypes.ASSIGN) {
                         nameOfSetterField = getNameOfAssignedField(currentStatement);
        @@ -928,7 +946,6 @@ private static String getNameOfAssignedField(DetailAST assignAst) {
                 if (assignAst.getChildCount() > 0
                                 && (assignAst.getLastChild().getType() == TokenTypes.IDENT
                                 || assignAst.getLastChild().getType() == TokenTypes.METHOD_CALL)) {
        -
                     final DetailAST methodCallDot = assignAst.getFirstChild();
                     if (methodCallDot.getChildCount() == 2
                         && "this".equals(methodCallDot.getFirstChild().getText())) {
        @@ -960,9 +977,8 @@ private static String getNameOfSuperClassUpdatedField(DetailAST methodCallAst) {
             }
         
             /**
        -     * 

        - * Gets name of the field, that was used in calling setter from a super class - *

        + * Gets name of the field, that was used in calling setter from a super class. + * * @param methodCallDotAst The token to examine. * @return * name of field in method parameter. @@ -1007,9 +1023,7 @@ private static String getNameOfGetterField(DetailAST expr) { final DetailAST exprFirstChild = expr.getFirstChild(); if (exprFirstChild.getType() == TokenTypes.IDENT) { - nameOfGetterField = exprFirstChild.getText(); - } else if (exprFirstChild.getType() == TokenTypes.DOT && exprFirstChild.getChildCount() == 2 @@ -1068,9 +1082,8 @@ private static boolean isMainMethodModifiers(final DetailAST methodAST) { */ private static boolean isVoidType(final DetailAST methodAST) { boolean result = true; - DetailAST methodTypeAST = null; if (hasChildToken(methodAST, TokenTypes.TYPE)) { - methodTypeAST = methodAST.findFirstToken(TokenTypes.TYPE); + final DetailAST methodTypeAST = methodAST.findFirstToken(TokenTypes.TYPE); result = hasChildToken(methodTypeAST, TokenTypes.LITERAL_VOID); } return result; @@ -1169,6 +1182,7 @@ private static boolean hasChildToken(DetailAST ast, int tokenType) { * Private class for members of class and their patterns. */ private static final class FormatMatcher { + /** The regexp to match against. */ private Pattern regExp; /** The Member of Class. */ @@ -1235,7 +1249,7 @@ private void updateRegexp(final String newFormat, final int compileFlags) { this.format = newFormat; } catch (final PatternSyntaxException ex) { - throw new ConversionException("unable to parse " + newFormat, ex); + throw new IllegalArgumentException("unable to parse " + newFormat, ex); } } @@ -1252,12 +1266,14 @@ public boolean hasRule(String ruleCheck) { public String toString() { return rule; } + } /** * Class to keep current position and collect getters, setters. */ private static class ClassDetail { + /** * Current position in custom order declaration. */ @@ -1319,13 +1335,12 @@ public Map getWrongOrderedGettersSetters() { /** * Compare order of getters and setters. Order should be like "getX; setX; getY; setY; ...". * If it is wrong order, then wrong ordered setters and getters will be returned as map. - * @param allGettersSetters collection of all gettter and setters + * @param allGettersSetters collection of all getter and setters * @param index index from upper loo * @return Map with setter AST as key and getter AST as value. */ private static Map getWrongOrderedGettersSetters( List allGettersSetters, int index) { - final DetailAST getterAst = allGettersSetters.get(index); final String getterName = getIdentifier(getterAst); String getterField = null; @@ -1345,9 +1360,8 @@ else if (isBooleanGetterName(getterName)) { // method is NOT getter final DetailAST setterAst = allGettersSetters.get(j); final String setterName = getIdentifier(setterAst); - String setterField = null; if (isSetterName(setterName)) { - setterField = getNameWithoutPrefix( + final String setterField = getNameWithoutPrefix( getIdentifier(setterAst), SETTER_PREFIX); // if fields are same and setter is sibling with getter @@ -1394,6 +1408,7 @@ private boolean containsSetter(String methodName) { } return result; } + } } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/DiamondOperatorForVariableDefinitionCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/DiamondOperatorForVariableDefinitionCheck.java index 78339c8fea..c92a6906dc 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/DiamondOperatorForVariableDefinitionCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/DiamondOperatorForVariableDefinitionCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -41,6 +41,7 @@ * *

        * @author Aleksey Nesterenko + * @since 1.12.0 */ public class DiamondOperatorForVariableDefinitionCheck extends AbstractCheck { @@ -53,17 +54,24 @@ public int[] getDefaultTokens() { } @Override - public void visitToken(DetailAST variableDefNode) { + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override + public void visitToken(DetailAST variableDefNode) { final DetailAST assignNode = variableDefNode.findFirstToken(TokenTypes.ASSIGN); if (assignNode != null) { - final DetailAST newNode = assignNode.getFirstChild().getFirstChild(); // we check only creation by NEW if (newNode.getType() == TokenTypes.LITERAL_NEW) { - final DetailAST variableDefNodeType = variableDefNode.findFirstToken(TokenTypes.TYPE); final DetailAST varDefArguments = getFirstTypeArgumentsToken(variableDefNodeType); @@ -73,7 +81,6 @@ public void visitToken(DetailAST variableDefNode) { && newNode.getLastChild().getType() != TokenTypes.OBJBLOCK // arrays can not be generics && newNode.findFirstToken(TokenTypes.ARRAY_DECLARATOR) == null) { - final DetailAST typeArgs = getFirstTypeArgumentsToken(newNode); if (varDefArguments.equalsTree(typeArgs)) { @@ -96,12 +103,10 @@ private static DetailAST getFirstTypeArgumentsToken(DetailAST rootToken) { if (resultNode.getType() == TokenTypes.DOT) { resultNode = resultNode.getFirstChild().getNextSibling(); } - if (resultNode.getType() != TokenTypes.TYPE_ARGUMENTS) { - final DetailAST childNode = getFirstTypeArgumentsToken(resultNode); + final DetailAST childNode = getFirstTypeArgumentsToken(resultNode); - if (childNode == null) { - resultNode = resultNode.getNextSibling(); - } + if (childNode == null) { + resultNode = resultNode.getNextSibling(); } } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/EitherLogOrThrowCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/EitherLogOrThrowCheck.java index 2e6e402957..f44c4c50c9 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/EitherLogOrThrowCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/EitherLogOrThrowCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -41,6 +41,7 @@ *

        *

        * Examples: + *

        * *
          * catch (NoSuchMethodException e) {
        @@ -70,6 +71,7 @@
          * 

        * What check can detect:
        * Loggers + *

        *
          *
        • logger is declared as class field
        • *
        • logger is declared as method's local variable
        • @@ -86,6 +88,7 @@ *
        *

        * What check can not detect:
        + *

        *
          *
        • loggers that is used like method's return value. Example: * @@ -103,6 +106,7 @@ *
        *

        * Default parameters are: + *

        *
          *
        • loggerFullyQualifiedClassName - fully qualified class name of * logger type. Default value is "org.slf4j.Logger".
        • @@ -114,8 +118,10 @@ * different loggers, then create another instance of this check. *

          * @author Baratali Izmailov + * @since 1.9.0 */ public class EitherLogOrThrowCheck extends AbstractCheck { + /** * Key for error message. */ @@ -204,6 +210,16 @@ public int[] getDefaultTokens() { TokenTypes.METHOD_DEF, }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(final DetailAST ast) { switch (ast.getType()) { @@ -246,6 +262,7 @@ && isLoggerVariableDefinition(ast)) { } /** + * Checks if AST object is logger import. * @param importAst * DetailAST of import statement. * @return true if import equals logger full class name. @@ -333,7 +350,7 @@ && isLoggerVariableDefinition(variableDefAst)) { */ private void processCatchNode(final DetailAST catchAst) { boolean isLoggingExceptionFound = false; - int loggingExceptionLineNumber = 0; + DetailAST loggingExceptionAst = null; final List exceptionVariableNames = new LinkedList<>(); final String catchParameterName = getCatchParameterName(catchAst); final DetailAST statementsAst = @@ -365,7 +382,7 @@ && isInstanceCreationBasedOnException( && (isLoggingExceptionArgument(currentStatementAst, catchParameterName) || isPrintStackTrace(currentStatementAst, catchParameterName))) { isLoggingExceptionFound = true; - loggingExceptionLineNumber = currentStatementAst.getLineNo(); + loggingExceptionAst = currentStatementAst; } break; // throw exception @@ -377,7 +394,7 @@ && isInstanceCreationBasedOnException( if (exceptionVariableNames.contains(getIdentifier(thrownExceptionAst)) || isInstanceCreationBasedOnException( thrownExceptionAst, catchParameterName)) { - log(loggingExceptionLineNumber, MSG_KEY); + log(loggingExceptionAst, MSG_KEY); break; } } @@ -567,11 +584,11 @@ private static boolean isPrintStackTrace(final DetailAST expressionAst, /** * Verify that method is invoked on aUsedInstanceName. - * @param usedInstanseName name of instance. + * @param usedInstanceName name of instance. * @param methodCallAst DetailAST of METHOD_CALL. * @return true if method is invoked on aUsedInstanceName. */ - private static boolean isInstanceMethodCall(final String usedInstanseName, + private static boolean isInstanceMethodCall(final String usedInstanceName, final DetailAST methodCallAst) { boolean result = false; if (methodCallAst != null @@ -582,7 +599,7 @@ private static boolean isInstanceMethodCall(final String usedInstanseName, if (firstDotIndex != -1) { final String usedObjectName = methodCallIdent.substring(0, firstDotIndex); - if (usedObjectName.equals(usedInstanseName)) { + if (usedObjectName.equals(usedInstanceName)) { result = true; } } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/EmptyPublicCtorInClassCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/EmptyPublicCtorInClassCheck.java index 6cc4c4f67a..4e7c0ce04c 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/EmptyPublicCtorInClassCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/EmptyPublicCtorInClassCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -37,6 +37,7 @@ *

          *

          * Example 1. Check will generate violation for this code: + *

          * *
            * class Dummy {
          @@ -47,6 +48,7 @@
            *
            * 

          * Example 2. Check will not generate violation for this code: + *

          * *
            * class Dummy {
          @@ -55,9 +57,12 @@
            * }
            * 
          * + *

          * class Dummy has only one ctor, which is not public. + *

          *

          * Example 3. Check will not generate violation for this code: + *

          * *
            * class Dummy {
          @@ -68,7 +73,9 @@
            * }
            * 
          * + *

          * class Dummy has multiple ctors. + *

          *

          * Check has two properties: *

          @@ -94,8 +101,10 @@ *
          * * @author Zuy Alexey + * @since 1.13.0 */ public class EmptyPublicCtorInClassCheck extends AbstractCheck { + /** * Violation message key. */ @@ -166,6 +175,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void beginTree(DetailAST aRootNode) { singleTypeImports.clear(); @@ -176,7 +195,6 @@ public void beginTree(DetailAST aRootNode) { @Override public void visitToken(DetailAST node) { switch (node.getType()) { - case TokenTypes.IMPORT: final String packageMemberName = getIdentifierName(node); @@ -223,7 +241,7 @@ private static int getClassCtorCount(DetailAST classDefNode) { } /** - * Gets first constructor defininition for class. + * Gets first constructor definition for class. * @param classDefNode * a class definition node. * @return first ctor definition node for class or null if class has no ctor. @@ -408,15 +426,18 @@ private static boolean isOnDemandImport(String importTargetName) { */ private static String joinSingleTypeImportWithIdentifier(String importEntry, String identifierName) { + final String result; final String importEntryLastPart = getSimpleIdentifierNameFromQualifiedName(importEntry); final String annotationNameFirstPart = getQualifiedNameFirstPart(identifierName); if (importEntryLastPart.equals(annotationNameFirstPart)) { - return importEntry + identifierName.substring(annotationNameFirstPart.length()); + result = importEntry + identifierName.substring(annotationNameFirstPart.length()); } else { - return null; + result = null; } + + return result; } /** @@ -465,14 +486,17 @@ private static boolean isOnDemandImport(String importTargetName) { * argument. */ private static String getQualifiedNameFirstPart(String canonicalName) { + final String result; final int firstDotIndex = canonicalName.indexOf('.'); if (firstDotIndex == -1) { - return canonicalName; + result = canonicalName; } else { - return canonicalName.substring(0, firstDotIndex); + result = canonicalName.substring(0, firstDotIndex); } + + return result; } /** @@ -521,4 +545,5 @@ private static String getIdentifierName(DetailAST identifierNode) { return result; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/FinalizeImplementationCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/FinalizeImplementationCheck.java index c7f1802080..9b48a037a3 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/FinalizeImplementationCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/FinalizeImplementationCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -24,6 +24,7 @@ import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** + * Validates finalize method implementation. *

          * This Check detects 3 most common cases of incorrect finalize() method implementation: *

          @@ -50,7 +51,7 @@ * }
        * * @author Max Vetrenko - * + * @since 1.11.0 */ public class FinalizeImplementationCheck extends AbstractCheck { @@ -92,14 +93,23 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST methodDefToken) { if (isFinalizeMethodSignature(methodDefToken)) { - final String warningMessage = validateFinalizeMethod(methodDefToken); if (warningMessage != null) { - log(methodDefToken.getLineNo(), warningMessage); + log(methodDefToken, warningMessage); } } } @@ -124,7 +134,6 @@ private static String validateFinalizeMethod(DetailAST finalizeMethodToken) { else { warningMessage = MSG_KEY_MISSED_TRY_FINALLY; } - } else { final DetailAST literalFinally = literalTry @@ -135,7 +144,6 @@ private static String validateFinalizeMethod(DetailAST finalizeMethodToken) { warningMessage = MSG_KEY_MISSED_SUPER_FINALIZE_CALL; } } - } else { warningMessage = MSG_KEY_PUBLIC_FINALIZE; @@ -160,7 +168,7 @@ && isFinalizeMethodName(methodDefToken) && isVoid(methodDefToken) * @param modifierType * modifier type. * @param methodToken - * MODIFIRES Token. + * MODIFIERS Token. * @return true, if finalize() has "protected" access modifier. */ private static boolean hasModifier(int modifierType, DetailAST methodToken) { @@ -207,13 +215,16 @@ private static int getParamsCount(DetailAST methodDefToken) { * @return true, if method has super.finalize() call. */ private static boolean containsSuperFinalizeCall(DetailAST openingBrace) { + boolean result = false; final DetailAST methodCallToken = openingBrace.getFirstChild().getFirstChild(); - if (methodCallToken != null) { + if (methodCallToken != null && methodCallToken.getType() == TokenTypes.METHOD_CALL) { final DetailAST dotToken = methodCallToken.getFirstChild(); - if (dotToken.findFirstToken(TokenTypes.LITERAL_SUPER) != null) { - return true; + if (dotToken.getType() == TokenTypes.DOT + && dotToken.findFirstToken(TokenTypes.LITERAL_SUPER) != null) { + result = true; } } - return false; + return result; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCCommentsInMethodsCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCCommentsInMethodsCheck.java index 8a92114b3f..6a9b1b8c05 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCCommentsInMethodsCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCCommentsInMethodsCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,7 +19,8 @@ package com.github.sevntu.checkstyle.checks.coding; -import java.util.Set; +import java.util.ArrayDeque; +import java.util.Deque; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; @@ -31,47 +32,81 @@ * class declaration into the method body you will get an error. *

        * @author Ilia Dubinin + * @since 1.6.0 */ public class ForbidCCommentsInMethodsCheck extends AbstractCheck { + /** * Warning message key. */ public static final String MSG_KEY = "forbid.c.comments.in.the.method.body"; - /** - * Set contains C style comments from current file. - */ - private Set clangComments; + /** AST to use for null checks because {@link Deque} doesn't allow null elements. */ + private static final DetailAST NULL_AST = new DetailAST(); + + /** Method stack. */ + private final Deque scopeStack = new ArrayDeque<>(); + + /** Reference to current method. */ + private DetailAST methodAst; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.METHOD_DEF, + TokenTypes.OBJBLOCK, + TokenTypes.BLOCK_COMMENT_BEGIN, }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + + @Override + public boolean isCommentNodesRequired() { + return true; + } + @Override public void beginTree(DetailAST rootAST) { - clangComments = getFileContents().getCComments().keySet(); + methodAst = NULL_AST; } @Override - public void visitToken(DetailAST methodNode) { - if (!clangComments.isEmpty()) { - final DetailAST borders = - methodNode.findFirstToken(TokenTypes.SLIST); - //Could be null when aMethodNode doesn't have body - //(into interface for example) - if (borders != null) { - final int methodBodyBegin = borders.getLineNo(); - final int methodBodyEnd = borders.getLastChild().getLineNo(); - for (final int commentLineNo : clangComments) { - if (commentLineNo > methodBodyBegin - && commentLineNo < methodBodyEnd) { - log(commentLineNo, MSG_KEY); + public void visitToken(DetailAST ast) { + scopeStack.push(methodAst); + + switch (ast.getType()) { + case TokenTypes.METHOD_DEF: + methodAst = ast; + break; + case TokenTypes.OBJBLOCK: + methodAst = NULL_AST; + break; + default: + if (methodAst != NULL_AST) { + final DetailAST lcurly = methodAst.findFirstToken(TokenTypes.SLIST); + if (lcurly != null + && (ast.getLineNo() > lcurly.getLineNo() + || ast.getLineNo() == lcurly.getLineNo() + && ast.getColumnNo() > lcurly.getColumnNo())) { + log(ast, MSG_KEY); } } - } + break; } } + + @Override + public void leaveToken(DetailAST ast) { + methodAst = scopeStack.pop(); + } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainImportsCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainImportsCheck.java index 79eddd1e9f..97a64abb47 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainImportsCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainImportsCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -56,6 +56,7 @@ *

        * @author Daniil * Yaroslavtsev + * @since 1.8.0 */ public class ForbidCertainImportsCheck extends AbstractCheck { @@ -117,14 +118,6 @@ public void setForbiddenImportsRegexp(String forbiddenImportsRegexp) { } } - /** - * Gets the regexp for excluding imports from checking. - * @return regexp for excluding imports from checking. - */ - public String getForbiddenImportsExcludesRegexp() { - return forbiddenImportsExcludesRegexp.toString(); - } - /** * Sets the regexp for excluding imports from checking. * @param forbiddenImportsExcludesRegexp @@ -140,16 +133,26 @@ public void setForbiddenImportsExcludesRegexp(String @Override public int[] getDefaultTokens() { - final int[] defaultTokens; - if (packageNamesRegexp == null || forbiddenImportsRegexp == null - || forbiddenImportsExcludesRegexp == null) { - defaultTokens = new int[] {}; - } - else { - defaultTokens = new int[] {TokenTypes.PACKAGE_DEF, - TokenTypes.IMPORT, TokenTypes.LITERAL_NEW, }; - } - return defaultTokens; + return new int[] { + TokenTypes.PACKAGE_DEF, + TokenTypes.IMPORT, + TokenTypes.LITERAL_NEW, + }; + } + + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + + @Override + public void beginTree(DetailAST rootAST) { + packageMatches = false; } @Override @@ -163,22 +166,16 @@ public void visitToken(DetailAST ast) { } break; case TokenTypes.IMPORT: - if (packageMatches && forbiddenImportsRegexp != null - && forbiddenImportsExcludesRegexp != null) { - final String importQualifiedText = getText(ast); - if (isImportForbidden(importQualifiedText)) { - log(ast, importQualifiedText); - } + final String importQualifiedText = getText(ast); + if (isImportForbidden(importQualifiedText)) { + log(ast, importQualifiedText); } break; case TokenTypes.LITERAL_NEW: - if (forbiddenImportsRegexp != null - && forbiddenImportsExcludesRegexp != null - && packageMatches - && ast.findFirstToken(TokenTypes.DOT) != null) { - final String importQualifiedText = getText(ast); - if (isImportForbidden(importQualifiedText)) { - log(ast, importQualifiedText); + if (ast.findFirstToken(TokenTypes.DOT) != null) { + final String classQualifiedText = getText(ast); + if (isImportForbidden(classQualifiedText)) { + log(ast, classQualifiedText); } } break; @@ -195,8 +192,11 @@ public void visitToken(DetailAST ast) { * classes package, false otherwise */ private boolean isImportForbidden(String importText) { - return forbiddenImportsRegexp.matcher(importText).matches() - && !forbiddenImportsExcludesRegexp.matcher(importText).matches(); + return packageMatches + && forbiddenImportsRegexp != null + && forbiddenImportsRegexp.matcher(importText).matches() + && (forbiddenImportsExcludesRegexp == null + || !forbiddenImportsExcludesRegexp.matcher(importText).matches()); } /** @@ -207,7 +207,7 @@ private boolean isImportForbidden(String importText) { * import to be warned. */ private void log(DetailAST nodeToWarn, String importText) { - log(nodeToWarn.getLineNo(), MSG_KEY, + log(nodeToWarn, MSG_KEY, getForbiddenImportRegexp(), importText); } @@ -226,12 +226,10 @@ private static String getText(DetailAST packageDefOrImportNode) { if (identNode == null) { final DetailAST parentDotAST = packageDefOrImportNode.findFirstToken(TokenTypes.DOT); - if (parentDotAST != null) { - final FullIdent dottedPathIdent = FullIdent - .createFullIdentBelow(parentDotAST); - final DetailAST nameAST = parentDotAST.getLastChild(); - result = dottedPathIdent.getText() + "." + nameAST.getText(); - } + final FullIdent dottedPathIdent = FullIdent + .createFullIdentBelow(parentDotAST); + final DetailAST nameAST = parentDotAST.getLastChild(); + result = dottedPathIdent.getText() + "." + nameAST.getText(); } else { result = identNode.getText(); diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainMethodCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainMethodCheck.java new file mode 100644 index 0000000000..b45e81586d --- /dev/null +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainMethodCheck.java @@ -0,0 +1,277 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.coding; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.github.sevntu.checkstyle.Utils; +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; + +/** + * Check that forbidden method is not used. We can forbid a method by method name and number of + * arguments. + * This can be used to enforce things like: + *
          + *
        • exit() method of System class should not be called.
        • + *
        • assertTrue() and assertFalse() methods of Assert class have a 1 arg variant that does not + * provide a helpful message on failure. These methods should not be used. + *
        + * Parameters are: + *
          + *
        • methodName - Regex to match name of the method to be forbidden. + * When blank or unspecified, all the methods are allowed.
        • + *
        • argumentCount - Number or range to match number of arguments the method takes. + * Multiple numbers/ranges must be comma separated. When unspecified, defaults to "0-". + *
        + * + *

        An example configuration: + *

        + * <module name="ForbidCertainMethodCheck">
        + *    <property name="methodName" value="exit"/>
        + * </module>
        + * <module name="ForbidCertainMethodCheck">
        + *    <property name="methodName" value="assert(True|False)"/>
        + *    <property name="argumentCount" value="1"/>
        + * </module>
        + * <module name="ForbidCertainMethodCheck">
        + *    <property name="methodName" value="assertEquals"/>
        + *    <property name="argumentCount" value="2"/>
        + * </module>
        + * 
        + * Argument count can be bounded range (e.g.: {@code 2-4}) or unbounded range + * (e.g.: {@code -5, 6-}). Unbounded range can be unbounded only on one side. + * Multiple ranges must be comma separated. + * For example, the following will allow only 4 and 8 arguments. + * + *
        + * <module name="ForbidCertainMethodCheck">
        + *    <property name="methodName" value="asList"/>
        + *    <property name="argumentCount" value="-3, 5-7, 9-"/>
        + * </module>
        + * 
        + * + *

        + * Note: The check only matches method name. Matching on class/object of the + * method is not done. For e.g. there is no way to forbid only "System.exit()". You can match + * by methodName="exit", but beware that it will violate "System.exit()" and "MySystem.exit()", + * so use it with caution. + *

        + * + * @author Raghav Kumar Gautam + * @since 1.28.0 + */ +public class ForbidCertainMethodCheck extends AbstractCheck { + + /** Key is pointing to the warning message text in "messages.properties" file. */ + public static final String MSG_KEY = "forbid.certain.method"; + /** Regex for splitting string on comma. */ + private static final Pattern COMMA_REGEX = Pattern.compile(","); + + /** Name of the method. */ + private Pattern methodName = CommonUtils.createPattern("^$"); + + /** Range for number of arguments. */ + private String argumentCount = "0-"; + /** Range objects for matching number of arguments. */ + private final List argumentCountRanges = new ArrayList<>( + Collections.singletonList(new IntRange(0, Integer.MAX_VALUE))); + + /** + * Set method name regex for the forbidden method. + * @param methodName regex for the method name + */ + public void setMethodName(String methodName) { + this.methodName = CommonUtils.createPattern(methodName); + } + + /** + * Set number or range to match number of arguments of the forbidden method. + * Multiple values must be comma separated. + * @param argumentCount range for matching number of arguments + * @throws CheckstyleException when argumentCount is not a valid range + */ + public void setArgumentCount(String argumentCount) throws CheckstyleException { + this.argumentCount = argumentCount; + if (argumentCount.trim().length() > 0) { + final String[] rangeTokens = COMMA_REGEX.split(argumentCount); + argumentCountRanges.clear(); + for (String oneToken : rangeTokens) { + argumentCountRanges.add(IntRange.from(oneToken)); + } + } + else { + throw new CheckstyleException( + "argumentCount must be non-empty, found: " + argumentCount); + } + } + + @Override + public int[] getDefaultTokens() { + return getRequiredTokens(); + } + + @Override + public int[] getAcceptableTokens() { + return getRequiredTokens(); + } + + @Override + public int[] getRequiredTokens() { + return new int[] { + TokenTypes.METHOD_CALL, + }; + } + + @Override + public void visitToken(DetailAST ast) { + switch (ast.getType()) { + case TokenTypes.METHOD_CALL: + final DetailAST dot = ast.getFirstChild(); + // method that looks like: method() + final String methodNameInCode; + if (dot.getType() == TokenTypes.IDENT) { + methodNameInCode = dot.getText(); + } + // method that looks like: obj.method() + else { + methodNameInCode = dot.getLastChild().getText(); + } + final int numArgsInCode = dot.getNextSibling().getChildCount(TokenTypes.EXPR); + if (isForbiddenMethod(methodNameInCode, numArgsInCode)) { + log(ast, MSG_KEY, methodNameInCode, methodName, + numArgsInCode, argumentCount); + } + break; + default: + Utils.reportInvalidToken(ast.getType()); + break; + } + } + + /** + * Check if the method/constructor call against defined rules. + * @param name ruleName of the the method + * @param argCount number of arguments of the method + * @return true if method name and argument matches, false otherwise. + */ + private boolean isForbiddenMethod(String name, int argCount) { + boolean matched = false; + if (methodName.matcher(name).matches()) { + for (IntRange intRange : argumentCountRanges) { + if (intRange.contains(argCount)) { + matched = true; + break; + } + } + } + return matched; + } + + /** + * Represents a range of non-negative integers. + * Range must be bounded on one side or both sides. + * It can't be unbounded on both side. + *
        + * Some examples of valid ranges: + *
          + *
        • 1-10: 1 and 10 and all numbers between 1 and 10
        • + *
        • -10: same as 0-10
        • + *
        • 5-: same as 5-infinity
        • + *
        • 1: same as 1-1
        • + *
        + */ + static class IntRange { + /** Regex for matching range. */ + private static final Pattern RANGE_PATTERN = + Pattern.compile("^\\s*+(\\d*+)\\s*+-\\s*+(\\d*+)\\s*+$"); + /** Lower limit of the range. No lower limit when null. */ + private final int lowerLimit; + /** Upper limit of the range. No upper limit when null. */ + private final int upperLimit; + + /** + * Initialize IntRange object with a lower limit and an upper limit. + * @param lowerLimit lower limit of the range, must be >= 0, null is equivalent to 0 + * @param upperLimit upper limit of the range, null is equivalent to infinity + */ + IntRange(int lowerLimit, int upperLimit) { + this.lowerLimit = lowerLimit; + this.upperLimit = upperLimit; + } + + /** + * Create a range object corresponding to it string representation. + * @param range string representation of the range + * @return IntRange object for the string + * + * @throws CheckstyleException if the specified range is not valid + */ + static IntRange from(String range) throws CheckstyleException { + int lowerLimit = 0; + int upperLimit = Integer.MAX_VALUE; + if (!range.contains("-")) { + lowerLimit = Integer.parseInt(range.trim()); + upperLimit = lowerLimit; + } + else { + final Matcher matcher = RANGE_PATTERN.matcher(range); + if (!matcher.find()) { + throw new CheckstyleException("Specified range is not valid: " + range); + } + final String lowerLimitString = matcher.group(1); + final String upperLimitString = matcher.group(2); + if (lowerLimitString.length() == 0 && upperLimitString.length() == 0) { + throw new CheckstyleException("Specified range is unbounded on both side: " + + range); + } + if (lowerLimitString.length() > 0) { + lowerLimit = Integer.parseInt(lowerLimitString); + } + if (upperLimitString.length() > 0) { + upperLimit = Integer.parseInt(upperLimitString); + } + if (lowerLimit > upperLimit) { + throw new CheckstyleException( + "Lower limit of the range is larger than the upper limit: " + range); + } + } + return new IntRange(lowerLimit, upperLimit); + } + + /** + * Check if range contain given number. Range is closed. + * If lower/upper bound is absent, it is considered unbounded on lower/upper side. + * @param num the number to be checked + * @return true if number is contained in the range, false otherwise + */ + public boolean contains(int num) { + return num >= lowerLimit && num <= upperLimit; + } + } + +} diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidInstantiationCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidInstantiationCheck.java index 228a26b5b3..82eb3766e6 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidInstantiationCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidInstantiationCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -42,6 +42,7 @@ *

        * @author Daniil * Yaroslavtsev + * @since 1.8.0 */ public class ForbidInstantiationCheck extends AbstractCheck { @@ -99,10 +100,19 @@ public int[] getDefaultTokens() { return new int[] {TokenTypes.IMPORT, TokenTypes.LITERAL_NEW }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { switch (ast.getType()) { - case TokenTypes.IMPORT: importsList.add(getText(ast)); break; @@ -117,7 +127,6 @@ public void visitToken(DetailAST ast) { final String instanceClassName = getClassName(instanceClass); for (String forbiddenClass : forbiddenClasses) { - if (forbiddenClass.startsWith("java.lang.") && forbiddenClass.endsWith(instanceClassName)) { log(ast, MSG_KEY, instanceClassName); @@ -143,7 +152,6 @@ else if (addedUsingForbiddenImport(instanceClass, Utils.reportInvalidToken(ast.getType()); break; } - } /** @@ -228,7 +236,7 @@ private static String getClassName(final String classNameAndPath) { * - DetailAST node is pointing to import definition or to the "new" * literal node ("IMPORT" or "LITERAL_NEW" node types). * @return Import text without "import" word and semicolons for given - * "IMPORT" node or instanstiated class Name&Path for given + * "IMPORT" node or instantiated class Name&Path for given * "LITERAL_NEW" node. */ private static String getText(final DetailAST ast) { diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidReturnInFinallyBlockCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidReturnInFinallyBlockCheck.java index ef7b1a7a3d..3d3fcdfede 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidReturnInFinallyBlockCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidReturnInFinallyBlockCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,7 +20,6 @@ package com.github.sevntu.checkstyle.checks.coding; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; @@ -31,14 +30,16 @@ *

        * The finally block is always executed unless there is abnormal program termination, either * resulting from a JVM crash or from a call to System.exit(0). On top of that, any value returned - * from within the finnally block will override the value returned prior to execution of the finally + * from within the finally block will override the value returned prior to execution of the finally * block. This check reports if the finally block contains a return statement. *

        * * @author Andrew Uljanenko + * @since 1.13.0 */ public class ForbidReturnInFinallyBlockCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. @@ -52,6 +53,16 @@ public final int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST finallyNode) { final DetailAST firstSlistNode = finallyNode.findFirstToken(TokenTypes.SLIST); @@ -60,7 +71,7 @@ public void visitToken(DetailAST finallyNode) { for (DetailAST returnNode : listOfReturnNodes) { if (!isReturnInMethodDefinition(returnNode)) { - log(finallyNode.getLineNo(), MSG_KEY); + log(finallyNode, MSG_KEY); } } } @@ -76,7 +87,8 @@ private List getReturnNodes(DetailAST node) { DetailAST child = node.getFirstChild(); while (child != null) { if (child.getType() == TokenTypes.LITERAL_RETURN) { - return Collections.singletonList(child); + result.add(child); + break; } result.addAll(getReturnNodes(child)); child = child.getNextSibling(); @@ -101,4 +113,5 @@ private static boolean isReturnInMethodDefinition(DetailAST returnNode) { } return result; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsCheck.java index 743d0f0423..fba33e11d0 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -30,7 +30,8 @@ /** *

        - * This Check warns on throwing anonymous exception.
        + * This Check warns on throwing anonymous exception. + *

        * Examples: *
          * catch (Exception e) {
        @@ -57,8 +58,10 @@
          * 
        * @author Aleksey Nesterenko * @author Max Vetrenko + * @since 1.11.0 */ public class ForbidThrowAnonymousExceptionsCheck extends AbstractCheck { + /** * Warning message key. */ @@ -89,6 +92,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST literalThrowOrVariableDefAst) { switch (literalThrowOrVariableDefAst.getType()) { @@ -113,7 +126,7 @@ private void identifyThrowingAnonymousException(DetailAST throwDefAst) { if (throwingLiteralNewAst != null && hasObjectBlock(throwingLiteralNewAst)) { - log(throwDefAst.getLineNo(), MSG_KEY); + log(throwDefAst, MSG_KEY); } else if (throwingLiteralNewAst == null) { final DetailAST throwingExceptionNameAst = getThrowingExceptionNameAst(throwDefAst @@ -121,7 +134,7 @@ else if (throwingLiteralNewAst == null) { if (throwingExceptionNameAst != null && anonymousExceptions.contains(throwingExceptionNameAst .getText())) { - log(throwDefAst.getLineNo(), MSG_KEY); + log(throwDefAst, MSG_KEY); } } } @@ -129,7 +142,7 @@ else if (throwingLiteralNewAst == null) { /** * Analyzes variable definition for anonymous exception definition. if found * - adds it to list of anonymous exceptions - * @param variableDefAst The token to exmaine. + * @param variableDefAst The token to examine. */ private void lookForAnonymousExceptionDefinition(DetailAST variableDefAst) { @@ -157,7 +170,7 @@ && hasObjectBlock(variableLiteralNewAst)) { /** * Gets the literal new node from variable definition node or throw node. - * @param literalThrowOrVariableDefAst The token to exmaine. + * @param literalThrowOrVariableDefAst The token to examine. * @return the specified node. */ private static DetailAST @@ -168,7 +181,7 @@ && hasObjectBlock(variableLiteralNewAst)) { /** * Retrieves the AST node which contains the name of throwing exception. - * @param expressionAst The token to exmaine. + * @param expressionAst The token to examine. * @return the specified node. */ private static DetailAST @@ -178,7 +191,7 @@ && hasObjectBlock(variableLiteralNewAst)) { /** * Checks if definition with a literal new has an ObjBlock. - * @param literalNewAst The token to exmaine. + * @param literalNewAst The token to examine. * @return true if the new has an object block. */ private static boolean hasObjectBlock(DetailAST literalNewAst) { @@ -188,7 +201,7 @@ private static boolean hasObjectBlock(DetailAST literalNewAst) { /** * Checks if variable name is definitely an exception name. It is so if * variable type ends with "Exception" suffix - * @param variableNameAst The token to exmaine. + * @param variableNameAst The token to examine. * @return true if the name is an exception. */ private boolean isExceptionName(DetailAST variableNameAst) { diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/IllegalCatchExtendedCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/IllegalCatchExtendedCheck.java index 173bd94d6c..73642e3c4a 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/IllegalCatchExtendedCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/IllegalCatchExtendedCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,23 +19,35 @@ package com.github.sevntu.checkstyle.checks.coding; +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; + +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; -import com.puppycrawl.tools.checkstyle.checks.coding.AbstractIllegalCheck; import com.puppycrawl.tools.checkstyle.utils.CheckUtils; /** * Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException * is almost never acceptable. * @author Simon Harris + * @since 1.8.0 */ -public final class IllegalCatchExtendedCheck extends AbstractIllegalCheck { +public final class IllegalCatchExtendedCheck extends AbstractCheck { + /** * Warning message key. */ public static final String MSG_KEY = "illegal.catch"; + /** Illegal class names. */ + private final Set illegalClassNames = Arrays.stream( + new String[] {"Exception", "Error", "RuntimeException", "Throwable", + "java.lang.Error", "java.lang.Exception", "java.lang.RuntimeException", + "java.lang.Throwable", }).collect(Collectors.toSet()); + /** Disable warnings for "catch" blocks containing * throwing an exception. */ private boolean allowThrow = true; @@ -44,18 +56,24 @@ public final class IllegalCatchExtendedCheck extends AbstractIllegalCheck { * rethrowing an exception. */ private boolean allowRethrow = true; - /** Creates new instance of the check. */ - public IllegalCatchExtendedCheck() { - super(new String[] { - "Exception", - "Error", - "RuntimeException", - "Throwable", - "java.lang.Error", - "java.lang.Exception", - "java.lang.RuntimeException", - "java.lang.Throwable", - }); + /** + * Set the list of illegal classes. + * + * @param classNames + * array of illegal exception classes + */ + public void setIllegalClassNames(final String... classNames) { + illegalClassNames.clear(); + for (final String name : classNames) { + illegalClassNames.add(name); + final int lastDot = name.lastIndexOf('.'); + if (lastDot > 0 + && lastDot < name.length() - 1) { + final String shortName = name + .substring(name.lastIndexOf('.') + 1); + illegalClassNames.add(shortName); + } + } } /** @@ -83,6 +101,11 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + @Override public int[] getRequiredTokens() { return getDefaultTokens(); @@ -107,10 +130,7 @@ public void visitToken(DetailAST detailAST) { // For warnings disable first lvl child must be an EXPR and // second lvl child must be IDENT or LITERAL_NEW with // appropriate boolean flags. - final boolean noWarning = throwAST != null - && firstLvlChild != null - && secondLvlChild != null - && firstLvlChild.getType() == TokenTypes.EXPR + final boolean noWarning = secondLvlChild != null && ((allowThrow && secondLvlChild.getType() == TokenTypes.IDENT) || (allowRethrow && secondLvlChild.getType() == TokenTypes.LITERAL_NEW)); @@ -133,7 +153,6 @@ public DetailAST getThrowAST(DetailAST parentAST) { final DetailAST[] asts = getChilds(parentAST); for (DetailAST currentNode : asts) { - if (currentNode.getType() != TokenTypes.PARAMETER_DEF && currentNode.getNumberOfChildren() > 0) { result = getThrowAST(currentNode); @@ -166,4 +185,15 @@ private static DetailAST[] getChilds(DetailAST node) { return result; } + /** + * Checks if given class is illegal. + * + * @param ident + * ident to check. + * @return true if given ident is illegal. + */ + protected boolean isIllegalClassName(final String ident) { + return illegalClassNames.contains(ident); + } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/LogicConditionNeedOptimizationCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/LogicConditionNeedOptimizationCheck.java index 4b150cbe52..d28acecdc3 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/LogicConditionNeedOptimizationCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/LogicConditionNeedOptimizationCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -26,30 +26,47 @@ /** *

        * This check prevents the placement of local variables and fields after calling - * methods in '&&' and '||' conditions. + * methods and instanceof in '&&' and '||' conditions. *

        *

        * For example: if(getProperty() && property) ==> if(property && getProperty()), * and similarly for any expression. *

        * @author Ilia Dubinin + * @since 1.8.0 */ public class LogicConditionNeedOptimizationCheck extends AbstractCheck { + /** * The key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "logic.condition.need.optimization"; + /** Integer for the 3rd position. */ + private static final int THIRD_POSITION = 3; + /** Number of operands positions in start/stop array. */ + private static final int OPERAND_SIZE = 4; + @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LAND, TokenTypes.LOR }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST detailAST) { if (needOptimization(detailAST)) { - log(detailAST.getLineNo(), MSG_KEY, + log(detailAST, MSG_KEY, detailAST.getText(), detailAST.getLineNo(), detailAST.getColumnNo()); } @@ -64,23 +81,108 @@ public void visitToken(DetailAST detailAST) { * @return - boolean variable */ private static boolean needOptimization(DetailAST logicNode) { - final DetailAST secondOperand = getSecondOperand(logicNode); - return !secondOperand.branchContains(TokenTypes.METHOD_CALL) - && logicNode.branchContains(TokenTypes.METHOD_CALL); + final DetailAST[] operands = getOperands(logicNode); + final boolean firstInstanceOf = branchContains(operands, 1, TokenTypes.LITERAL_INSTANCEOF); + final boolean secondTypeCast = branchContains(operands, 2, TokenTypes.TYPECAST); + final boolean result; + + if (firstInstanceOf && secondTypeCast) { + result = false; + } + else { + result = !branchContains(operands, 2, TokenTypes.METHOD_CALL) + && !branchContains(operands, 2, TokenTypes.LITERAL_INSTANCEOF) + && (firstInstanceOf + || branchContains(operands, 1, TokenTypes.METHOD_CALL)); + } + + return result; } /** *

        - * Return second operand of current logic operator. + * Return operands of current logic operator. *

        * @param logicNode - current logic operator - * @return second operand + * @return operands */ - private static DetailAST getSecondOperand(DetailAST logicNode) { - DetailAST child = logicNode.getLastChild(); - if (child.getType() == TokenTypes.RPAREN) { - child = child.getPreviousSibling(); + private static DetailAST[] getOperands(DetailAST logicNode) { + final DetailAST[] results = new DetailAST[OPERAND_SIZE]; + DetailAST node = logicNode.getFirstChild(); + + // start of first + results[0] = node; + + int parenthesis = 0; + + do { + if (node.getType() == TokenTypes.LPAREN) { + parenthesis++; + } + else { + if (node.getType() == TokenTypes.RPAREN) { + parenthesis--; + } + if (parenthesis == 0) { + // end of first + results[1] = node; + } + } + + node = node.getNextSibling(); + } while (parenthesis > 0); + + // start of second + results[2] = node; + results[THIRD_POSITION] = logicNode.getLastChild(); + + return results; + } + + /** + * Checks if the node range contains a token of the provided type. + * @param operands the list operands in order of start and stop + * @param setNumber to retrieve the 1st or 2nd operand + * @param type a TokenType + * @return true if and only if the node range + * contains a token of type {@code type}. + */ + private static boolean branchContains(DetailAST[] operands, int setNumber, int type) { + final boolean result; + + if (setNumber == 1) { + result = branchContains(operands[0], operands[1], type); } - return child; + else { + result = branchContains(operands[2], operands[THIRD_POSITION], type); + } + + return result; } + + /** + * Checks if the node range contains a token of the provided type. + * @param start the token to start checking with (inclusive) + * @param end the token to end with (inclusive) + * @param type a TokenType + * @return true if and only if the node range + * contains a token of type {@code type}. + */ + private static boolean branchContains(DetailAST start, DetailAST end, int type) { + boolean result = false; + DetailAST current = start; + + while (true) { + result = current.branchContains(type); + + if (current == end || result) { + break; + } + + current = current.getNextSibling(); + } + + return result; + } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopCheck.java index d7d2519a51..6540a6a48d 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -36,13 +36,14 @@ /** *

        * This check can help you to write the whole for-each map iteration more - * correctly: + * correctly. *

        *

        * 1. If you iterate over a map using map.keySet() or map.entrySet(), but your * code uses only map values, Check will propose you to use map.values() instead * of map.keySet() or map.entrySet(). Replacing map.keySet() or map.entrySet() * with map.values() for such cases can a bit improve an iteration performance. + *

        *

        * Bad: *

        @@ -71,9 +72,11 @@ * } *
        * + *

        * 2. If you iterate over a map using map.entrySet(), but never call * entry.getValue(), Check will propose you to use map.keySet() instead of * map.entrySet(). to iterate over map keys only. + *

        *

        * Bad: *

        @@ -95,10 +98,12 @@ * } *
        * + *

        * 3. If you iterate over a map with map.keySet() and use both keys and values, * check will propose you to use map.entrySet() to improve an iteration * performance by avoiding search operations inside a map. For this case, * iteration can significantly grow up a performance. + *

        *

        * Bad: *

        @@ -120,6 +125,7 @@ * } *
      * @author Max Vetrenko + * @since 1.11.0 */ public class MapIterationInForEachLoopCheck extends AbstractCheck { @@ -273,6 +279,16 @@ public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_FOR, TokenTypes.IMPORT, TokenTypes.VARIABLE_DEF, }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void beginTree(DetailAST ast) { qualifiedImportList.clear(); @@ -282,7 +298,6 @@ public void beginTree(DetailAST ast) { @Override public void visitToken(DetailAST ast) { switch (ast.getType()) { - case TokenTypes.IMPORT: final String qualifiedMapImportText = getMapImportQualifiedName(ast); if (qualifiedMapImportText != null) { @@ -330,14 +345,10 @@ private String validate(DetailAST forLiteralNode) { final DetailAST forEachNode = forLiteralNode.findFirstToken(TokenTypes.FOR_EACH_CLAUSE); final DetailAST keySetOrEntrySetNode = getKeySetOrEntrySetNode(forEachNode); - boolean isMapClassField = false; // Search for keySet or entrySet if (keySetOrEntrySetNode != null) { - if (keySetOrEntrySetNode.getPreviousSibling().getChildCount() != 0) { - isMapClassField = true; - } - final DetailAST variableDefNode = forEachNode.getFirstChild(); - final String keyOrEntryVariableName = variableDefNode.getLastChild().getText(); + final boolean isMapClassField = keySetOrEntrySetNode.getPreviousSibling() + .getChildCount() != 0; final String currentMapVariableName; @@ -351,6 +362,8 @@ private String validate(DetailAST forLiteralNode) { final DetailAST forEachOpeningBrace = forLiteralNode.getLastChild(); if (!isMapPassedIntoAnyMethod(forEachOpeningBrace)) { + final DetailAST variableDefNode = forEachNode.getFirstChild(); + final String keyOrEntryVariableName = variableDefNode.getLastChild().getText(); if (proposeKeySetUsage && KEY_SET_METHOD_NAME.equals( @@ -370,7 +383,7 @@ else if (proposeEntrySetUsage) { /** * Checks if the not is a for each. - * @param forNode The token to exmaine. + * @param forNode The token to examine. * @return true if is for each. */ private static boolean isForEach(DetailAST forNode) { @@ -400,10 +413,22 @@ private DetailAST getKeySetOrEntrySetNode(DetailAST forEachNode) { || ENTRY_SET_METHOD_NAME.equals(identNode.getText())) { final String mapClassName; if (isMapClassField) { - mapClassName = identNode.getPreviousSibling().getLastChild().getText(); + final DetailAST lastChild = identNode.getPreviousSibling().getLastChild(); + if (lastChild == null) { + mapClassName = null; + } + else { + mapClassName = lastChild.getText(); + } } else { - mapClassName = identNode.getPreviousSibling().getText(); + final DetailAST previousSibling = identNode.getPreviousSibling(); + if (previousSibling == null) { + mapClassName = null; + } + else { + mapClassName = previousSibling.getText(); + } } if (mapNamesList.contains(mapClassName)) { keySetOrEntrySetNode = identNode; @@ -422,14 +447,16 @@ private DetailAST getKeySetOrEntrySetNode(DetailAST forEachNode) { * @return true, if any Method Call contains Map Parameter. */ private boolean isMapPassedIntoAnyMethod(DetailAST forEachOpeningBraceNode) { + boolean result = false; final List methodCallNodeList = getSubTreeNodesOfType( forEachOpeningBraceNode, TokenTypes.METHOD_CALL); for (DetailAST methodCallNode : methodCallNodeList) { if (hasMapAsParameter(methodCallNode)) { - return true; + result = true; + break; } } - return false; + return result; } /** @@ -480,7 +507,6 @@ private String checkForWrongKeySetUsage(DetailAST forEachOpeningBraceNode, Strin } if (mapIdentNode != null && GET_NODE_NAME.equals(identOrLiteralIfNode.getText()) && mapName.equals(mapIdentNode.getText())) { - methodGetCallCount++; } @@ -489,10 +515,33 @@ private String checkForWrongKeySetUsage(DetailAST forEachOpeningBraceNode, Strin } } + if (methodGetCallCount != 0 && keyIdentCount != 0) { + if (proposeValuesUsage && methodGetCallCount == keyIdentCount) { + result = MSG_KEY_VALUES; + } + else if (methodGetCallCount < keyIdentCount + && methodGetCallCount > 0 + && getMethodGetCallInsideIfCount(identAndLiteralIfNodesList, mapName, + isMapClassField) != methodGetCallCount) { + result = MSG_KEY_ENTRYSET; + } + } + return result; + } + + /** + * Counts the getter methods called inside the if statement. + * @param identAndLiteralIfNodesList the nodes to examine. + * @param mapName Current map name. + * @param isMapClassField if the map is a class field. + * @return The number of methods. + */ + private static int getMethodGetCallInsideIfCount(List identAndLiteralIfNodesList, + String mapName, boolean isMapClassField) { final DetailAST literalIfNode = getFirstNodeOfType(identAndLiteralIfNodesList, TokenTypes.LITERAL_IF); - int methodGetCallInsideIfCount = 0; + int result = 0; if (literalIfNode != null) { for (DetailAST node : getSubTreeNodesOfType(literalIfNode, TokenTypes.IDENT)) { DetailAST mapIdentNode = node.getPreviousSibling(); @@ -502,22 +551,10 @@ private String checkForWrongKeySetUsage(DetailAST forEachOpeningBraceNode, Strin if (mapIdentNode != null && GET_NODE_NAME.equals(node.getText()) && mapName.equals(mapIdentNode.getText())) { - methodGetCallInsideIfCount++; + result++; } } } - - if (methodGetCallCount != 0 && keyIdentCount != 0) { - - if (proposeValuesUsage && methodGetCallCount == keyIdentCount) { - result = MSG_KEY_VALUES; - } - - else if (methodGetCallCount < keyIdentCount && methodGetCallCount > 0 - && methodGetCallInsideIfCount != methodGetCallCount) { - result = MSG_KEY_ENTRYSET; - } - } return result; } @@ -537,7 +574,6 @@ private String checkForWrongEntrySetUsage(DetailAST forEachOpeningBraceNode, int methodGetKeyCallCount = 0; int methodGetValueCallCount = 0; for (DetailAST identNode : identNodesList) { - final DetailAST entryNode = identNode.getPreviousSibling(); if (entryNode != null && GET_KEY_NODE_NAME.equals(identNode.getText()) @@ -557,7 +593,6 @@ private String checkForWrongEntrySetUsage(DetailAST forEachOpeningBraceNode, } else if (methodGetKeyCallCount > 0 && methodGetValueCallCount == 0) { result = MSG_KEY_KEYSET; - } return result; } @@ -570,12 +605,12 @@ else if (methodGetKeyCallCount > 0 && methodGetValueCallCount == 0) { */ private boolean isMapVariable(DetailAST variableDefNode) { boolean result = false; - final List literaNewNodeslList = + final List literalNewNodeslList = getSubTreeNodesOfType(variableDefNode, TokenTypes.LITERAL_NEW, TokenTypes.ASSIGN); - final String className = getClassName(literaNewNodeslList); + final String className = getClassName(literalNewNodeslList); if (className != null - && getFirstNodeOfType(literaNewNodeslList, TokenTypes.ASSIGN) != null) { + && getFirstNodeOfType(literalNewNodeslList, TokenTypes.ASSIGN) != null) { result = isMapImplementation(className); } return result; @@ -635,19 +670,21 @@ private boolean isClassContainsInsideQualifiedImportList(String className) { /** * Returns the instance's class name. - * @param literaNewNodesList + * @param literalNewNodesList * This list contains "new" literals. * @return object's class name, * if class name is missed, returns null. */ - private static String getClassName(final List literaNewNodesList) { - for (DetailAST literalNewNode : literaNewNodesList) { + private static String getClassName(final List literalNewNodesList) { + String result = null; + for (DetailAST literalNewNode : literalNewNodesList) { final DetailAST exprNode = literalNewNode.getParent(); if (exprNode.getParent().getType() == TokenTypes.ASSIGN) { - return literalNewNode.getFirstChild().getText(); + result = literalNewNode.getFirstChild().getText(); + break; } } - return null; + return result; } /** @@ -661,12 +698,14 @@ private static String getClassName(final List literaNewNodesList) { */ private static DetailAST getFirstNodeOfType(List nodesList, int aSpecificType) { + DetailAST result = null; for (DetailAST node : nodesList) { if (node.getType() == aSpecificType) { - return node; + result = node; + break; } } - return null; + return result; } /** @@ -677,14 +716,16 @@ private static DetailAST getFirstNodeOfType(List nodesList, * @return full path of map implementation or null. */ private String getMapImportQualifiedName(DetailAST importNode) { + String result = null; final String mapClassQualifiedName = FullIdent.createFullIdent( importNode.getFirstChild()).getText(); for (String qualifiedName : supportedMapImplQualifiedNames) { if (mapClassQualifiedName.equals(qualifiedName)) { - return mapClassQualifiedName; + result = mapClassQualifiedName; + break; } } - return null; + return result; } /** @@ -723,4 +764,5 @@ private static List getSubTreeNodesOfType(DetailAST rootNode, } return result; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MoveVariableInsideIfCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MoveVariableInsideIfCheck.java new file mode 100644 index 0000000000..39672c8b1c --- /dev/null +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MoveVariableInsideIfCheck.java @@ -0,0 +1,366 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.coding; + +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.utils.ScopeUtils; + +/** + *

      + * Checks if a variable is only used inside if statements and asks for it's + * declaration to be moved there too. + *

      + *

      + * Rationale: Code inside if/else statements are only executed when those specific block + * conditions evaluate to true. Moving variables inside these blocks prevents the code from being + * executed when the value of the variable is not even being used. It also helps limit the scope + * of the variables from being too broad to confuse new readers. Suppressing variables with false + * violations because of the check's limitations (stated below) also help clearly state the + * purpose of the variable as a temporary storage for a current/future changing value. + *

      + *

      + * An example of how to configure the check is: + *

      + *
      + * <module name="MoveVariableInsideIfCheck"/>
      + * 
      + *

      + * which will produce the following violation: + *

      + *
      + * String variable = input.substring(1); // violation - variable is only used inside if block
      + *
      + * if (condition) {
      + *     return method(variable);
      + * }
      + *
      + * return "";
      + * 
      + *

      + * The code can be written as the following to avoid a violation: + *

      + *
      + * if (condition) {
      + *     String variable = input.substring(1);
      + *     return method(variable);
      + * }
      + *
      + * return "";
      + * 
      + *

      + * No violations will be produced if a variable is used in same scope as declaration, condition of + * block, or if used in multiple blocks. + *

      + *
      + * String variable = input.substring(1);
      + *
      + * if (condition && variable.charAt(0) == 'T') {
      + *     return method(variable);
      + * }
      + * else {
      + *     return method2(variable);
      + * }
      + *
      + * return "";
      + * 
      + *

      + * Limitations: The check can not determine if the value of variable being stored is changed after + * the declaration. Variables like this can't be moved, or may be too complex to move, and thus + * should be suppressed. + *

      + *

      + * Case #1: + *

      + *
      + * final String variable = list.remove(0); // false positive - list is modified with storing value
      + * final String next = list.get(0); // expecting above list modification
      + *
      + * if (next.equals(input)) {
      + *     list.add(variable);
      + * }
      + * 
      + *

      + * Case #2: + *

      + *
      + * final String variable = field.get(0); // false positive - field is modified later, before block
      + *
      + * modifyField(); // field is modified inside this method
      + *
      + * if (condition) {
      + *     field.add(variable);
      + * }
      + * 
      + * + * @author Richard Veach + * @since 1.24.0 + */ +public class MoveVariableInsideIfCheck extends AbstractCheck { + + /** + * A key is pointing to the warning message text in "messages.properties" + * file. + */ + public static final String MSG_KEY = "move.variable.inside"; + + @Override + public int[] getDefaultTokens() { + return new int[] {TokenTypes.VARIABLE_DEF}; + } + + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + + @Override + public void visitToken(DetailAST ast) { + if (ScopeUtils.isLocalVariableDef(ast)) { + validateLocalVariable(ast); + } + } + + /** + * Examines the local variable for violations to be moved inside an nest if + * statement. + * + * @param ast The local variable to examine. + */ + private void validateLocalVariable(DetailAST ast) { + final Holder holder = new Holder(ast); + + for (DetailAST child = ast.getNextSibling(); (!holder.exit) && (child != null); + child = child.getNextSibling()) { + switch (child.getType()) { + case TokenTypes.LITERAL_IF: + validateIf(holder, child); + break; + default: + validateOther(holder, child); + break; + } + } + + if (holder.blockNode != null) { + log(ast, MSG_KEY, holder.variableName, holder.blockNode.getLineNo()); + } + } + + /** + * Examines an if statement to see how many times the specified variable + * identifier was used inside it. + * + * @param holder The object holder with the specified variable to check and + * it's current state. + * @param ifNodeGiven The current if node to examine. + */ + private static void validateIf(Holder holder, DetailAST ifNodeGiven) { + DetailAST ifNode = ifNodeGiven; + + // -@cs[SingleBreakOrContinue] Too complex to break apart + while (true) { + // check condition + final DetailAST rparen = ifNode.findFirstToken(TokenTypes.RPAREN); + final boolean usedInCondition = holder.hasIdent( + ifNode.findFirstToken(TokenTypes.LPAREN), rparen); + + if (usedInCondition) { + holder.setExit(); + break; + } + + final DetailAST elseNode = ifNode.getLastChild(); + + // check body of if + final DetailAST body = rparen.getNextSibling(); + final DetailAST bodyEnd; + + if (body.getType() == TokenTypes.SLIST) { + bodyEnd = body.getLastChild(); + } + else { + bodyEnd = elseNode; + } + + final boolean used = holder.hasIdent(body, bodyEnd); + + if (used) { + holder.setBlockNode(ifNode); + + if (holder.exit) { + break; + } + } + + if (elseNode.getType() != TokenTypes.LITERAL_ELSE) { + break; + } + + ifNode = elseNode.getFirstChild(); + + if (ifNode.getType() != TokenTypes.LITERAL_IF) { + // check body of else + + validateElseOfIf(holder, ifNode, elseNode); + break; + } + } + } + + /** + * Examines the else of an if statement to see how many times the specified + * variable identifier was used inside it. + * + * @param holder The object holder with the specified variable to check and + * it's current state. + * @param ifNode The if node of the specified else. + * @param elseNode The current else node to examine. + */ + private static void validateElseOfIf(Holder holder, DetailAST ifNode, DetailAST elseNode) { + final boolean used; + + if (ifNode.getType() == TokenTypes.SLIST) { + used = holder.hasIdent(ifNode.getFirstChild(), ifNode.getLastChild()); + } + else { + used = holder.hasIdent(ifNode, elseNode.getLastChild()); + } + + if (used) { + holder.setBlockNode(elseNode); + } + } + + /** + * Examines other nodes to see how many times a variable was used inside it. + * If the variable is used, no violations are reported for it. + * + * @param holder The object holder with the specified variable to check and + * it's current state. + * @param child The current node to examine. + */ + private static void validateOther(Holder holder, DetailAST child) { + final boolean used = holder.hasIdent(child, child.getNextSibling()); + + if (used) { + holder.setExit(); + } + } + + /** + * The holder of information for the specified variable. + * + * @author Richard Veach + */ + private static class Holder { + + /** The name of the variable being examined. */ + private String variableName; + /** Switch to trigger ending examining more nodes. */ + private boolean exit; + /** The node to report violations on. */ + private DetailAST blockNode; + + /** + * Default constructor for the class. + * + * @param ast The variable the holder is for. + */ + Holder(DetailAST ast) { + variableName = ast.findFirstToken(TokenTypes.IDENT).getText(); + } + + /** + * Sets the specified node that is to be reported for the violation for + * the block. If there is already a node being reported, then no nodes + * are reported. + * + * @param blockNode The given block node to report for. + */ + public void setBlockNode(DetailAST blockNode) { + if (this.blockNode != null) { + setExit(); + } + else { + this.blockNode = blockNode; + } + } + + /** Sets the state to exit examining further nodes. */ + public void setExit() { + blockNode = null; + exit = true; + } + + /** + * Checks if any of the nodes between the given start and end are an + * identifier with the name of the variable. + * + * @param start The node to start examining from. + * @param end The last node to stop examining once reached. If null, + * then the last node is when we leave the start node. + * @return true if the identifier has been found, otherwise false. + */ + public boolean hasIdent(DetailAST start, DetailAST end) { + boolean found = false; + DetailAST curNode = start; + + // -@cs[SingleBreakOrContinue] Too complex to break apart + while (curNode != null) { + if ((curNode.getType() == TokenTypes.IDENT) + && (variableName.equals(curNode.getText()))) { + found = true; + break; + } + + if (curNode == end) { + break; + } + + DetailAST toVisit = curNode.getFirstChild(); + + while (toVisit == null) { + toVisit = curNode.getNextSibling(); + + if (toVisit == null) { + if (end == null) { + break; + } + + curNode = curNode.getParent(); + } + } + + curNode = toVisit; + } + + return found; + } + + } + +} diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MultipleStringLiteralsExtendedCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MultipleStringLiteralsExtendedCheck.java index 0fa59db06a..fee8a6cf3a 100755 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MultipleStringLiteralsExtendedCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MultipleStringLiteralsExtendedCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -36,8 +36,10 @@ * Checks for multiple occurrences of the same string literal within a single file. * * @author Daniel Grenner + * @since 1.5.3 */ public class MultipleStringLiteralsExtendedCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. @@ -48,7 +50,7 @@ public class MultipleStringLiteralsExtendedCheck extends AbstractCheck { * The found strings and their positions. <String, ArrayList>, with * the ArrayList containing StringInfo objects. */ - private final Map> stringMap = Maps.newHashMap(); + private final Map> stringMap = Maps.newHashMap(); /** * Marks the TokenTypes where duplicate strings should be ignored. @@ -136,19 +138,27 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { if (!isInIgnoreOccurrenceContext(ast)) { final String currentString = ast.getText(); if ((pattern == null) || !pattern.matcher(currentString).find()) { - List hitList = stringMap.get(currentString); + List hitList = stringMap.get(currentString); if (hitList == null) { hitList = Lists.newArrayList(); stringMap.put(currentString, hitList); } - final int line = ast.getLineNo(); - final int col = ast.getColumnNo(); - hitList.add(new StringInfo(line, col)); + hitList.add(ast); } } } @@ -163,15 +173,17 @@ public void visitToken(DetailAST ast) { * {@link #ignoreOccurrenceContext}. */ private boolean isInIgnoreOccurrenceContext(DetailAST ast) { + boolean result = false; DetailAST token = ast.getParent(); while (token != null) { final int type = token.getType(); if (ignoreOccurrenceContext.get(type)) { - return true; + result = true; + break; } token = token.getParent(); } - return false; + return result; } @Override @@ -184,66 +196,19 @@ public void beginTree(DetailAST rootAST) { public void finishTree(DetailAST rootAST) { final Set keys = stringMap.keySet(); for (String key : keys) { - final List hits = stringMap.get(key); + final List hits = stringMap.get(key); if (hits.size() > allowedDuplicates) { int hitsSize = 1; if (highlightAllDuplicates) { hitsSize = hits.size(); } for (int index = 0; index < hitsSize; index++) { - final StringInfo firstFinding = hits.get(index); - final int line = firstFinding.getLine(); - final int col = firstFinding.getCol(); - log(line, col, + final DetailAST firstFinding = hits.get(index); + log(firstFinding, MSG_KEY, key, hits.size()); } } } } - /** - * This class contains information about where a string was found. - */ - private static final class StringInfo { - /** - * Line of finding. - */ - private final int line; - /** - * Column of finding. - */ - private final int col; - - /** - * Creates information about a string position. - * - * @param line - * int - * @param col - * int - */ - private StringInfo(int line, int col) { - this.line = line; - this.col = col; - } - - /** - * The line where a string was found. - * - * @return int Line of the string. - */ - private int getLine() { - return line; - } - - /** - * The column where a string was found. - * - * @return int Column of the string. - */ - private int getCol() { - return col; - } - } - } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsExtendedCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsExtendedCheck.java index 5c8d4b0368..2c5b2edf55 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsExtendedCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsExtendedCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -40,12 +40,12 @@ * <module name="MultipleVariableDeclarations"/> * * - * * - * * @author o_sukhodolsky + * @since 1.5.3 */ public class MultipleVariableDeclarationsExtendedCheck extends AbstractCheck { + /** * Warning message key. */ @@ -89,6 +89,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + /** * Searches for wrong declarations and checks the their type. * @@ -96,12 +106,13 @@ public int[] getDefaultTokens() { * uses to get the parent or previous sibling token. */ public void work(DetailAST ast) { - DetailAST nextNode = ast.getNextSibling(); - final boolean isCommaSeparated = (nextNode != null) - && (nextNode.getType() == TokenTypes.COMMA); if (nextNode != null) { + // -@cs[MoveVariableInsideIf] assignment value is modified later so + // it can't be moved + final boolean isCommaSeparated = nextNode.getType() == TokenTypes.COMMA; + if ((nextNode.getType() == TokenTypes.COMMA) || (nextNode.getType() == TokenTypes.SEMI)) { nextNode = nextNode.getNextSibling(); @@ -127,7 +138,6 @@ public void work(DetailAST ast) { @Override public void visitToken(DetailAST ast) { - final DetailAST token = ast; final boolean inFor = ast.getParent().getType() == TokenTypes.FOR_INIT; final boolean inClass = ast.getParent().getParent().getType() == TokenTypes.CLASS_DEF; @@ -139,10 +149,9 @@ else if (!ignoreCycles && inFor) { work(token); } - else if (!ignoreMethods && !inClass && !inFor) { + else if (!ignoreMethods && !inFor) { work(token); } - } /** @@ -168,4 +177,5 @@ private static DetailAST getLastNode(final DetailAST node) { return currentNode; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NameConventionForJunit4TestClassesCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NameConventionForJunit4TestClassesCheck.java index 1bbda5cd22..8a4e525935 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NameConventionForJunit4TestClassesCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NameConventionForJunit4TestClassesCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -53,6 +53,7 @@ * considered to be a test. This option defaults to empty regex(one that matches * nothing). If for example this option set to "RunWith", then class "SomeClass" * is considered to be a test: + *

      * *
        * 
      @@ -69,6 +70,7 @@
        * matching annotation, it is considered to be a test. This option defaults to
        * "Test|org.junit.Test". For example, if this option set to "Test", then class
        * "SomeClass" is considered to be a test.
      + * 

      * *
        * 
      @@ -95,6 +97,7 @@
        * Following configuration will adjust Check to look for classes annotated with
        * annotation "RunWith" or classes with methods annotated with "Test" and verify
        * that classes names end with "Test" or "Tests".
      + * 

      * *
        *     <module name="NameConventionForJUnit4TestClassesCheck">
      @@ -105,8 +108,10 @@
        * 
      * * @author Zuy Alexey + * @since 1.13.0 */ public class NameConventionForJunit4TestClassesCheck extends AbstractCheck { + /** * Violation message key. */ @@ -195,6 +200,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST classDefNode) { if ((isClassDefinitionAnnotated(classDefNode) || isAtleastOneMethodAnnotated(classDefNode)) @@ -222,19 +237,21 @@ private boolean isClassDefinitionAnnotated(DetailAST classDefNode) { * defined annotation */ private boolean isAtleastOneMethodAnnotated(DetailAST classDefNode) { + boolean result = false; DetailAST classMemberNode = classDefNode.findFirstToken(TokenTypes.OBJBLOCK).getFirstChild(); while (classMemberNode != null) { if (classMemberNode.getType() == TokenTypes.METHOD_DEF && hasAnnotation(classMemberNode, methodAnnotationNameRegex)) { - return true; + result = true; + break; } classMemberNode = classMemberNode.getNextSibling(); } - return false; + return result; } /** @@ -331,11 +348,14 @@ private static String getIdentifierName(DetailAST identifierNode) { * against regex. */ private static boolean isMatchesRegex(Pattern regexPattern, String str) { + final boolean result; if (regexPattern != null) { - return regexPattern.matcher(str).matches(); + result = regexPattern.matcher(str).matches(); } else { - return false; + result = false; } + return result; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NoNullForCollectionReturnCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NoNullForCollectionReturnCheck.java index 88c21af32f..3c21887950 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NoNullForCollectionReturnCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NoNullForCollectionReturnCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -49,17 +49,17 @@ * TreeSet, Vector, Collection, List, Map, Set. *

      * @author Ilja Dubinin + * @since 1.9.0 */ public class NoNullForCollectionReturnCheck extends AbstractCheck { + /** * Warning message key. */ public static final String MSG_KEY = "no.null.for.collections"; /** - *

      * Default list of collection implementing classes. - *

      */ private static final String DEFAULT_COLLECTIONS = "AbstractCollection AbstractList " + "AbstractQueue AbstractSequentialList AbstractSet ArrayBlockingQueue ArrayDeque " @@ -70,9 +70,7 @@ public class NoNullForCollectionReturnCheck extends AbstractCheck { + "LinkedList LinkedTransferQueue PriorityBlockingQueue PriorityQueue RoleList " + "RoleUnresolvedList Stack SynchronousQueue TreeSet Vector Collection List Map Set"; /** - *

      * List of collection, that will be check. - *

      */ private Set collectionList = new HashSet<>(); @@ -128,6 +126,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void beginTree(DetailAST rootAST) { methodDefs.clear(); @@ -149,7 +157,7 @@ public void visitToken(DetailAST detailAST) { && (hasNullLiteralInReturn(detailAST) || (searchThroughMethodBody && isReturnedValueBeNull(detailAST)))) { - log(detailAST.getLineNo(), MSG_KEY); + log(detailAST, MSG_KEY); } } break; @@ -269,7 +277,7 @@ private static LinkedList getAllSubblocks(DetailAST blockDef) { subblocks.addAll(getChildren(blockBody, TokenTypes.LITERAL_TRY)); final List nestedSubblocks = new LinkedList<>(); for (DetailAST currentSubblock : subblocks) { - if (currentSubblock.branchContains(TokenTypes.SLIST)) { + if (currentSubblock.findFirstToken(TokenTypes.SLIST) != null) { nestedSubblocks.addAll(getAllSubblocks(currentSubblock)); } } @@ -352,7 +360,7 @@ private static List getChildren(DetailAST root, int type) { */ private static DetailAST getMethodDef(DetailAST returnLit) { DetailAST methodDef = returnLit; - while (methodDef.getType() != TokenTypes.METHOD_DEF) { + while (methodDef != null && methodDef.getType() != TokenTypes.METHOD_DEF) { methodDef = methodDef.getParent(); } return methodDef; @@ -373,4 +381,5 @@ private static DetailAST getBlockBody(DetailAST blockDef) { } return blockBody; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NumericLiteralNeedsUnderscoreCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NumericLiteralNeedsUnderscoreCheck.java index 5023a8d08c..a3821a152e 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NumericLiteralNeedsUnderscoreCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/NumericLiteralNeedsUnderscoreCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -138,6 +138,7 @@ * int passingBinary = 0b0000_1111; *
      * @author Cheng-Yu Pai + * @since 1.18.0 */ public class NumericLiteralNeedsUnderscoreCheck extends AbstractCheck { @@ -151,6 +152,7 @@ public class NumericLiteralNeedsUnderscoreCheck extends AbstractCheck { * Type of numeric literal. */ protected enum NumericType { + /** * Denotes a decimal literal. For example, 1.2f */ @@ -165,6 +167,7 @@ protected enum NumericType { * Denotes a binary literal. For example, 0b0011 */ BINARY, + } /** @@ -337,10 +340,20 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(final DetailAST ast) { if (!passesCheck(ast)) { - log(ast.getLineNo(), MSG_KEY); + log(ast, MSG_KEY); } } @@ -356,8 +369,10 @@ private static boolean isField(final DetailAST ast) { current = current.getParent(); } return current.getType() == TokenTypes.VARIABLE_DEF - && current.branchContains(TokenTypes.LITERAL_STATIC) - && current.branchContains(TokenTypes.FINAL); + && current.findFirstToken(TokenTypes.MODIFIERS) + .findFirstToken(TokenTypes.LITERAL_STATIC) != null + && current.findFirstToken(TokenTypes.MODIFIERS) + .findFirstToken(TokenTypes.FINAL) != null; } /** @@ -542,23 +557,23 @@ else if ("0b".equals(prefix)) { */ private static boolean numericSegmentPassesRequirement(String numericSegment, int minLength, int symbolsUntilUnderscore) { - if (numericSegment.length() < minLength) { - return true; - } - final char underscore = '_'; - int symbolCount = 0; boolean passes = true; - for (int i = 0; i < numericSegment.length(); i++) { - final char current = numericSegment.charAt(i); - if (symbolCount >= symbolsUntilUnderscore && current != underscore) { - passes = false; - break; - } - if (current == underscore) { - symbolCount = 0; - } - else { - symbolCount++; + if (numericSegment.length() >= minLength) { + final char underscore = '_'; + int symbolCount = 0; + + for (int i = 0; i < numericSegment.length(); i++) { + final char current = numericSegment.charAt(i); + if (symbolCount >= symbolsUntilUnderscore && current != underscore) { + passes = false; + break; + } + if (current == underscore) { + symbolCount = 0; + } + else { + symbolCount++; + } } } return passes; diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheck.java index 73daf0883c..426f3b1b52 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -29,8 +29,10 @@ import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** + * Detects overridable methods in constructors. *

      * This check prevents any calls to overridable methods that are take place in: + *

      *
      1. * Any constructor body (verification is always done by default and not * configurable). @@ -81,6 +83,7 @@ *

        * Notes:

        This check doesn`t handle the situation when there * is a call to an overloaded method(s).

        Here`s an example: + *

        * *
         public class Test {
          *
        @@ -124,6 +127,7 @@
          * @author  Daniil
          *         Yaroslavtsev
          * @author Ilja Dubinin
        + * @since 1.8.0
          */
         public class OverridableMethodInConstructorCheck extends AbstractCheck {
         
        @@ -176,7 +180,7 @@ public class OverridableMethodInConstructorCheck extends AbstractCheck {
             private DetailAST curMethodDef;
         
             /**
        -     * A current root of the synthax tree is being processed.
        +     * A current root of the syntax tree is being processed.
              * */
             private DetailAST treeRootAST;
         
        @@ -252,6 +256,16 @@ public int[] getDefaultTokens() {
                 return new int[] {TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF};
             }
         
        +    @Override
        +    public int[] getAcceptableTokens() {
        +        return getDefaultTokens();
        +    }
        +
        +    @Override
        +    public int[] getRequiredTokens() {
        +        return getDefaultTokens();
        +    }
        +
             @Override
             public void beginTree(DetailAST rootAST) {
                 treeRootAST = rootAST;
        @@ -259,13 +273,10 @@ public void beginTree(DetailAST rootAST) {
         
             @Override
             public void visitToken(final DetailAST detailAST) {
        -
                 final DetailAST classDef = getClassDef(detailAST);
         
                 if (classDef != null && !hasModifier(classDef, TokenTypes.FINAL)) {
        -
                     switch (detailAST.getType()) {
        -
                         case TokenTypes.CTOR_DEF:
                             logWarnings(detailAST, KEY_CTOR);
                             break;
        @@ -306,7 +317,6 @@ && realizesAnInterface(classDef, Serializable.class.getSimpleName())) {
              *            "messages.properties" file.
              */
             private void logWarnings(final DetailAST detailAST, final String key) {
        -
                 final List methodCallsToWarnList =
                     getOverridables(detailAST);
         
        @@ -337,7 +347,6 @@ private void logWarnings(final DetailAST detailAST, final String key) {
              *         constructor body.
              */
             private List getOverridables(final DetailAST parentAST) {
        -
                 final List result =
                     new LinkedList<>();
                 final List methodCallsList = getMethodCallsList(parentAST);
        @@ -366,7 +375,6 @@ && isOverridableMethodCall(curNode)) {
              *         overridable method call and false otherwise.
              */
             private boolean isOverridableMethodCall(final DetailAST methodCallAST) {
        -
                 boolean result = false;
                 visitedMethodCalls.add(methodCallAST);
         
        @@ -408,7 +416,6 @@ && isOverridableMethodCall(curNode)) {
              *         current parent node.
              */
             private List getMethodCallsList(final DetailAST parentAST) {
        -
                 final List result = new LinkedList<>();
         
                 for (DetailAST curNode : getChildren(parentAST)) {
        @@ -432,7 +439,6 @@ private List getMethodCallsList(final DetailAST parentAST) {
              * @return The method name is related to the current METHOD_CALL DetailAST.
              */
             private String getMethodName(final DetailAST methodCallAST) {
        -
                 String result = null;
         
                 final DetailAST ident = methodCallAST.findFirstToken(TokenTypes.IDENT);
        @@ -444,7 +450,6 @@ private String getMethodName(final DetailAST methodCallAST) {
                     final DetailAST childAST = methodCallAST.getFirstChild();
         
                     if (childAST != null && childAST.getType() == TokenTypes.DOT) {
        -
                         final DetailAST firstChild = childAST.getFirstChild();
                         final DetailAST lastChild = childAST.getLastChild();
         
        @@ -478,7 +483,6 @@ else if (firstChild.getType() == TokenTypes.IDENT
              *         node.
              */
             private DetailAST getMethodDef(final DetailAST methodCallAST) {
        -
                 DetailAST result = null;
         
                 curMethodDef = null;
        @@ -486,20 +490,18 @@ private DetailAST getMethodDef(final DetailAST methodCallAST) {
         
                 final String methodName = getMethodName(methodCallAST);
                 if (methodName != null) {
        -
                     final DetailAST curClassAST = getClassDef(methodCallAST);
                     final DetailAST callsChild = methodCallAST.getFirstChild();
        -            final String variableTypeName;
        +            final String variableTypeName = getVariableType(methodCallAST);
         
        -            if (callsChild.getType() != TokenTypes.DOT
        -                    || (variableTypeName = getVariableType(methodCallAST)) == null
        +            if (variableTypeName == null
        +                    || callsChild.getType() != TokenTypes.DOT
                             || isItTypeOfCurrentClass(variableTypeName, curClassAST)
                             || isItCallMethodViaKeywordThis(variableTypeName, curClassAST)) {
                         getMethodDef(curClassAST, methodName);
                     }
         
                     if (curMethodDefCount == 0) {
        -
                         final List baseClasses = getBaseClasses(curClassAST);
         
                         for (DetailAST curBaseClass : baseClasses) {
        @@ -555,7 +557,6 @@ private List getMethodDef(final DetailAST parentAST,
                 List definitionsList = new LinkedList<>();
         
                 for (DetailAST curNode : getChildren(parentAST)) {
        -
                     if (curNode.getNumberOfChildren() > 0) {
                         if (curNode.getType() == TokenTypes.METHOD_DEF) {
                             final String curMethodName = curNode.findFirstToken(
        @@ -603,7 +604,6 @@ else if (dotChild.getType() == TokenTypes.DOT) {
                         typeName = dotChild.getFirstChild().getText()
                                 + PATH_SEPARATOR + dotChild.getLastChild().getText();
                     }
        -
                 }
                 return typeName;
             }
        @@ -651,14 +651,13 @@ else if (dotChild.getType() == TokenTypes.DOT) {
             }
         
             /**
        -     * Gets the count of parameters for current method definitioin or
        +     * Gets the count of parameters for current method definition or
              * method call.
              * @param methodDefOrCallAST METHOD_DEF or METHOD_CALL
              *     DetailAST node
              * @return the count of parameters for current method.
              */
             private static int getMethodParamsCount(DetailAST methodDefOrCallAST) {
        -
                 int result = 0;
                 DetailAST paramsParentAST = null;
         
        @@ -696,7 +695,6 @@ else if (methodDefOrCallAST.getType() == TokenTypes.METHOD_DEF) {
              */
             private static boolean hasModifier(final DetailAST methodOrClassDefAST,
                 int modifierType) {
        -
                 boolean result = false;
                 final DetailAST modifiers = methodOrClassDefAST
                         .findFirstToken(TokenTypes.MODIFIERS);
        @@ -722,7 +720,6 @@ private static boolean hasModifier(final DetailAST methodOrClassDefAST,
              *         node named aMethodNode.
              * */
             private static DetailAST getClassDef(final DetailAST methodNode) {
        -
                 DetailAST curNode = methodNode;
         
                 while (curNode != null && curNode.getType() != TokenTypes.CLASS_DEF) {
        @@ -736,14 +733,13 @@ private static DetailAST getClassDef(final DetailAST methodNode) {
              * Gets the CLASS_DEF DetailAST node for the class is named "aClassName".
              *
              * @param rootNode
        -     *            A root node of synthax tree is being processed.
        +     *            A root node of syntax tree is being processed.
              * @param className
              *            The name of class to search.
              * @return The CLASS_DEF DetailAST node which is related to the class is
              *         named "aClassName".
              */
             private static DetailAST getClassDef(DetailAST rootNode, String className) {
        -
                 DetailAST curNode = rootNode;
         
                 while (curNode != null) {
        @@ -781,7 +777,6 @@ private static DetailAST getClassDef(DetailAST rootNode, String className) {
              */
             private boolean realizesAnInterface(final DetailAST classDefNode,
                     final String interfaceName) {
        -
                 boolean result = false;
                 final List classWithBaseClasses =
                         getBaseClasses(classDefNode);
        @@ -810,7 +805,6 @@ private boolean realizesAnInterface(final DetailAST classDefNode,
              */
             private static boolean implementsAnInterface(final DetailAST classDefAST,
                     final String interfaceName) {
        -
                 boolean result = false;
                 final DetailAST implClause = classDefAST
                         .findFirstToken(TokenTypes.IMPLEMENTS_CLAUSE);
        @@ -837,7 +831,6 @@ private static boolean implementsAnInterface(final DetailAST classDefAST,
              *         processed and all it`s base classes.
              */
             private List getBaseClasses(final DetailAST classDefNode) {
        -
                 final List result = new LinkedList<>();
                 String baseClassName = getBaseClassName(classDefNode);
         
        @@ -847,7 +840,15 @@ private List getBaseClasses(final DetailAST classDefNode) {
                         result.add(curClass);
                         baseClassName = getBaseClassName(curClass);
                         if (baseClassName != null) {
        -                    curClass = getClassDef(treeRootAST, baseClassName);
        +                    final DetailAST nextClass = getClassDef(treeRootAST, baseClassName);
        +
        +                    // prevent infinite loop with similar named classes
        +                    if (nextClass == curClass) {
        +                        curClass = null;
        +                    }
        +                    else {
        +                        curClass = nextClass;
        +                    }
                         }
                         else {
                             break;
        @@ -865,7 +866,6 @@ private List getBaseClasses(final DetailAST classDefNode) {
              * @return The name of a base class for current class.
              */
             private static String getBaseClassName(final DetailAST classDefNode) {
        -
                 String result = null;
                 final DetailAST extendsClause = classDefNode
                         .findFirstToken(TokenTypes.EXTENDS_CLAUSE);
        @@ -903,11 +903,12 @@ private static List getChildren(final DetailAST node) {
             }
         
             /**
        -     * Class that incapsulates the DetailAST node related to the method call
        +     * Class that encapsulates the DetailAST node related to the method call
              * that leads to call of the overridable method and the name of
              * overridable method.
              */
             private final class OverridableMetCall {
        +
                 /**
                  * DetailAST node is related to the method call that leads to
                  *           call of the overridable method.
        @@ -931,6 +932,7 @@ private OverridableMetCall(DetailAST methodCallAST,
                     this.metCallAST = methodCallAST;
                     this.overridableMetName = overridableMetName;
                 }
        +
             }
         
         }
        diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/RedundantReturnCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/RedundantReturnCheck.java
        index 8d53df0422..70ed96d9d4 100644
        --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/RedundantReturnCheck.java
        +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/RedundantReturnCheck.java
        @@ -1,6 +1,6 @@
         ////////////////////////////////////////////////////////////////////////////////
         // checkstyle: Checks Java source code for adherence to a set of rules.
        -// Copyright (C) 2001-2016 the original author or authors.
        +// Copyright (C) 2001-2018 the original author or authors.
         //
         // This library is free software; you can redistribute it and/or
         // modify it under the terms of the GNU Lesser General Public
        @@ -76,6 +76,7 @@
          * @author Troshin Sergey
          * @author Max Vetrenko
          * @author Alexey Nesterenko
        + * @since 1.8.0
          */
         public class RedundantReturnCheck extends AbstractCheck {
         
        @@ -107,8 +108,17 @@ public int[] getDefaultTokens() {
             }
         
             @Override
        -    public void visitToken(DetailAST ast) {
        +    public int[] getAcceptableTokens() {
        +        return getDefaultTokens();
        +    }
        +
        +    @Override
        +    public int[] getRequiredTokens() {
        +        return getDefaultTokens();
        +    }
         
        +    @Override
        +    public void visitToken(DetailAST ast) {
                 final DetailAST blockAst = ast.getLastChild();
         
                 switch (ast.getType()) {
        @@ -139,8 +149,8 @@ public void visitToken(DetailAST ast) {
              * @return true if the block can be ignored.
              */
             private boolean ignoreLonelyReturn(DetailAST objectBlockAst) {
        -
                 return allowReturnInEmptyMethodsAndConstructors
        +                    && objectBlockAst.getFirstChild() != null
                             && objectBlockAst.getFirstChild().getType()
                                 == TokenTypes.LITERAL_RETURN;
             }
        @@ -160,7 +170,6 @@ private static boolean hasNonEmptyBody(DetailAST defAst) {
              * @return true if void method has non-empty body.
              */
             private static boolean isVoidMethodWithNonEmptyBody(DetailAST methodDefAst) {
        -
                 return methodDefAst.getLastChild().getType() == TokenTypes.SLIST
                             && methodDefAst.findFirstToken(TokenTypes.TYPE)
                                 .findFirstToken(TokenTypes.LITERAL_VOID) != null
        @@ -174,7 +183,7 @@ private static boolean isVoidMethodWithNonEmptyBody(DetailAST methodDefAst) {
              */
             private void log(List redundantReturnsAst) {
                 for (DetailAST redundantLiteralReturnAst : redundantReturnsAst) {
        -            log(redundantLiteralReturnAst.getLineNo(), MSG_KEY);
        +            log(redundantLiteralReturnAst, MSG_KEY);
                 }
             }
         
        @@ -186,25 +195,21 @@ private void log(List redundantReturnsAst) {
              * @return list of redundant returns or empty list if none were found
              */
             private static List getRedundantReturns(DetailAST objectBlockAst) {
        -
                 final List redundantReturns = new ArrayList<>();
         
                 final int placeForRedundantReturn = objectBlockAst
                     .getLastChild().getPreviousSibling().getType();
         
                 if (placeForRedundantReturn == TokenTypes.LITERAL_RETURN) {
        -
                     final DetailAST lastChildAst = objectBlockAst.getLastChild();
         
                     final DetailAST redundantReturnAst = lastChildAst.getPreviousSibling();
         
                     redundantReturns.add(redundantReturnAst);
        -
                 }
                 else if (placeForRedundantReturn == TokenTypes.LITERAL_TRY
                         && !getRedundantReturnsInTryCatchBlock(objectBlockAst
                             .findFirstToken(TokenTypes.LITERAL_TRY)).isEmpty()) {
        -
                     final List redundantsAst = getRedundantReturnsInTryCatchBlock(objectBlockAst
                             .findFirstToken(TokenTypes.LITERAL_TRY));
         
        @@ -221,7 +226,6 @@ else if (placeForRedundantReturn == TokenTypes.LITERAL_TRY
              * @return list of redundant returns or empty list if none were found
              */
             private static List getRedundantReturnsInTryCatchBlock(DetailAST tryAst) {
        -
                 final List redundantReturns = new ArrayList<>();
         
                 DetailAST tryBlockAst = null;
        @@ -262,7 +266,6 @@ private static List getRedundantReturnsInTryCatchBlock(DetailAST tryA
         
                 // if redundant return is in finally block
                 if (blockAst.getNextSibling() != null) {
        -
                     final DetailAST afterCatchBlockAst = blockAst.getNextSibling().getLastChild()
                         .getLastChild();
         
        @@ -285,7 +288,6 @@ private static DetailAST getNextCatchBlock(DetailAST blockAst) {
                 DetailAST catchBlockAst = null;
                 if (blockAst.getNextSibling() != null
                         && blockAst.getNextSibling().getType() == TokenTypes.LITERAL_CATCH) {
        -
                     catchBlockAst = blockAst.getNextSibling();
                 }
                 return catchBlockAst;
        @@ -298,11 +300,9 @@ private static DetailAST getNextCatchBlock(DetailAST blockAst) {
              * @return redundant literal return if found, else null.
              */
             private static DetailAST getRedundantReturnInBlock(DetailAST statementAst) {
        -
                 DetailAST redundantReturnAst = null;
         
                 if (statementAst != null) {
        -
                     if (statementAst.getType() == TokenTypes.LITERAL_RETURN) {
                         redundantReturnAst = statementAst;
                     }
        @@ -328,24 +328,21 @@ private static DetailAST getRedundantReturnInBlock(DetailAST statementAst) {
             private static DetailAST findRedundantReturnInCatch(DetailAST lastStatementInCatchBlockAst) {
                 DetailAST redundantReturnAst = null;
                 DetailAST currentNodeAst = lastStatementInCatchBlockAst;
        -        DetailAST toVisitAst = currentNodeAst;
                 DetailAST returnAst = null;
        -        while (toVisitAst != null) {
        -
        -            toVisitAst = Utils.getNextSubTreeNode(toVisitAst, currentNodeAst);
        -
        -            if (toVisitAst != null
        -                    && (toVisitAst.getParent().getParent().getNextSibling() == null
        -                        || toVisitAst.getParent().getParent().getNextSibling().getType()
        -                            == TokenTypes.RCURLY)
        -                    && toVisitAst.getType() == TokenTypes.LITERAL_RETURN
        -                    && toVisitAst.getParent().getNextSibling() == null) {
        +        DetailAST toVisitAst = Utils.getNextSubTreeNode(currentNodeAst, currentNodeAst);
         
        +        while (toVisitAst != null) {
        +            if (toVisitAst.getType() == TokenTypes.OBJBLOCK) {
        +                while (toVisitAst.getNextSibling() == null) {
        +                    toVisitAst = toVisitAst.getParent();
        +                }
        +                toVisitAst = toVisitAst.getNextSibling();
        +            }
        +            else if (isFinalReturn(toVisitAst)) {
                         returnAst = toVisitAst;
         
                         while (toVisitAst != null
                                     && toVisitAst.getParent() != currentNodeAst.getLastChild()) {
        -
                             toVisitAst = toVisitAst.getParent();
                         }
         
        @@ -355,9 +352,25 @@ private static DetailAST findRedundantReturnInCatch(DetailAST lastStatementInCat
         
                         toVisitAst = returnAst;
                     }
        +
        +            toVisitAst = Utils.getNextSubTreeNode(toVisitAst, currentNodeAst);
                 }
         
                 currentNodeAst = Utils.getNextSubTreeNode(currentNodeAst, lastStatementInCatchBlockAst);
                 return redundantReturnAst;
             }
        +
        +    /**
        +     * Checks if the {@code ast} is the final return statement.
        +     * @param ast the AST to examine.
        +     * @return {@code true} if the {@code ast} is the final return statement.
        +     */
        +    private static boolean isFinalReturn(DetailAST ast) {
        +        return (ast.getParent().getParent().getNextSibling() == null
        +                    || ast.getParent().getParent().getNextSibling().getType()
        +                    == TokenTypes.RCURLY)
        +                && ast.getType() == TokenTypes.LITERAL_RETURN
        +                && ast.getParent().getNextSibling() == null;
        +    }
        +
         }
        diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/RequireFailForTryCatchInJunitCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/RequireFailForTryCatchInJunitCheck.java
        new file mode 100644
        index 0000000000..374fb60b9e
        --- /dev/null
        +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/RequireFailForTryCatchInJunitCheck.java
        @@ -0,0 +1,249 @@
        +////////////////////////////////////////////////////////////////////////////////
        +// checkstyle: Checks Java source code for adherence to a set of rules.
        +// Copyright (C) 2001-2018 the original author or authors.
        +//
        +// This library is free software; you can redistribute it and/or
        +// modify it under the terms of the GNU Lesser General Public
        +// License as published by the Free Software Foundation; either
        +// version 2.1 of the License, or (at your option) any later version.
        +//
        +// This library is distributed in the hope that it will be useful,
        +// but WITHOUT ANY WARRANTY; without even the implied warranty of
        +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
        +// Lesser General Public License for more details.
        +//
        +// You should have received a copy of the GNU Lesser General Public
        +// License along with this library; if not, write to the Free Software
        +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
        +////////////////////////////////////////////////////////////////////////////////
        +
        +package com.github.sevntu.checkstyle.checks.coding;
        +
        +import com.github.sevntu.checkstyle.Utils;
        +import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
        +import com.puppycrawl.tools.checkstyle.api.DetailAST;
        +import com.puppycrawl.tools.checkstyle.api.FullIdent;
        +import com.puppycrawl.tools.checkstyle.api.TokenTypes;
        +import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility;
        +
        +/**
        + * 

        + * Checks if a try/catch block has a junit fail assertion inside the try for a junit method. + *

        + *

        + * Rationale: Tests should not complete the try block naturally if they are expecting a failure. + * If the try completes normally the test will pass successfully and skip over any assertions in + * the catch block. + * If tests are not expecting exceptions, then they should remove the catch block and propagate + * the exception to the junit caller which will display the full exception to the user. + *

        + *

        + * A junit test method is identified by the annotations placed on it. It is only considered a junit + * method if it contains the annotation 'org.junit.Test'. This check doesn't examine methods called + * by a test method. It must contain the annotation. Failures are identified by the + * method call to the method 'org.junit.Assert.fail'. + *

        + *

        + * An example of how to configure the check is: + *

        + *
        + * <module name="RequireFailForTryCatchInJunitCheck"/>
        + * 
        + *

        + * which will cause a violation in the example below: + *

        + *
        + *   @Test
        + *   public void testMyCase() {
        + *     try { // violation here as try block has no 'Assert.fail()'.
        + *       verifySomeResult();
        + *     }
        + *     catch (IllegalArgumentException ex) {
        + *       assertEquals("expected exception message",
        + *           "Some message that is expected", ex.getMessage());
        + *     }
        + *   }
        + * 
        + * @author Richard Veach + * @since 1.25.0 + */ +public class RequireFailForTryCatchInJunitCheck extends AbstractCheck { + + /** + * Violation message key. + */ + public static final String MSG_KEY = "require.fail"; + + /** + * Fully qualified junit test annotation. + */ + private static final String FQ_JUNIT_TEST = "org.junit.Test"; + /** + * JUnit's fail assertion method name. + */ + private static final String FAIL = "fail"; + + /** + * {@code true} if the junit test is imported. + */ + private boolean importTest; + /** + * {@code true} if the junit assert is imported. + */ + private boolean importAssert; + /** + * {@code true} if the junit fail assertion method is statically imported. + */ + private boolean importStaticFail; + + @Override + public int[] getDefaultTokens() { + return getRequiredTokens(); + } + + @Override + public int[] getAcceptableTokens() { + return getRequiredTokens(); + } + + @Override + public int[] getRequiredTokens() { + return new int[] { + TokenTypes.IMPORT, + TokenTypes.STATIC_IMPORT, + TokenTypes.LITERAL_TRY, + }; + } + + @Override + public void beginTree(DetailAST rootAST) { + importTest = false; + importAssert = false; + importStaticFail = false; + } + + @Override + public void visitToken(DetailAST ast) { + switch (ast.getType()) { + case TokenTypes.IMPORT: + final String imprt = getImportText(ast); + + if (FQ_JUNIT_TEST.equals(imprt)) { + importTest = true; + } + if ("org.junit.Assert".equals(imprt)) { + importAssert = true; + } + break; + case TokenTypes.STATIC_IMPORT: + final String staticImprt = getImportText(ast); + + if ("org.junit.Assert.fail".equals(staticImprt)) { + importStaticFail = true; + } + break; + case TokenTypes.LITERAL_TRY: + examineTry(ast); + break; + default: + Utils.reportInvalidToken(ast.getType()); + break; + } + } + + /** + * Examines the try block for violations. + * @param ast The try block to examine. + */ + private void examineTry(DetailAST ast) { + final DetailAST method = getMethod(ast); + + if (isTestMethod(method) + && ast.findFirstToken(TokenTypes.LITERAL_CATCH) != null) { + final DetailAST last = ast.findFirstToken(TokenTypes.SLIST).getLastChild() + .getPreviousSibling(); + + if (last == null + || last.getType() != TokenTypes.SEMI + || !isValidFail(last.getPreviousSibling())) { + log(ast, MSG_KEY); + } + } + } + + /** + * Checks if the given method is a test method, defined by the junit annotation Test. + * @param method the method AST to examine. + * @return {@code true} if the method is a test method. + */ + private boolean isTestMethod(DetailAST method) { + return method != null + && ((importTest && AnnotationUtility.containsAnnotation(method, "Test")) + || AnnotationUtility.containsAnnotation(method, FQ_JUNIT_TEST)); + } + + /** + * Checks if the expression is an junit fail assertion. + * @param expression The expression to examine. + * @return {@code true} if the expression is a valid junit fail assertion. + */ + private boolean isValidFail(DetailAST expression) { + boolean result = false; + + if (expression.getFirstChild().getType() == TokenTypes.METHOD_CALL) { + final DetailAST ident = expression.getFirstChild().getFirstChild(); + + if (importAssert && ident.getType() == TokenTypes.DOT) { + final DetailAST firstChild = ident.getFirstChild(); + + result = "Assert".equals(firstChild.getText()) + && FAIL.equals(firstChild.getNextSibling().getText()); + } + else if (importStaticFail) { + result = FAIL.equals(ident.getText()); + } + } + + return result; + } + + /** + * Retrieves the method definition AST parent from the specified node, as long as it doesn't + * contain a lambda. + * @param node The node to examine. + * @return The parent method definition. + */ + private static DetailAST getMethod(DetailAST node) { + DetailAST result = null; + + for (DetailAST token = node.getParent(); token != null; token = token.getParent()) { + final int type = token.getType(); + if (type == TokenTypes.METHOD_DEF) { + result = token; + } + if (type == TokenTypes.METHOD_DEF || type == TokenTypes.LAMBDA) { + break; + } + } + + return result; + } + + /** + * Returns import text. + * + * @param ast ast node that represents import + * @return String that represents importing class + */ + private static String getImportText(DetailAST ast) { + final FullIdent imp; + if (ast.getType() == TokenTypes.IMPORT) { + imp = FullIdent.createFullIdentBelow(ast); + } + else { + imp = FullIdent.createFullIdent(ast.getFirstChild().getNextSibling()); + } + return imp.getText(); + } + +} diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnBooleanFromTernaryCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnBooleanFromTernaryCheck.java index 7482b0038c..cebaaf547d 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnBooleanFromTernaryCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnBooleanFromTernaryCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -30,6 +30,7 @@ *

        * * @author Ivan Sopov + * @since 1.8.0 */ public class ReturnBooleanFromTernaryCheck extends AbstractCheck { @@ -51,6 +52,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { final DetailAST secondBranch = ast.getLastChild(); @@ -62,4 +73,5 @@ public void visitToken(DetailAST ast) { log(ast, MSG_KEY); } } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheck.java index 20cecc460b..6b9e0fc8b2 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -21,8 +21,6 @@ import java.util.Collection; import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; import java.util.Set; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; @@ -49,7 +47,12 @@ *
      2. Methods by name ("ignoreMethodsNames" property). Note, that the "ignoreMethodsNames" * property type is a RegExp: * using this property you can list the names of ignored methods separated by comma (but you - * can also use '|' to separate different method names in usual for RegExp style).
      3. + * can also use '|' to separate different method names in usual for RegExp style). + * If the violation is on a lambda, since it has no method name, you can specify the string + * {@code null} to ignore all lambda violations for now. It should be noted, that ignoring lambdas + * this way may not always be supported as it is a hack and giving all lambdas the same name. It + * could be changed if a better way to single out individual lambdas if found. + *
      4. *
      5. Methods which linelength less than given value ("linesLimit" property). *
      6. "return" statements which depth is greater or equal to the given value ("returnDepthLimit" * property). There are few supported
        @@ -63,6 +66,7 @@ *
        * * @author Daniil Yaroslavtsev + * @since 1.8.0 */ public class ReturnCountExtendedCheck extends AbstractCheck { @@ -81,12 +85,19 @@ public class ReturnCountExtendedCheck extends AbstractCheck { "return.count.extended.ctor"; /** - * Default maximum allowed "return" literals count per method/ctor. + * A key is pointing to the warning message text in "messages.properties" + * file. + */ + public static final String MSG_KEY_LAMBDA = + "return.count.extended.lambda"; + + /** + * Default maximum allowed "return" literals count per method/ctor/lambda. */ private static final int DEFAULT_MAX_RETURN_COUNT = 1; /** - * Default number of lines of which method/ctor body may consist to be + * Default number of lines of which method/ctor/lambda body may consist to be * skipped by check. */ private static final int DEFAULT_IGNORE_METHOD_LINES_COUNT = 20; @@ -99,7 +110,7 @@ public class ReturnCountExtendedCheck extends AbstractCheck { /** * Number which defines, how many lines of code on the top of current - * processed method/ctor will be ignored by check. + * processed method/ctor/lambda will be ignored by check. */ private static final int DEFAULT_TOP_LINES_TO_IGNORE_COUNT = 5; @@ -109,12 +120,12 @@ public class ReturnCountExtendedCheck extends AbstractCheck { private Set ignoreMethodsNames = new HashSet<>(); /** - * Maximum allowed "return" literals count per method/ctor (1 by default). + * Maximum allowed "return" literals count per method/ctor/lambda (1 by default). */ private int maxReturnCount = DEFAULT_MAX_RETURN_COUNT; /** - * Maximum number of lines of which method/ctor body may consist to be + * Maximum number of lines of which method/ctor/lambda body may consist to be * skipped by check. 20 by default. */ private int ignoreMethodLinesCount = DEFAULT_IGNORE_METHOD_LINES_COUNT; @@ -125,14 +136,14 @@ public class ReturnCountExtendedCheck extends AbstractCheck { private int minIgnoreReturnDepth = DEFAULT_MIN_IGNORE_RETURN_DEPTH; /** - * Option to ignore "empty" return statements in void methods and ctors. + * Option to ignore "empty" return statements in void methods and ctors and lambdas. * "true" by default. */ private boolean ignoreEmptyReturns = true; /** * Number which defines, how many lines of code on the top of each - * processed method/ctor will be ignored by check. 5 by default. + * processed method/ctor/lambda will be ignored by check. 5 by default. */ private int topLinesToIgnoreCount = DEFAULT_TOP_LINES_TO_IGNORE_COUNT; @@ -159,7 +170,7 @@ public void setIgnoreMethodsNames(String[] ignoreMethodNames) { } /** - * Sets maximum allowed "return" literals count per method/ctor. + * Sets maximum allowed "return" literals count per method/ctor/lambda. * @param maxReturnCount - the new "maxReturnCount" property value. * @see ReturnCountExtendedCheck#maxReturnCount */ @@ -168,7 +179,7 @@ public void setMaxReturnCount(int maxReturnCount) { } /** - * Sets the maximum number of lines of which method/ctor body may consist to + * Sets the maximum number of lines of which method/ctor/lambda body may consist to * be skipped by check. * @param ignoreMethodLinesCount * - the new value of "ignoreMethodLinesCount" property. @@ -189,7 +200,7 @@ public void setMinIgnoreReturnDepth(int minIgnoreReturnDepth) { } /** - * Sets the "ignoring empty return statements in void methods and ctors" + * Sets the "ignoring empty return statements in void methods and ctors and lambdas" * option state. * @param ignoreEmptyReturns * the new "allowEmptyReturns" property value. @@ -212,16 +223,30 @@ public void setTopLinesToIgnoreCount(int topLinesToIgnoreCount) { @Override public int[] getDefaultTokens() { - return new int[] {TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, }; + return new int[] { + TokenTypes.METHOD_DEF, + TokenTypes.CTOR_DEF, + TokenTypes.LAMBDA, + }; + } + + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); } @Override - public void visitToken(final DetailAST methodDefNode) { - final DetailAST openingBrace = methodDefNode + public void visitToken(final DetailAST node) { + final DetailAST openingBrace = node .findFirstToken(TokenTypes.SLIST); - final String methodName = getMethodName(methodDefNode); + final String nodeName = getMethodName(node); if (openingBrace != null - && !matches(methodName, ignoreMethodsNames)) { + && !matches(nodeName, ignoreMethodsNames)) { final DetailAST closingBrace = openingBrace.getLastChild(); int curMethodLinesCount = getLinesCount(openingBrace, @@ -232,34 +257,48 @@ public void visitToken(final DetailAST methodDefNode) { } if (curMethodLinesCount >= ignoreMethodLinesCount) { - - final int mCurReturnCount = getReturnCount(methodDefNode, + final int mCurReturnCount = getReturnCount(node, openingBrace); if (mCurReturnCount > maxReturnCount) { - final String mKey; - - if (methodDefNode.getType() == TokenTypes.METHOD_DEF) { - mKey = MSG_KEY_METHOD; - } - else { - mKey = MSG_KEY_CTOR; - } + logViolation(node, nodeName, mCurReturnCount); + } + } + } + } - final DetailAST methodNameToken = methodDefNode - .findFirstToken(TokenTypes.IDENT); + /** + * Reports violation to user based on the parameters given. + * @param node The node that the violation is on. + * @param nodeName The name given to the node. + * @param mCurReturnCount The return count violation amount. + */ + private void logViolation(DetailAST node, String nodeName, int mCurReturnCount) { + if (node.getType() == TokenTypes.LAMBDA) { + // lambdas have no name + log(node, MSG_KEY_LAMBDA, mCurReturnCount, maxReturnCount); + } + else { + final DetailAST nodeNameToken = node + .findFirstToken(TokenTypes.IDENT); + final String mKey; - log(methodNameToken, mKey, - methodName, mCurReturnCount, - maxReturnCount); - } + if (node.getType() == TokenTypes.METHOD_DEF) { + mKey = MSG_KEY_METHOD; } + else { + mKey = MSG_KEY_CTOR; + } + + log(nodeNameToken, mKey, + nodeName, mCurReturnCount, + maxReturnCount); } } /** - * Gets the "return" statements count for given method/ctor and saves the - * last "return" statement DetailAST node for given method/ctor body. Uses + * Gets the "return" statements count for given method/ctor/lambda and saves the + * last "return" statement DetailAST node for given method/ctor/lambda body. Uses * an iterative algorithm. * @param methodOpeningBrace * a DetailAST node that points to the current method`s opening @@ -275,22 +314,15 @@ private int getReturnCount(final DetailAST methodDefNode, DetailAST curNode = methodOpeningBrace; - while (curNode != null) { - - // before node visiting - if (curNode.getType() == TokenTypes.RCURLY - && curNode.getParent() == methodOpeningBrace) { - // stop at closing brace - break; - } - else { - if (curNode.getType() == TokenTypes.LITERAL_RETURN - && getDepth(methodDefNode, curNode) < minIgnoreReturnDepth - && shouldEmptyReturnStatementBeCounted(curNode) - && getLinesCount(methodOpeningBrace, - curNode) > topLinesToIgnoreCount) { - result++; - } + // stop at closing brace + while (curNode.getType() != TokenTypes.RCURLY + || curNode.getParent() != methodOpeningBrace) { + if (curNode.getType() == TokenTypes.LITERAL_RETURN + && getDepth(methodDefNode, curNode) < minIgnoreReturnDepth + && shouldEmptyReturnStatementBeCounted(curNode) + && getLinesCount(methodOpeningBrace, + curNode) > topLinesToIgnoreCount) { + result++; } // before node leaving @@ -300,11 +332,13 @@ && getLinesCount(methodOpeningBrace, // skip nested methods (UI listeners, Runnable.run(), etc.) if (type == TokenTypes.METHOD_DEF // skip anonymous classes - || type == TokenTypes.CLASS_DEF) { + || type == TokenTypes.CLASS_DEF + // skip lambdas which is like an anonymous class/method + || type == TokenTypes.LAMBDA) { nextNode = curNode.getNextSibling(); } - while ((curNode != null) && (nextNode == null)) { + while (nextNode == null) { // leave the visited Node nextNode = curNode.getNextSibling(); if (nextNode == null) { @@ -371,12 +405,13 @@ private static int getDepth(DetailAST methodDefNode, */ private static String getMethodName(DetailAST methodDefNode) { String result = null; - for (DetailAST curNode : getChildren(methodDefNode)) { - if (curNode.getType() == TokenTypes.IDENT) { - result = curNode.getText(); - break; - } + final DetailAST ident = methodDefNode.findFirstToken(TokenTypes.IDENT); + + // lambdas don't have a name + if (ident != null && methodDefNode.getType() != TokenTypes.LAMBDA) { + result = ident.getText(); } + return result; } @@ -393,23 +428,6 @@ private static int getLinesCount(DetailAST beginAst, DetailAST endAST) { return endAST.getLineNo() - beginAst.getLineNo(); } - /** - * Gets all the children which are one level below on the current DetailAST - * parent node. - * @param node - * Current parent node. - * @return The list of children one level below on the current parent node. - */ - private static List getChildren(final DetailAST node) { - final List result = new LinkedList<>(); - DetailAST curNode = node.getFirstChild(); - while (curNode != null) { - result.add(curNode); - curNode = curNode.getNextSibling(); - } - return result; - } - /** * Matches string to given list of RegExp patterns. * @@ -420,10 +438,16 @@ private static List getChildren(final DetailAST node) { * @return true if given string could be fully matched by one of given patterns, false otherwise */ private static boolean matches(String string, Collection patterns) { + String match = string; + + if (match == null) { + match = "null"; + } + boolean result = false; if (!patterns.isEmpty()) { for (String pattern : patterns) { - if (string.matches(pattern)) { + if (match.matches(pattern)) { result = true; break; } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnNullInsteadOfBooleanCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnNullInsteadOfBooleanCheck.java index fff5b20827..4da752a14d 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnNullInsteadOfBooleanCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnNullInsteadOfBooleanCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -34,6 +34,7 @@ *

        * * @author Ivan Sopov + * @since 1.8.0 */ public class ReturnNullInsteadOfBooleanCheck extends AbstractCheck { @@ -55,6 +56,11 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + @Override public int[] getRequiredTokens() { return new int[] { @@ -105,4 +111,5 @@ public void leaveToken(DetailAST ast) { break; } } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationCheck.java index 48cb94016a..8320124928 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -39,7 +39,7 @@ * , for example:

        * *
        - * <module name="SimpleAccesorNameNotationCheck"> <
        + * <module name="SimpleAccessorNameNotationCheck"> <
          * property name="prefix" value="m_"/>
          * </module>
          * 
        @@ -47,8 +47,10 @@ * * @author Hidoyatov Victor * @author Ilja Dubinin + * @since 1.9.0 */ public class SimpleAccessorNameNotationCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. @@ -91,24 +93,34 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST methodDef) { - final String methodName = methodDef.findFirstToken(TokenTypes.IDENT).getText(); if (hasBody(methodDef) && !isMethodAtAnonymousClass(methodDef)) { + final String methodName = methodDef.findFirstToken(TokenTypes.IDENT).getText(); if (methodName.startsWith(BOOLEAN_GETTER_PREFIX)) { if (!isGetterCorrect(methodDef, methodName.substring(BOOLEAN_GETTER_PREFIX.length()))) { - log(methodDef.getLineNo(), MSG_KEY_GETTER); + log(methodDef, MSG_KEY_GETTER); } } else if (methodName.startsWith(SETTER_PREFIX)) { if (!isSetterCorrect(methodDef, methodName.substring(SETTER_PREFIX.length()))) { - log(methodDef.getLineNo(), MSG_KEY_SETTER); + log(methodDef, MSG_KEY_SETTER); } } else if (methodName.startsWith(GETTER_PREFIX)) { if (!isGetterCorrect(methodDef, methodName.substring(GETTER_PREFIX.length()))) { - log(methodDef.getLineNo(), MSG_KEY_GETTER); + log(methodDef, MSG_KEY_GETTER); } } } @@ -127,17 +139,14 @@ else if (methodName.startsWith(GETTER_PREFIX)) { private boolean isSetterCorrect(DetailAST methodDef, String methodName) { final DetailAST methodType = methodDef.findFirstToken(TokenTypes.TYPE); boolean result = true; - if (methodType.branchContains(TokenTypes.LITERAL_VOID)) { - + if (methodType.findFirstToken(TokenTypes.LITERAL_VOID) != null) { DetailAST currentVerifiedTop = methodDef.findFirstToken(TokenTypes.SLIST); if (containsOnlyExpression(currentVerifiedTop)) { - currentVerifiedTop = currentVerifiedTop.getFirstChild(); - final boolean containsOnlyOneAssignment = currentVerifiedTop.getChildCount() == 1 - && currentVerifiedTop.getFirstChild().getType() == TokenTypes.ASSIGN; + final boolean containsOnlyOneAssignment = currentVerifiedTop.getFirstChild() + .getType() == TokenTypes.ASSIGN; if (containsOnlyOneAssignment) { - currentVerifiedTop = currentVerifiedTop.getFirstChild(); final DetailAST parameters = methodDef.findFirstToken(TokenTypes.PARAMETERS); @@ -147,7 +156,6 @@ private boolean isSetterCorrect(DetailAST methodDef, String methodName) { if (nameOfSettingField != null && verifyFieldAndMethodName(nameOfSettingField, methodName)) { - result = false; } } @@ -171,22 +179,18 @@ private boolean isGetterCorrect(DetailAST methodDef, String methodName) { final DetailAST parameters = methodDef.findFirstToken(TokenTypes.PARAMETERS); boolean result = true; if (parameters.getChildCount() == 0) { - DetailAST currentVerifiedTop = methodDef.findFirstToken(TokenTypes.SLIST); if (containsOnlyReturn(currentVerifiedTop)) { - currentVerifiedTop = currentVerifiedTop.getFirstChild(); if (isCorrectReturn(currentVerifiedTop)) { - currentVerifiedTop = currentVerifiedTop.getFirstChild(); final String nameOfGettingField = getNameOfGettingField(currentVerifiedTop); if (nameOfGettingField != null && verifyFieldAndMethodName(nameOfGettingField, methodName)) { - result = false; } } @@ -207,8 +211,7 @@ && verifyFieldAndMethodName(nameOfGettingField, private static boolean containsOnlyExpression(DetailAST objectBlock) { //three child: EXPR, SEMI and RCURLY return objectBlock.getChildCount() == EXPRESSION_BLOCK_CHILD_COUNT - && objectBlock.getFirstChild().getType() == TokenTypes.EXPR - && objectBlock.findFirstToken(TokenTypes.SEMI) != null; + && objectBlock.getFirstChild().getType() == TokenTypes.EXPR; } /** @@ -225,32 +228,23 @@ private static String getNameOfSettingField(DetailAST assign, DetailAST parameters) { String nameOfSettingField = null; - final DetailAST assigningFirstChild = assign.getFirstChild(); - if (assign.getChildCount() == 2 && assign.getLastChild().getType() == TokenTypes.IDENT) { + final DetailAST assigningFirstChild = assign.getFirstChild(); if (assigningFirstChild.getType() == TokenTypes.IDENT) { - nameOfSettingField = assigningFirstChild.getText(); if (checkNameOfParameters(parameters, nameOfSettingField)) { nameOfSettingField = null; } - } else { if (assigningFirstChild.getType() == TokenTypes.DOT) { - - if (assigningFirstChild.getChildCount() == 2 - && "this".equals(assigningFirstChild - .getFirstChild().getText()) - && assigningFirstChild.getLastChild().getType() == TokenTypes.IDENT) { - + if ("this".equals(assigningFirstChild.getFirstChild().getText())) { nameOfSettingField = assigningFirstChild.getLastChild() .getText(); } - } } } @@ -292,14 +286,13 @@ private static boolean containsOnlyReturn(DetailAST methodBody) { * Return true when getter has correct arguments of return. *

        * @param literalReturn - * - DeailAST contains LITERAL_RETURN + * - DetailAST contains LITERAL_RETURN * @return - true when getter has correct return. */ private static boolean isCorrectReturn(DetailAST literalReturn) { //two child: EXPR and SEMI return literalReturn.getChildCount() == 2 - && literalReturn.getFirstChild().getType() == TokenTypes.EXPR - && literalReturn.getLastChild().getType() == TokenTypes.SEMI; + && literalReturn.getFirstChild().getType() == TokenTypes.EXPR; } /** @@ -317,16 +310,12 @@ private static String getNameOfGettingField(DetailAST expr) { final DetailAST exprFirstChild = expr.getFirstChild(); if (exprFirstChild.getType() == TokenTypes.IDENT) { - nameOfGettingField = exprFirstChild.getText(); - } else { if (exprFirstChild.getType() == TokenTypes.DOT && exprFirstChild.getChildCount() == 2 - && exprFirstChild.getFirstChild().getType() == TokenTypes.LITERAL_THIS - && exprFirstChild.getLastChild().getType() == TokenTypes.IDENT) { - + && exprFirstChild.getFirstChild().getType() == TokenTypes.LITERAL_THIS) { nameOfGettingField = exprFirstChild.getLastChild().getText(); } } @@ -340,26 +329,23 @@ private static String getNameOfGettingField(DetailAST expr) { * Return true when name of the field is not contained in parameters of the * setter method. *

        - * @param paramrters + * @param parameters * - DetailAST contains parameters of the setter. * @param fieldName * - name of the field. * @return true when name of the field is not contained in parameters. */ - private static boolean checkNameOfParameters(DetailAST paramrters, + private static boolean checkNameOfParameters(DetailAST parameters, String fieldName) { - boolean isNameOfParameter = false; - final int parametersChildCount = paramrters.getChildCount(); + final int parametersChildCount = parameters.getChildCount(); - final DetailAST parameterDef = paramrters + final DetailAST parameterDef = parameters .findFirstToken(TokenTypes.PARAMETER_DEF); for (int i = 0; i < parametersChildCount && !isNameOfParameter; i++) { - isNameOfParameter = parameterDef.findFirstToken(TokenTypes.IDENT).getText() .equals(fieldName); - } return isNameOfParameter; @@ -389,4 +375,5 @@ private static boolean hasBody(DetailAST methodDef) { final DetailAST body = methodDef.findFirstToken(TokenTypes.SLIST); return body != null; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SingleBreakOrContinueCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SingleBreakOrContinueCheck.java index 005580e175..75946dffc9 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SingleBreakOrContinueCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SingleBreakOrContinueCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -109,6 +109,7 @@ *
      * * @author Yasser Aziza + * @since 1.18.0 */ public class SingleBreakOrContinueCheck extends AbstractCheck { @@ -125,10 +126,20 @@ public int[] getDefaultTokens() { TokenTypes.LITERAL_DO, }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { if (getNumberOfContinueAndBreaks(ast.getFirstChild()) > 1) { - log(ast.getLineNo(), MSG_KEY); + log(ast, MSG_KEY); } } @@ -171,4 +182,5 @@ private static boolean shouldIgnore(DetailAST node) { || TokenTypes.LITERAL_WHILE == node.getType() || TokenTypes.LITERAL_DO == node.getType(); } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/TernaryPerExpressionCountCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/TernaryPerExpressionCountCheck.java index 13403c5ca7..be2484b771 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/TernaryPerExpressionCountCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/TernaryPerExpressionCountCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -44,9 +44,12 @@ * System.out.println(x); * * - * Output for code above is "D", but more obvious would be "BC".
      - * - * Check has following properties:
      + *

      + * Output for code above is "D", but more obvious would be "BC". + *

      + *

      + * Check has following properties: + *

      *
        *
      • maxTernaryPerExpressionCount - limit of ternary operators per * expression
        @@ -73,8 +76,10 @@ * procedureNameToUse + "("; * * + *

        * When using ignoreIsolatedTernaryOnLine (value = true), even without
        - * ignoreTernaryOperatorsInBraces option Check won't warn on code below:
        + * ignoreTernaryOperatorsInBraces option Check won't warn on code below: + *

        * *
          * int a = (d == 5) ? d : f
        @@ -83,6 +88,7 @@
          * 
        * * @author Aleksey Nesterenko + * @since 1.12.0 */ public class TernaryPerExpressionCountCheck extends AbstractCheck { @@ -93,12 +99,22 @@ public class TernaryPerExpressionCountCheck extends AbstractCheck { */ public static final String MSG_KEY = "ternary.per.expression.count"; + /** Default limit of ternary operators per expression. */ private static final int DEFAULT_MAX_TERNARY_PER_EXPRESSION_COUNT = 1; + /** Limit of ternary operators per expression. */ private int maxTernaryPerExpressionCount = DEFAULT_MAX_TERNARY_PER_EXPRESSION_COUNT; + /** + * If true Check will ignore ternary operators in braces (braces explicitly + * set priority level). + */ private boolean ignoreTernaryOperatorsInBraces = true; + /** + * If true Check will ignore one line ternary operators, if only it is + * places in line alone. + */ private boolean ignoreIsolatedTernaryOnLine = true; @Override @@ -108,6 +124,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + /** * Sets the maximum number of ternary operators, default value = 1. * @@ -143,7 +169,6 @@ public void setIgnoreIsolatedTernaryOnLine(boolean ignoreIsolatedTernaryOnLine) @Override public void visitToken(DetailAST expressionNode) { - final List questionNodes = getQuestionNodes(expressionNode); if (questionNodes.size() > maxTernaryPerExpressionCount) { @@ -160,7 +185,6 @@ public void visitToken(DetailAST expressionNode) { * List of question nodes */ private List getQuestionNodes(DetailAST expressionNode) { - final List questionNodes = new LinkedList<>(); DetailAST currentNode = expressionNode; @@ -172,7 +196,6 @@ private List getQuestionNodes(DetailAST expressionNode) { && !isSkipTernaryOperator(currentNode)) { questionNodes.add(currentNode); } - } while (currentNode != null); return questionNodes; @@ -259,4 +282,5 @@ private static DetailAST getNextNode(DetailAST expressionNode, return toVisit; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UnnecessaryParenthesesExtendedCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UnnecessaryParenthesesExtendedCheck.java index 165ba492bb..ac156c56df 100755 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UnnecessaryParenthesesExtendedCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UnnecessaryParenthesesExtendedCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,7 +19,6 @@ package com.github.sevntu.checkstyle.checks.coding; -import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; @@ -38,7 +37,7 @@ *

        * The check is not "type aware", that is to say, it can't tell if parentheses * are unnecessary based on the types in an expression. It also doesn't know - * about operator precedence and associatvity; therefore it won't catch + * about operator precedence and associativity; therefore it won't catch * something like *

        *
        @@ -51,8 +50,10 @@
          *
          * @author Eric Roe
          * @author Antonenko Dmitriy
        + * @since 1.8.0
          */
         public class UnnecessaryParenthesesExtendedCheck extends AbstractCheck {
        +
             /**Warning message key.*/
             public static final String MSG_KEY_ASSIGN = "unnecessary.paren.assign";
             /**Warning message key.*/
        @@ -153,51 +154,55 @@ public int[] getDefaultTokens() {
                 };
             }
         
        +    @Override
        +    public int[] getAcceptableTokens() {
        +        return getDefaultTokens();
        +    }
        +
        +    @Override
        +    public int[] getRequiredTokens() {
        +        return getDefaultTokens();
        +    }
        +
             @Override
             public void visitToken(DetailAST ast) {
                 final int type = ast.getType();
        -        final boolean surrounded = isSurrounded(ast);
                 final DetailAST parent = ast.getParent();
         
        -        if ((type == TokenTypes.ASSIGN)
        -            && (parent.getType() == TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR)) {
        -            // shouldn't process assign in annotation pairs
        -            return;
        -        }
        -
        -        // An identifier surrounded by parentheses.
        -        if (surrounded && (type == TokenTypes.IDENT)) {
        -            parentToSkip = ast.getParent();
        -            log(ast, MSG_KEY_IDENT, ast.getText());
        -            return;
        -        }
        +        // shouldn't process assign in annotation pairs
        +        if ((type != TokenTypes.ASSIGN)
        +            || (parent.getType() != TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR)) {
        +            final boolean surrounded = isSurrounded(ast);
         
        -        // A literal (numeric or string) surrounded by parentheses.
        -        if (surrounded && inTokenList(type, LITERALS)) {
        -            parentToSkip = ast.getParent();
        -            if (type == TokenTypes.STRING_LITERAL) {
        -                log(ast, MSG_KEY_STRING,
        -                    chopString(ast.getText()));
        +            // An identifier surrounded by parentheses.
        +            if (surrounded && (type == TokenTypes.IDENT)) {
        +                parentToSkip = ast.getParent();
        +                log(ast, MSG_KEY_IDENT, ast.getText());
                     }
        -            else {
        -                log(ast, MSG_KEY_LITERAL, ast.getText());
        +            // A literal (numeric or string) surrounded by parentheses.
        +            else if (surrounded && inTokenList(type, LITERALS)) {
        +                parentToSkip = ast.getParent();
        +                if (type == TokenTypes.STRING_LITERAL) {
        +                    log(ast, MSG_KEY_STRING,
        +                        chopString(ast.getText()));
        +                }
        +                else {
        +                    log(ast, MSG_KEY_LITERAL, ast.getText());
        +                }
                     }
        -            return;
        -        }
        -
        -        // The rhs of an assignment surrounded by parentheses.
        -        if (inTokenList(type, ASSIGNMENTS)) {
        -            assignDepth++;
        -            final DetailAST last = ast.getLastChild();
        -            if (last.getType() == TokenTypes.RPAREN) {
        -                final DetailAST subtree = ast.getFirstChild().getNextSibling()
        -                    .getNextSibling();
        -                final int subtreeType = subtree.getType();
        -                if (!ignoreCalculationOfBooleanVariables || !inTokenList(
        -                    subtreeType, EQUALS)) {
        -                    log(ast, MSG_KEY_ASSIGN);
        +            // The rhs of an assignment surrounded by parentheses.
        +            else if (inTokenList(type, ASSIGNMENTS)) {
        +                assignDepth++;
        +                final DetailAST last = ast.getLastChild();
        +                if (last.getType() == TokenTypes.RPAREN) {
        +                    final DetailAST subtree = ast.getFirstChild().getNextSibling()
        +                        .getNextSibling();
        +                    final int subtreeType = subtree.getType();
        +                    if (!ignoreCalculationOfBooleanVariables || !inTokenList(
        +                        subtreeType, EQUALS)) {
        +                        log(ast, MSG_KEY_ASSIGN);
        +                    }
                         }
        -
                     }
                 }
             }
        @@ -212,39 +217,7 @@ public void leaveToken(DetailAST ast) {
                     || (parent.getType() != TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR)) {
                     // An expression is surrounded by parentheses.
                     if (type == TokenTypes.EXPR) {
        -
        -                // If 'mParentToSkip' == 'aAST', then we've already logged a
        -                // warning about an immediate child node in visitToken, so we don't
        -                // need to log another one here.
        -
        -                if ((parentToSkip != ast) && exprSurrounded(ast)) {
        -                    if (assignDepth >= 1) {
        -                        if (!ignoreCalculationOfBooleanVariables || !inTokenList(
        -                            subtreeType(ast), EQUALS)) {
        -                            log(ast, MSG_KEY_ASSIGN);
        -                        }
        -                    }
        -                    else if (ast.getParent().getType()
        -                        == TokenTypes.LITERAL_RETURN) {
        -                        if (!ignoreCalculationOfBooleanVariablesWithReturn
        -                                || !inTokenList(subtreeType(ast), EQUALS)) {
        -                            log(ast, MSG_KEY_RETURN);
        -                        }
        -                    }
        -                    else if (ast.getParent().getType()
        -                            == TokenTypes.LITERAL_ASSERT) {
        -                        if (!ignoreCalculationOfBooleanVariablesWithAssert
        -                                || !inTokenList(subtreeType(ast), EQUALS)) {
        -                            log(ast, MSG_KEY_EXPR);
        -                        }
        -                    }
        -                    else {
        -                        if (!ignoreCalculationOfBooleanVariables || !inTokenList(
        -                            subtreeType(ast), EQUALS)) {
        -                            log(ast, MSG_KEY_EXPR);
        -                        }
        -                    }
        -                }
        +                leaveTokenExpression(ast);
         
                         parentToSkip = null;
                     }
        @@ -256,6 +229,45 @@ else if (inTokenList(type, ASSIGNMENTS)) {
                 }
             }
         
        +    /**
        +     * Examines the expression AST for violations.
        +     * @param ast The AST to examine.
        +     */
        +    private void leaveTokenExpression(DetailAST ast) {
        +        // If 'mParentToSkip' == 'aAST', then we've already logged a
        +        // warning about an immediate child node in visitToken, so we don't
        +        // need to log another one here.
        +
        +        if ((parentToSkip != ast) && exprSurrounded(ast)) {
        +            if (assignDepth >= 1) {
        +                if (!ignoreCalculationOfBooleanVariables || !inTokenList(
        +                    subtreeType(ast), EQUALS)) {
        +                    log(ast, MSG_KEY_ASSIGN);
        +                }
        +            }
        +            else if (ast.getParent().getType()
        +                == TokenTypes.LITERAL_RETURN) {
        +                if (!ignoreCalculationOfBooleanVariablesWithReturn
        +                        || !inTokenList(subtreeType(ast), EQUALS)) {
        +                    log(ast, MSG_KEY_RETURN);
        +                }
        +            }
        +            else if (ast.getParent().getType()
        +                    == TokenTypes.LITERAL_ASSERT) {
        +                if (!ignoreCalculationOfBooleanVariablesWithAssert
        +                        || !inTokenList(subtreeType(ast), EQUALS)) {
        +                    log(ast, MSG_KEY_EXPR);
        +                }
        +            }
        +            else {
        +                if (!ignoreCalculationOfBooleanVariables || !inTokenList(
        +                    subtreeType(ast), EQUALS)) {
        +                    log(ast, MSG_KEY_EXPR);
        +                }
        +            }
        +        }
        +    }
        +
             /**
              * Tests if the given DetailAST is surrounded by parentheses.
              * In short, does aAST have a previous sibling whose type is
        @@ -271,8 +283,7 @@ private static boolean isSurrounded(DetailAST ast) {
                 final DetailAST next = ast.getNextSibling();
         
                 return (prev != null) && (next != null)
        -            && (prev.getType() == TokenTypes.LPAREN)
        -            && (next.getType() == TokenTypes.RPAREN);
        +            && (prev.getType() == TokenTypes.LPAREN);
             }
         
             /**
        @@ -285,15 +296,7 @@ private static boolean isSurrounded(DetailAST ast) {
              *         equal to TokenTypes.EXPR.
              */
             private static boolean exprSurrounded(DetailAST ast) {
        -        boolean surrounded = false;
        -        if (ast.getChildCount() >= MIN_CHILDREN_FOR_MATCH) {
        -            final AST n1 = ast.getFirstChild();
        -            final AST nn = ast.getLastChild();
        -
        -            surrounded = (n1.getType() == TokenTypes.LPAREN)
        -                && (nn.getType() == TokenTypes.RPAREN);
        -        }
        -        return surrounded;
        +        return ast.getChildCount() >= MIN_CHILDREN_FOR_MATCH;
             }
         
             /**
        @@ -324,10 +327,14 @@ private static boolean inTokenList(int type, int[] tokens) {
              *         MAX_QUOTED_LENGTH; otherwise aString.
              */
             private static String chopString(String string) {
        +        final String result;
                 if (string.length() > MAX_QUOTED_LENGTH) {
        -            return string.substring(0, MAX_QUOTED_LENGTH) + "...\"";
        +            result = string.substring(0, MAX_QUOTED_LENGTH) + "...\"";
        +        }
        +        else {
        +            result = string;
                 }
        -        return string;
        +        return result;
             }
         
             /**
        @@ -381,4 +388,5 @@ public final void setIgnoreCalculationOfBooleanVariablesWithAssert(
                 this.ignoreCalculationOfBooleanVariablesWithAssert =
                     ignoreCalculationOfBooleanVariablesWithAssert;
             }
        +
         }
        diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UselessSingleCatchCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UselessSingleCatchCheck.java
        index 15fdca1c05..322f609a56 100644
        --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UselessSingleCatchCheck.java
        +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UselessSingleCatchCheck.java
        @@ -1,6 +1,6 @@
         ////////////////////////////////////////////////////////////////////////////////
         // checkstyle: Checks Java source code for adherence to a set of rules.
        -// Copyright (C) 2001-2016 the original author or authors.
        +// Copyright (C) 2001-2018 the original author or authors.
         //
         // This library is free software; you can redistribute it and/or
         // modify it under the terms of the GNU Lesser General Public
        @@ -37,8 +37,10 @@
          *  
        * * @author Zuy Alexey + * @since 1.13.0 */ public class UselessSingleCatchCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. @@ -52,6 +54,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST tryBlockNode) { final int catchBlocksCount = tryBlockNode.getChildCount(TokenTypes.LITERAL_CATCH); @@ -78,10 +90,10 @@ && isSimpleRethrow(firstStatementNode)) { /** * Determines whether throw node is of form - * throw exceptionObject; + * throw exceptionObject;. * @param throwNode * node of type TokenTypes.LITERAL_THROW - * @return wheather this throw node is of specified form + * @return whether this throw node is of specified form */ private static boolean isSimpleRethrow(DetailAST throwNode) { final DetailAST exprNode = throwNode.findFirstToken(TokenTypes.EXPR); @@ -91,7 +103,7 @@ private static boolean isSimpleRethrow(DetailAST throwNode) { } /** - * Gets catch parameter name + * Gets catch parameter name. * @param catchNode * node of type TokenTypes.LITERAL_CATCH * @return catch parameter name diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UselessSuperCtorCallCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UselessSuperCtorCallCheck.java index 97071f8372..ba154c052a 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UselessSuperCtorCallCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/UselessSuperCtorCallCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -32,6 +32,7 @@ *

        *

        * Case 1. no-argument "super()" is called from class ctor if class is not derived, for example: + *

        *
          * 
          * class Dummy {
        @@ -45,6 +46,7 @@
          * 

        * Case 2. no-argument "super()" is called without parameters from class ctor if class is * derived, for example: + *

        *
          * 
          * class Derived extends Base {
        @@ -67,6 +69,7 @@
          * violations when "super()" called inside derived class. This option defaults to "false".
          * If for example this option set to "true", then Check will not generate violation for
          * cases like following:
        + * 

        *
          * 
          * class Base {
        @@ -87,9 +90,10 @@
          * Check will not generate violation when "super()" called inside class ctor when class
          * has multiple public ctors(however, setting this option to "true" will not prevent Check
          * from logging violation if class does not extend anything). This option defaults to "false".
        - * This option may be usefull for cases in which class`s ctors just forward its arguments to
        + * This option may be useful for cases in which class`s ctors just forward its arguments to
          * super ctors, thus removing "super()" in this case will make default ctors look not like
          * others. For example:
        + * 

        *
          * 
          * class Base {
        @@ -128,6 +132,7 @@
          * 

        * Checkstyle configuration example with options "allowCallToNoArgsSuperCtor" and * "allowCallToNoArgsSuperCtorIfMultiplePublicCtor" set to true. + *

        *
          *   <module name="UselessSuperCtorCallCheck">
          *     <property name="allowCallToNoArgsSuperCtor" value="true"/>
        @@ -136,8 +141,10 @@
          * 
        * * @author Zuy Alexey + * @since 1.13.0 */ public class UselessSuperCtorCallCheck extends AbstractCheck { + /** * Violation message key. */ @@ -188,6 +195,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST aSuperCallNode) { if (getSuperCallArgsCount(aSuperCallNode) == 0) { @@ -269,7 +286,7 @@ private static int getClassPublicCtorCount(DetailAST aClassDefNode) { } /** - * Checks whether given ctor is public + * Checks whether given ctor is public. * @param aCtorDefNode * a ctor definition node(TokenTypes.CTOR_DEF) * @return true, if given ctor is public diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/WhitespaceBeforeArrayInitializerCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/WhitespaceBeforeArrayInitializerCheck.java index 35a71938cc..91b7b2aa51 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/WhitespaceBeforeArrayInitializerCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/WhitespaceBeforeArrayInitializerCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -36,14 +36,18 @@ * }; *
        * + *

        * This example is valid too: + *

        * *
          * int[] tab = new int[]
          *                 {0, 1, 2, 3}
          * 
        * + *

        * But this violates check: + *

        * *
          * int[] ints = new int[]{0, 1, 2, 3};
        @@ -51,6 +55,7 @@
          *
          *
          * @author liscju
        + * @since 1.14.0
          */
         public class WhitespaceBeforeArrayInitializerCheck extends AbstractCheck {
         
        @@ -64,11 +69,21 @@ public int[] getDefaultTokens() {
                 return new int[] {TokenTypes.ARRAY_INIT};
             }
         
        +    @Override
        +    public int[] getAcceptableTokens() {
        +        return getDefaultTokens();
        +    }
        +
        +    @Override
        +    public int[] getRequiredTokens() {
        +        return getDefaultTokens();
        +    }
        +
             @Override
             public void visitToken(DetailAST ast) {
                 final DetailAST previousAst = getPreviousAst(ast);
                 if (!areTokensSeparatedByWhitespace(previousAst, ast) && isNestedArrayInitializer(ast)) {
        -            log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY);
        +            log(ast, MSG_KEY);
                 }
             }
         
        @@ -120,4 +135,5 @@ private static DetailAST getPreviousAst(DetailAST ast) {
                 }
                 return previousAst;
             }
        +
         }
        diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/package-info.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/package-info.java
        index 13b3be2f81..4f344ef7d3 100644
        --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/package-info.java
        +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/package-info.java
        @@ -1,6 +1,6 @@
         ////////////////////////////////////////////////////////////////////////////////
         // checkstyle: Checks Java source code for adherence to a set of rules.
        -// Copyright (C) 2001-2016 the original author or authors.
        +// Copyright (C) 2001-2018 the original author or authors.
         //
         // This library is free software; you can redistribute it and/or
         // modify it under the terms of the GNU Lesser General Public
        diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionCheck.java
        index 8a650787df..1b0c5c9a64 100644
        --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionCheck.java
        +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionCheck.java
        @@ -1,6 +1,6 @@
         ////////////////////////////////////////////////////////////////////////////////
         // checkstyle: Checks Java source code for adherence to a set of rules.
        -// Copyright (C) 2001-2016 the original author or authors.
        +// Copyright (C) 2001-2018 the original author or authors.
         //
         // This library is free software; you can redistribute it and/or
         // modify it under the terms of the GNU Lesser General Public
        @@ -81,6 +81,7 @@
          * 

        * * @author Aleksey Nesterenko + * @since 1.13.0 */ public class AvoidConditionInversionCheck extends AbstractCheck { @@ -118,7 +119,7 @@ public class AvoidConditionInversionCheck extends AbstractCheck { /** * If true - Check only puts violation on conditions with * - * relational operands + * relational operands. */ private boolean applyOnlyToRelationalOperands; @@ -127,7 +128,6 @@ public class AvoidConditionInversionCheck extends AbstractCheck { * @param applyOnlyToRelationalOperands The new value for the field. */ public void setApplyOnlyToRelationalOperands(boolean applyOnlyToRelationalOperands) { - this.applyOnlyToRelationalOperands = applyOnlyToRelationalOperands; } @@ -143,16 +143,22 @@ public int[] getDefaultTokens() { } @Override - public void visitToken(DetailAST ast) { + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + + @Override + public void visitToken(DetailAST ast) { final DetailAST expressionAst = ast.findFirstToken(TokenTypes.EXPR); switch (ast.getType()) { - case TokenTypes.LITERAL_RETURN: - if (!isEmptyReturn(ast)) { - final DetailAST inversionAst = getInversion(expressionAst); if (isAvoidableInversion(inversionAst)) { @@ -160,29 +166,26 @@ public void visitToken(DetailAST ast) { } } break; + case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_IF: - final DetailAST invertedAst = getInversion(expressionAst); - if (isAvoidableInversion(invertedAst)) { - log(invertedAst); } break; - case TokenTypes.FOR_CONDITION: + case TokenTypes.FOR_CONDITION: if (!isEmptyForCondition(ast)) { - final DetailAST inversionAst = getInversion(expressionAst); if (isAvoidableInversion(inversionAst)) { - log(inversionAst); } } break; + default: Utils.reportInvalidToken(ast.getType()); break; @@ -190,54 +193,50 @@ public void visitToken(DetailAST ast) { } /** - * Checks if return statement is not empty + * Checks if return statement is not empty. * @param returnAst * Node of type * {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#LITERAL_RETURN} * @return true if the return is empty. */ private static boolean isEmptyReturn(DetailAST returnAst) { - return returnAst.findFirstToken(TokenTypes.EXPR) == null; } /** - * Checks if condition in for-loop is not empty + * Checks if condition in for-loop is not empty. * @param forConditionAst * Node of type {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#FOR_CONDITION} * @return true if the for condition is empty. */ private static boolean isEmptyForCondition(DetailAST forConditionAst) { - return forConditionAst.getFirstChild() == null; } /** - * Gets inversion node of condition if one exists + * Gets inversion node of condition if one exists. * @param expressionAst * Node of type {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#EXPR} * @return Node of type {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#LNOT} * if exists, else - null */ private static DetailAST getInversion(DetailAST expressionAst) { - return expressionAst.findFirstToken(TokenTypes.LNOT); } /** - * Checks if current inversion is avoidable according to Check's properties + * Checks if current inversion is avoidable according to Check's properties. * @param inversionAst * Node of type {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#LNOT} * @return true if the inversion is avoidable. */ private boolean isAvoidableInversion(DetailAST inversionAst) { - return inversionAst != null && !isSkipCondition(inversionAst); } /** * Checks if current inverted condition has to be skipped by Check, - * it depends from user-defined property "applyOnlyToRelationalOperands" + * it depends from user-defined property "applyOnlyToRelationalOperands". * if it's true - Check will ignore inverted conditions with * non-relational operands * @param inversionConditionAst @@ -245,7 +244,6 @@ private boolean isAvoidableInversion(DetailAST inversionAst) { * @return true if token can be skipped. */ private boolean isSkipCondition(DetailAST inversionConditionAst) { - return (applyOnlyToRelationalOperands && !containsRelationalOperandsOnly(inversionConditionAst)) || !containsConditionalOrRelationalOperands(inversionConditionAst); @@ -254,29 +252,24 @@ private boolean isSkipCondition(DetailAST inversionConditionAst) { /** * Checks if current inverted condition contains only * - * relational operands + * relational operands. * @param inversionConditionAst * Node of type {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#LNOT} * @return true if the node contains only relation operands. */ private static boolean containsRelationalOperandsOnly(DetailAST inversionConditionAst) { - boolean result = true; final DetailAST operatorInInversionAst = inversionConditionAst.getFirstChild() .getNextSibling(); if (operatorInInversionAst != null) { - if (!RELATIONAL_OPERATORS_SET.contains(operatorInInversionAst.getType())) { - DetailAST currentNode = operatorInInversionAst.getFirstChild(); while (currentNode != null) { - if ((currentNode.getType() == TokenTypes.IDENT) || (!isRelationalOperand(currentNode))) { - result = false; } @@ -291,13 +284,12 @@ private static boolean containsRelationalOperandsOnly(DetailAST inversionConditi /** * Checks if current operand is * - * relational operand + * relational operand. * @param operandAst * Child node of {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#LNOT} node * @return true if the operand is relational. */ private static boolean isRelationalOperand(DetailAST operandAst) { - return operandAst.getFirstChild() == null || RELATIONAL_OPERATORS_SET.contains(operandAst.getType()); } @@ -305,21 +297,18 @@ private static boolean isRelationalOperand(DetailAST operandAst) { /** * Checks if current condition contains * - * conditional operators + * conditional operators. * @param inversionAst * Node of type {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#LNOT} * @return true if the node contains conditional or relational operands. */ private static boolean containsConditionalOrRelationalOperands(DetailAST inversionAst) { - boolean result = false; DetailAST currentNodeAst = inversionAst.getFirstChild(); while (currentNodeAst != null) { - if (RELATIONAL_AND_CONDITIONAL_OPERATORS_SET.contains(currentNodeAst.getType())) { - result = true; } @@ -330,13 +319,12 @@ private static boolean containsConditionalOrRelationalOperands(DetailAST inversi } /** - * Logs message on line where inverted condition is used + * Logs message on line where inverted condition is used. * @param inversionAst * Node of type {@link com.puppycrawl.tools.checkstyle.api.TokenTypes#LNOT} */ private void log(DetailAST inversionAst) { - - log(inversionAst.getLineNo(), MSG_KEY); + log(inversionAst, MSG_KEY); } } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/CauseParameterInExceptionCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/CauseParameterInExceptionCheck.java index dd7794aec7..b69c38ed68 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/CauseParameterInExceptionCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/CauseParameterInExceptionCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -46,8 +46,10 @@ * ("allowedCauseTypes" option).

      • * @author Daniil * Yaroslavtsev + * @since 1.8.0 */ public class CauseParameterInExceptionCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. @@ -144,6 +146,21 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + + @Override + public void beginTree(DetailAST rootAST) { + exceptionClassesToWarn.clear(); + } + @Override public void visitToken(DetailAST ast) { switch (ast.getType()) { @@ -173,7 +190,6 @@ public void finishTree(DetailAST treeRootAST) { for (DetailAST classDefNode : exceptionClassesToWarn) { log(classDefNode, MSG_KEY, getName(classDefNode)); } - exceptionClassesToWarn.clear(); } /** diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/CheckstyleTestMakeupCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/CheckstyleTestMakeupCheck.java new file mode 100644 index 0000000000..f709be6159 --- /dev/null +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/CheckstyleTestMakeupCheck.java @@ -0,0 +1,429 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.design; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +import com.github.sevntu.checkstyle.Utils; +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility; +import com.puppycrawl.tools.checkstyle.utils.ScopeUtils; + +/** + *

        + * Custom check to ensure Checkstyle tests are designed correctly. + *

        + * + *

        Rationale: This check was made to ensure tests follow a specific design implementation + * so 3rd party utilities like the regression utility can parse the tests for information + * used in creating regression reports. + * + *

        + * Check have following options: + *

        + *
          + *
        • + * createMethodRegexp - Regular expression for matching a create configuration method by name. This + * is the name of the method that starts creating a custom module configuration to be used for + * verifying results for regression purposes. + * Default value is {@code create(Root|Module)Config|getModuleConfig}.
        • + * + *
        • + * verifyMethodRegexp - Regular expression for matching a verify method by name. This is the name + * of the method that verifies the execution results of the custom configuration created for + * regression. As such, it should accept the custom configuration as a parameter. + * Default value is {@code verify(Warns|Suppressed)?}.
        • + *
        + * + *

        + * To configure the check to report incorrectly made checkstyle tests: + *

        + * + *
        + * <module name="CheckstyleTestMakeup"/>
        + * 
        + * + * @author Richard Veach + * @since 1.25.0 + */ +public class CheckstyleTestMakeupCheck extends AbstractCheck { + + /** Violations message. */ + public static final String MSG_KEY_CONFIG_NOT_ASSIGNED = "tester.config.not.assigned"; + /** Violations message. */ + public static final String MSG_KEY_CONFIG_NOT_ASSIGNED_WITH = "tester.config.not.assigned.with"; + /** Violations message. */ + public static final String MSG_KEY_CONFIG_NOT_ASSIGNED_PROPERLY = + "tester.config.not.assigned.properly"; + /** Violations message. */ + public static final String MSG_KEY_UNKNOWN_PROPERTY = "tester.unknown.property"; + /** Violations message. */ + public static final String MSG_KEY_CONFIG_NOT_FOUND = "tester.config.not.found"; + + /** Name of 'getPath' method. */ + private static final String METHOD_GET_PATH = "getPath"; + + /** AST of method that is currently being examined. */ + private DetailAST methodAst; + /** List of variable names that reference a file. */ + private Set fileVariableNames = new HashSet<>(); + /** List of variable names that reference a configuration. */ + private Set checkConfigNames = new HashSet<>(); + /** {@code true} if the 'verify' method was found in the method. */ + private boolean foundVerify; + + /** List of violations generated for a method. */ + private final Map violations = new HashMap<>(); + + /** Regular expression for matching a create method by name. */ + private Pattern createMethodRegexp = Pattern + .compile("create(Root|Module)Config|getModuleConfig"); + + /** Regular expression for matching a verify method by name. */ + private Pattern verifyMethodRegexp = Pattern.compile("verify(Warns|Suppressed)?"); + + /** + * Setter for {@link #createMethodRegexp}. + * @param createMethodRegexp The value to set. + */ + public void setCreateMethodRegexp(Pattern createMethodRegexp) { + this.createMethodRegexp = createMethodRegexp; + } + + /** + * Setter for {@link #verifyMethodRegexp}. + * @param verifyMethodRegexp The value to set. + */ + public void setVerifyMethodRegexp(Pattern verifyMethodRegexp) { + this.verifyMethodRegexp = verifyMethodRegexp; + } + + @Override + public int[] getDefaultTokens() { + return new int[] { + TokenTypes.METHOD_DEF, + TokenTypes.VARIABLE_DEF, + TokenTypes.METHOD_CALL, + }; + } + + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + + @Override + public void beginTree(DetailAST rootAST) { + resetInternalFields(); + } + + @Override + public void visitToken(DetailAST ast) { + switch (ast.getType()) { + case TokenTypes.METHOD_DEF: + checkMethod(ast); + break; + case TokenTypes.VARIABLE_DEF: + checkVariable(ast); + break; + case TokenTypes.METHOD_CALL: + checkMethodCall(ast); + break; + default: + Utils.reportInvalidToken(ast.getType()); + break; + } + } + + /** + * Examines the method to see if it is part of a Test. + * @param ast The method to examine. + */ + private void checkMethod(DetailAST ast) { + if (methodAst == null && AnnotationUtility.containsAnnotation(ast, "Test") + || AnnotationUtility.containsAnnotation(ast, "org.junit.Test")) { + methodAst = ast; + } + } + + /** + * Examines the variable declaration to see if it is a specific variable type to track. + * Variables of type {@link Configuration} or {@link DefaultConfiguration} need to be assigned + * a {@code null}, createModuleConfig, or createRootConfig and is tracked for future purposes. + * Variables of type {@link File} with the modifier {@code final} are tracked for future + * purposes. + * @param ast The variable to examine. + */ + private void checkVariable(DetailAST ast) { + if (methodAst != null && ScopeUtils.isLocalVariableDef(ast)) { + final DetailAST type = ast.findFirstToken(TokenTypes.TYPE).findFirstToken( + TokenTypes.IDENT); + + if (type != null) { + final String typeText = type.getText(); + + if ("DefaultConfiguration".equals(typeText) || "Configuration".equals(typeText)) { + checkConfigurationVariable(ast); + } + else if ("File".equals(typeText) + && ast.findFirstToken(TokenTypes.MODIFIERS) + .findFirstToken(TokenTypes.FINAL) != null) { + fileVariableNames.add(ast.findFirstToken(TokenTypes.IDENT).getText()); + } + } + } + } + + /** + * Examines the configuration variable to see if it is defined as described in + * {@link #checkVariable(DetailAST)}. + * @param ast The variable to examine. + */ + private void checkConfigurationVariable(DetailAST ast) { + checkConfigNames.add(ast.findFirstToken(TokenTypes.IDENT).getText()); + final DetailAST assignment = ast.findFirstToken(TokenTypes.ASSIGN); + + if (assignment == null) { + violations.put(ast, MSG_KEY_CONFIG_NOT_ASSIGNED); + } + else if (assignment.getFirstChild().getFirstChild().getType() == TokenTypes.METHOD_CALL) { + final DetailAST assignmentMethod = assignment.getFirstChild() + .getFirstChild().findFirstToken(TokenTypes.IDENT); + + if (assignmentMethod != null + && !createMethodRegexp.matcher(assignmentMethod.getText()).matches()) { + violations.put(assignment, MSG_KEY_CONFIG_NOT_ASSIGNED_WITH); + } + } + else if (assignment.getFirstChild().getFirstChild().getType() != TokenTypes.LITERAL_NULL) { + violations.put(ast, MSG_KEY_CONFIG_NOT_ASSIGNED_PROPERLY); + } + } + + /** + * Examines the method call and verify it is defined correctly. + * addAttribute method which is called by one of the configurations found earlier, must have + * all it's parameters be acceptable to {@link #isValidMethodCallExpression(DetailAST)}. + * Any method that matches {@link #verifyMethodRegexp} are tracked for future purposes. + * @param ast The method call to examine. + */ + private void checkMethodCall(DetailAST ast) { + if (methodAst != null) { + final DetailAST firstChild = ast.getFirstChild(); + final String methodCallName = getMethodCallName(firstChild); + final String methodCallerName = getMethodCallerName(firstChild); + + if ("addAttribute".equals(methodCallName) + && checkConfigNames.contains(methodCallerName)) { + final DetailAST elist = ast.findFirstToken(TokenTypes.ELIST); + + for (DetailAST expression = elist.getFirstChild(); expression != null; + expression = expression.getNextSibling()) { + if (expression.getType() == TokenTypes.EXPR + && !isValidMethodCallExpression(expression.getFirstChild())) { + violations.put(expression, MSG_KEY_UNKNOWN_PROPERTY); + } + } + } + else if (methodCallerName.equals(methodCallName) + && ast.getParent().getParent().getType() != TokenTypes.METHOD_CALL + && verifyMethodRegexp.matcher(methodCallName).matches()) { + foundVerify = true; + } + } + } + + /** + * Retrieves the name of the method being called. + * @param ast The method call token to examine. + * @return The name of the method. + */ + private String getMethodCallName(DetailAST ast) { + final String result; + if (ast.getType() == TokenTypes.DOT) { + result = getMethodCallName(ast.getFirstChild().getNextSibling()); + } + else { + result = ast.getText(); + } + return result; + } + + /** + * Retrieves the name of the variable calling the method. + * @param ast The method call token to examine. + * @return The name of who is calling the method. + */ + private String getMethodCallerName(DetailAST ast) { + final String result; + if (ast.getType() == TokenTypes.DOT) { + result = getMethodCallName(ast.getFirstChild()); + } + else { + result = ast.getText(); + } + return result; + } + + /** + * Identifies if the parameter of the method call is valid. + * Plain string literal is allowed. + * Adding multiple string literals is allowed because of line length limits. + * Plain {@code null} is allowed due to backward compatibility. + * Method calls are allowed only if they are any form of getPath, converting an enum to a + * string, or retrieving the path of a final {@link File} variable. + * @param expression The expression to examine. + * @return {@code true} if the method call is defined correctly. + */ + private boolean isValidMethodCallExpression(DetailAST expression) { + boolean result = false; + final DetailAST firstChild = expression.getFirstChild(); + + switch (expression.getType()) { + case TokenTypes.STRING_LITERAL: + result = true; + break; + case TokenTypes.METHOD_CALL: + result = isValidMethodCallExpressionMethodCall(firstChild); + break; + case TokenTypes.PLUS: + result = isValidMethodCallExpression(firstChild) + && isValidMethodCallExpression(firstChild.getNextSibling()); + break; + case TokenTypes.LITERAL_NULL: + result = true; + break; + default: + break; + } + + return result; + } + + /** + * Identifies if the inner method call of a method call is valid as defined in + * {@link #isValidMethodCallExpression(DetailAST)}. + * @param firstChild The first child of the method call. + * @return {@code true} if the method call is defined correctly. + */ + private boolean isValidMethodCallExpressionMethodCall(DetailAST firstChild) { + boolean result = false; + + if (firstChild.getType() == TokenTypes.DOT) { + if (firstChild.getFirstChild().getType() == TokenTypes.DOT) { + result = isEnumerationCall(firstChild); + } + else if (isFileVariable(firstChild.getFirstChild())) { + result = true; + } + } + else { + final String methodName = firstChild.getText(); + + if (isMethodGetPath(methodName)) { + result = true; + } + } + + return result; + } + + /** + * Checks if the method call is calling toString, getName, or name on an enumeration. + * @param ast The AST to examine. + * @return {@code true} if the method call is on a enumeration. + */ + private static boolean isEnumerationCall(DetailAST ast) { + boolean result = false; + final DetailAST firstChild = ast.getFirstChild(); + final DetailAST methodCalled = firstChild.getNextSibling(); + final DetailAST parameters = ast.getNextSibling(); + + if (firstChild.getFirstChild().getType() == TokenTypes.IDENT + && ("toString".equals(methodCalled.getText()) + || "getName".equals(methodCalled.getText()) + || "name".equals(methodCalled.getText())) + && parameters.getChildCount() == 0) { + result = true; + } + + return result; + } + + /** + * Checks if the method call is 'getPath' on a {@link File} variable. + * @param firstChild The AST to examine. + * @return {@code true} if the method call is on a file variable. + */ + private boolean isFileVariable(DetailAST firstChild) { + return METHOD_GET_PATH.equals(firstChild.getNextSibling().getText()) + && fileVariableNames.contains(firstChild.getText()); + } + + /** + * Checks if the method name is a form of 'getPath'. + * @param methodName The name to examine. + * @return {@code true} if the method is of the form. + */ + private static boolean isMethodGetPath(String methodName) { + return METHOD_GET_PATH.equals(methodName) + || "getNonCompilablePath".equals(methodName) + || "getUriString".equals(methodName) + || "getResourcePath".equals(methodName); + } + + @Override + public void leaveToken(DetailAST ast) { + if (ast == methodAst) { + if (foundVerify) { + if (checkConfigNames.isEmpty()) { + violations.put(ast, MSG_KEY_CONFIG_NOT_FOUND); + } + + for (Map.Entry entry : violations.entrySet()) { + log(entry.getKey(), entry.getValue()); + } + } + + resetInternalFields(); + } + } + + /** Resets the internal fields when a new file/method is to be processed. */ + private void resetInternalFields() { + methodAst = null; + fileVariableNames.clear(); + checkConfigNames.clear(); + foundVerify = false; + violations.clear(); + } + +} diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthCheck.java index bac66d4095..847af1d6d6 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -45,6 +45,7 @@ *

        * @author Daniil * Yaroslavtsev + * @since 1.8.0 */ public class ChildBlockLengthCheck extends AbstractCheck { @@ -55,7 +56,7 @@ public class ChildBlockLengthCheck extends AbstractCheck { public static final String MSG_KEY = "child.block.length"; /** - * The constant is used in percantage arifmethic operations. Represents + * The constant is used in percentage arithmetic operations. Represents * '100%' */ private static final double PERCENTS_FACTOR = 100.0; @@ -131,19 +132,27 @@ public int[] getDefaultTokens() { return blockTypes; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { final DetailAST aOpeningBrace = openingBrace(ast); // if the block has braces at all if (aOpeningBrace != null) { - final DetailAST aClosingBrace = closingBrace(ast); final int parentBlockSize = linesCount(aOpeningBrace, aClosingBrace); if (parentBlockSize > ignoreBlockLinesCount) { - final List childBlocks = getChildBlocks( aOpeningBrace, aClosingBrace); @@ -157,7 +166,6 @@ public void visitToken(DetailAST ast) { } else { for (DetailAST badBlock : badChildBlocks) { - final int blockSize = linesCount(badBlock); final double allowedBlockSize = (int) (parentBlockSize @@ -186,16 +194,9 @@ private List getChildBlocks(DetailAST blockOpeningBrace, DetailAST curNode = blockOpeningBrace; - while (curNode != null) { - // before node visiting - if (curNode == blockClosingBrace) { - // stop at closing brace - break; - } - else { - if (isAllowedBlockType(curNode.getType())) { - childBlocks.add(curNode); - } + while (curNode != blockClosingBrace) { + if (isAllowedBlockType(curNode.getType())) { + childBlocks.add(curNode); } // before node leaving DetailAST nextNode = curNode.getFirstChild(); @@ -207,7 +208,7 @@ private List getChildBlocks(DetailAST blockOpeningBrace, nextNode = curNode.getNextSibling(); } - while ((curNode != null) && (nextNode == null)) { + while (nextNode == null) { // leave the visited node nextNode = curNode.getNextSibling(); if (nextNode == null) { diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ConstructorWithoutParamsCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ConstructorWithoutParamsCheck.java index 3f8ca02a9d..92ccad3a0c 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ConstructorWithoutParamsCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ConstructorWithoutParamsCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -84,6 +84,7 @@ * issue 412

        . * * @author Sergey Dudoladov + * @since 1.20.0 */ public class ConstructorWithoutParamsCheck extends AbstractCheck { @@ -149,23 +150,24 @@ public int[] getAcceptableTokens() { @Override public void visitToken(DetailAST ast) { - - final String className = ast.getFirstChild().getText(); - - // The "new" keyword either creates objects or declares arrays. - // In the case of arrays, no objects (array elements) are automatically created, - // and this check does not apply. - if (regexp.matcher(className).find() - && !ignoredRegexp.matcher(className).find() - && !ast.branchContains(TokenTypes.ARRAY_DECLARATOR)) { - - final DetailAST parameterListAST = ast.findFirstToken(TokenTypes.ELIST); - final int numberOfParameters = parameterListAST.getChildCount(); - - if (numberOfParameters == 0) { - log(ast, MSG_KEY, className); + final DetailAST firstChild = ast.getFirstChild(); + if (firstChild != null) { + final String className = firstChild.getText(); + + // The "new" keyword either creates objects or declares arrays. + // In the case of arrays, no objects (array elements) are automatically created, + // and this check does not apply. + if (regexp.matcher(className).find() + && !ignoredRegexp.matcher(className).find() + && ast.findFirstToken(TokenTypes.ARRAY_DECLARATOR) == null) { + final DetailAST parameterListAST = ast.findFirstToken(TokenTypes.ELIST); + final int numberOfParameters = parameterListAST.getChildCount(); + + if (numberOfParameters == 0) { + log(ast, MSG_KEY, className); + } } - } } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ForbidWildcardAsReturnTypeCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ForbidWildcardAsReturnTypeCheck.java index 852fdab3c4..a0e0409a99 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ForbidWildcardAsReturnTypeCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/ForbidWildcardAsReturnTypeCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -26,10 +26,10 @@ import java.util.regex.Pattern; import antlr.collections.AST; - import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility; /** * Prevents using wildcards as return type of methods. @@ -44,10 +44,31 @@ * to accept the parameters they should accept and reject those they should * reject. If the user of a class has to think about wildcard types, there is * probably something wrong with the class’s API." + * Attention: some JDK classes have public methods with "?"(wildcard) in return type + * so it might not always possible to avoid wildcards in return type, as they do not demand user + * to bother about it (invisible for user or method). So suppressions should be used. + *

        + *

        + * Examples: + * + * JDK Collectors, so usage + * of methods that return wildcard could force user customizations over Collectors use wildcard in + * public methods + *

        + *
        {@code
        + * // custom util method, wildcard come from Collectors.toList()
        + * public  Collector singleResult(Function, T> collector) {
        + *   return Collectors.collectingAndThen(Collectors.toList(), collected -> collected.get(0));
        + * }
        + * }
        + *

        If suppressions become too wide spread and annoying it might be reasonable to update Check + * with option to ignore wildcard if used with another type (not alone). *

        * @author Baratali Izmailov + * @since 1.9.0 */ public class ForbidWildcardAsReturnTypeCheck extends AbstractCheck { + /** * Key for error message. */ @@ -62,6 +83,19 @@ public class ForbidWildcardAsReturnTypeCheck extends AbstractCheck { */ private static final int WILDCARD_SUPER_IDENT = TokenTypes.TYPE_LOWER_BOUNDS; + + /** {@link Deprecated Deprecated} annotation name. */ + private static final String DEPRECATED = "Deprecated"; + + /** Fully-qualified {@link Deprecated Deprecated} annotation name. */ + private static final String FQ_DEPRECATED = "java.lang." + DEPRECATED; + + /** {@link Override Override} annotation name. */ + private static final String OVERRIDE = "Override"; + + /** Fully-qualified {@link Override Override} annotation name. */ + private static final String FQ_OVERRIDE = "java.lang." + OVERRIDE; + /** * Empty array of DetailAST. */ @@ -184,26 +218,48 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST methodDefAst) { final String methodScope = getVisibilityScope(methodDefAst); - if (((checkPublicMethods && "public".equals(methodScope)) - || (checkPrivateMethods && "private".equals(methodScope)) - || (checkProtectedMethods && "protected".equals(methodScope)) - || (checkPackageMethods && "package".equals(methodScope))) + if (isCheckableMethodScope(methodScope) && (checkOverrideMethods - || !hasAnnotation(methodDefAst, "Override")) + || (!AnnotationUtility.containsAnnotation(methodDefAst, OVERRIDE) + && !AnnotationUtility.containsAnnotation(methodDefAst, FQ_OVERRIDE))) && (checkDeprecatedMethods - || !hasAnnotation(methodDefAst, "Deprecated"))) { + || (!AnnotationUtility.containsAnnotation(methodDefAst, DEPRECATED) + && !AnnotationUtility.containsAnnotation(methodDefAst, + FQ_DEPRECATED)))) { final List wildcardTypeArguments = getWildcardArgumentsAsMethodReturnType(methodDefAst); if (!wildcardTypeArguments.isEmpty() && !isIgnoreCase(methodDefAst, wildcardTypeArguments)) { - log(methodDefAst.getLineNo(), MSG_KEY); + log(methodDefAst, MSG_KEY); } } } + /** + * Checks if the method scope is defined as one of the types to check. + * @param methodScope The string version of the scope. + * @return {@code true} if the method should be checked. + */ + private boolean isCheckableMethodScope(String methodScope) { + return (checkPublicMethods && "public".equals(methodScope)) + || (checkPrivateMethods && "private".equals(methodScope)) + || (checkProtectedMethods && "protected".equals(methodScope)) + || (checkPackageMethods && "package".equals(methodScope)); + } + /** * Returns the visibility scope of method. * @param methodDefAst DetailAST of method definition. @@ -266,35 +322,8 @@ private static Set getModifiers(DetailAST methodDefAst) { * @return identifier of aAST, null if AST does not have identifier. */ private static String getIdentifier(final DetailAST ast) { - String result = null; final DetailAST identifier = ast.findFirstToken(TokenTypes.IDENT); - if (identifier != null) { - result = identifier.getText(); - } - return result; - } - - /** - * Verify that method definition contains specified annotation. - * @param methodDefAst DetailAST of method definition. - * @param annotationTitle Annotation title - * @return true if method definition contains specified annotation. - */ - private static boolean hasAnnotation(DetailAST methodDefAst, - String annotationTitle) { - boolean result = false; - final DetailAST modifiersAst = methodDefAst.getFirstChild(); - if (hasChildToken(modifiersAst, TokenTypes.ANNOTATION)) { - DetailAST modifierAst = modifiersAst.getFirstChild(); - while (modifierAst != null) { - if (modifierAst.getType() == TokenTypes.ANNOTATION - && annotationTitle.equals(getIdentifier(modifierAst))) { - result = true; - break; - } - modifierAst = modifierAst.getNextSibling(); - } - } + final String result = identifier.getText(); return result; } @@ -431,4 +460,5 @@ private static boolean hasBoundedWildcardAsReturnType( } return result; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/HideUtilityClassConstructorCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/HideUtilityClassConstructorCheck.java index db56df7693..82fe037cb3 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/HideUtilityClassConstructorCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/HideUtilityClassConstructorCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -33,8 +33,10 @@ * * @author lkuehne * @version $Revision: 1.12 $ + * @since 1.8.0 */ public class HideUtilityClassConstructorCheck extends AbstractCheck { + /** * Warning message key. */ @@ -47,6 +49,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { // abstract class could not have private constructor @@ -68,9 +80,9 @@ public void visitToken(DetailAST ast) { final DetailAST modifiers = child.findFirstToken(TokenTypes.MODIFIERS); final boolean isStatic = - modifiers.branchContains(TokenTypes.LITERAL_STATIC); + modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null; final boolean isPrivate = - modifiers.branchContains(TokenTypes.LITERAL_PRIVATE); + modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null; if (!isStatic && !isPrivate) { hasNonStaticMethodOrField = true; @@ -83,13 +95,12 @@ public void visitToken(DetailAST ast) { hasDefaultCtor = false; final DetailAST modifiers = child.findFirstToken(TokenTypes.MODIFIERS); - if (!modifiers.branchContains(TokenTypes.LITERAL_PRIVATE) - && !modifiers.branchContains(TokenTypes.LITERAL_PROTECTED)) { + if (modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null + && modifiers.findFirstToken(TokenTypes.LITERAL_PROTECTED) == null) { // treat package visible as public // for the purpose of this Check hasPublicCtor = true; } - } child = child.getNextSibling(); } @@ -109,12 +120,13 @@ public void visitToken(DetailAST ast) { && hasNonPrivateStaticMethodOrField; if (isUtilClass && (hasAccessibleCtor && !hasStaticModifier)) { - log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY); + log(ast, MSG_KEY); } } } /** + * Test is AST object has abstract modifier. * @param ast class definition for check. * @return true if a given class declared as abstract. */ @@ -126,6 +138,7 @@ private static boolean isAbstract(DetailAST ast) { } /** + * Test is AST object has static modifier. * @param ast class definition for check. * @return true if a given class declared as static. */ @@ -135,4 +148,5 @@ private static boolean isStatic(DetailAST ast) { return staticAST != null; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/InnerClassCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/InnerClassCheck.java index e7e42ec32b..05a46c8453 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/InnerClassCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/InnerClassCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -30,8 +30,10 @@ *

        * * @author Ruslan Dyachenko + * @since 1.8.0 */ public class InnerClassCheck extends AbstractCheck { + /** * Warning message key. */ @@ -47,6 +49,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { // First root class @@ -59,7 +71,7 @@ public void visitToken(DetailAST ast) { && nextSibling.getType() != TokenTypes.CLASS_DEF) { if (nextSibling.getType() == TokenTypes.VARIABLE_DEF || nextSibling.getType() == TokenTypes.METHOD_DEF) { - log(nextSibling.getLineNo(), nextSibling.getColumnNo(), MSG_KEY); + log(nextSibling, MSG_KEY); } nextSibling = nextSibling.getNextSibling(); } @@ -73,4 +85,5 @@ public void leaveToken(DetailAST ast) { rootClass = true; } } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/NestedSwitchCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/NestedSwitchCheck.java index 5d2ea06bb5..0356a2515d 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/NestedSwitchCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/NestedSwitchCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,9 +19,9 @@ package com.github.sevntu.checkstyle.checks.design; +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; -import com.puppycrawl.tools.checkstyle.checks.coding.AbstractNestedDepthCheck; /** *

        @@ -40,27 +40,37 @@ * } * * + *

        * Nested switch block that checks type parameter should be converted into separate * method.
        - * To enable this check use following configuration:
        - *
        - * <module name="NestedSwitchCheck"/> - *

        + * To enable this check use following configuration: + *

        + * + *
        + * <module name="NestedSwitchCheck"/>
        + * 
        * @author Damian Szczepanik (damianszczepanik@github) + * @since 1.13.0 */ -public class NestedSwitchCheck extends AbstractNestedDepthCheck { +public class NestedSwitchCheck extends AbstractCheck { + /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "avoid.nested.switch"; - /** Default allowed nesting depth. */ - private static final int DEFAULT_MAX = 0; + /** Maximum allowed nesting depth. */ + private int max; + /** Current nesting depth. */ + private int depth; - /** The default constructor. */ - public NestedSwitchCheck() { - super(DEFAULT_MAX); + /** + * Setter for maximum allowed nesting depth. + * @param max maximum allowed nesting depth. + */ + public final void setMax(int max) { + this.max = max; } @Override @@ -70,13 +80,32 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public final int[] getRequiredTokens() { + return getDefaultTokens(); + } + + @Override + public void beginTree(DetailAST rootAST) { + depth = 0; + } + @Override public void visitToken(DetailAST aAST) { - nestIn(aAST, MSG_KEY); + if (depth > max) { + log(aAST, MSG_KEY, depth, max); + } + ++depth; } @Override public void leaveToken(DetailAST aAST) { - nestOut(); + --depth; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/NoMainMethodInAbstractClassCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/NoMainMethodInAbstractClassCheck.java index 2cb46fdb62..46294324ae 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/NoMainMethodInAbstractClassCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/NoMainMethodInAbstractClassCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -30,8 +30,10 @@ * Forbids main methods in abstract classes. Existence of 'main' method can * mislead a developer to consider this class as a ready-to-use implementation. * @author Baratali Izmailov email + * @since 1.9.0 */ public class NoMainMethodInAbstractClassCheck extends AbstractCheck { + /** * Key for error message. */ @@ -54,6 +56,16 @@ public final int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public final void visitToken(final DetailAST ast) { if (ast.getType() == TokenTypes.CLASS_DEF) { @@ -68,7 +80,7 @@ public final void visitToken(final DetailAST ast) { } // type of token is METHOD_DEF else if (isChildOfCurrentObjBlockToken(ast) && isMainMethod(ast)) { - log(ast.getLineNo(), MSG_KEY); + log(ast, MSG_KEY); // remove current objblock objBlockTokensStack.pop(); } @@ -110,13 +122,9 @@ private boolean isChildOfCurrentObjBlockToken(final DetailAST methodDefAST) { * @return true if AST has abstract modifier, false otherwise. */ private static boolean hasAbstractModifier(final DetailAST classDefAST) { - boolean result = false; - if (hasChildToken(classDefAST, TokenTypes.MODIFIERS)) { - final DetailAST modifiers = - classDefAST.findFirstToken(TokenTypes.MODIFIERS); - result = hasChildToken(modifiers, TokenTypes.ABSTRACT); - } - return result; + final DetailAST modifiers = + classDefAST.findFirstToken(TokenTypes.MODIFIERS); + return hasChildToken(modifiers, TokenTypes.ABSTRACT); } /** @@ -148,10 +156,7 @@ && isMainMethodModifiers(methodAST) */ private static String getIdentifier(final DetailAST ast) { final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT); - if (ident != null) { - return ident.getText(); - } - return null; + return ident.getText(); } /** @@ -162,14 +167,10 @@ private static String getIdentifier(final DetailAST ast) { * false otherwise. */ private static boolean isMainMethodModifiers(final DetailAST methodAST) { - boolean result = false; - if (hasChildToken(methodAST, TokenTypes.MODIFIERS)) { - final DetailAST modifiers = - methodAST.findFirstToken(TokenTypes.MODIFIERS); - result = hasChildToken(modifiers, TokenTypes.LITERAL_PUBLIC) - && hasChildToken(modifiers, TokenTypes.LITERAL_STATIC); - } - return result; + final DetailAST modifiers = + methodAST.findFirstToken(TokenTypes.MODIFIERS); + return hasChildToken(modifiers, TokenTypes.LITERAL_PUBLIC) + && hasChildToken(modifiers, TokenTypes.LITERAL_STATIC); } /** @@ -179,13 +180,8 @@ private static boolean isMainMethodModifiers(final DetailAST methodAST) { * @return true if AST's type void, false otherwise. */ private static boolean isVoidType(final DetailAST methodAST) { - boolean result = true; - DetailAST methodTypeAST = null; - if (hasChildToken(methodAST, TokenTypes.TYPE)) { - methodTypeAST = methodAST.findFirstToken(TokenTypes.TYPE); - result = hasChildToken(methodTypeAST, TokenTypes.LITERAL_VOID); - } - return result; + final DetailAST methodTypeAST = methodAST.findFirstToken(TokenTypes.TYPE); + return hasChildToken(methodTypeAST, TokenTypes.LITERAL_VOID); } /** @@ -276,4 +272,5 @@ private static boolean hasOnlyStringEllipsisParameter(final DetailAST parameters private static boolean hasChildToken(DetailAST ast, int tokenType) { return ast.findFirstToken(tokenType) != null; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/PublicReferenceToPrivateTypeCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/PublicReferenceToPrivateTypeCheck.java index 4992c452ee..0c07caf39d 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/PublicReferenceToPrivateTypeCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/PublicReferenceToPrivateTypeCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -30,7 +30,6 @@ import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** - *

        * This Check warns on propagation of inner private types to outer classes:
        * - Externally accessible method if it returns private inner type.
        * - Externally accessible field if it's type is a private inner type.
        @@ -71,8 +70,10 @@ * dead/useless code
        *
        * @author Aleksey Nesterenko + * @since 1.12.0 */ public class PublicReferenceToPrivateTypeCheck extends AbstractCheck { + /** * Check message key for private types. */ @@ -99,6 +100,16 @@ public int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void beginTree(DetailAST rootAST) { privateTypes.clear(); @@ -141,7 +152,7 @@ public void finishTree(DetailAST rootAst) { outReturnedType.getText()) && !isExtendsOrImplementsSmth(privateType .getParent())) { - log(outReturnedType.getLineNo(), MSG_KEY, + log(outReturnedType, MSG_KEY, outReturnedType.getText()); } } @@ -193,7 +204,6 @@ private void addExternallyAccessibleFieldTypes(DetailAST fieldDefAst) { */ private static List getMethodOrFieldReferencedTypes(DetailAST typeAst) { - DetailAST returnedType = null; final List returnedTypes = new ArrayList<>(); DetailAST currentNode = typeAst; @@ -214,11 +224,11 @@ private void addExternallyAccessibleFieldTypes(DetailAST fieldDefAst) { */ private static List getMethodParameterTypes(DetailAST parametersDefAst) { - DetailAST parameterType = null; final List parameterTypes = new ArrayList<>(); if (parametersDefAst.getFirstChild() != null) { DetailAST currentNode = parametersDefAst; + DetailAST parameterType = null; while (currentNode != null) { if (currentNode.getType() == TokenTypes.PARAMETER_DEF) { @@ -232,11 +242,9 @@ private void addExternallyAccessibleFieldTypes(DetailAST fieldDefAst) { parameterTypes.add(parameterType); } } - } currentNode = Utils.getNextSubTreeNode(currentNode, parametersDefAst); } - } return parameterTypes; @@ -250,9 +258,9 @@ private void addExternallyAccessibleFieldTypes(DetailAST fieldDefAst) { */ private boolean isExtendsOrImplementsSmth(DetailAST classOrInterfaceDefAst) { return (classOrInterfaceDefAst - .branchContains(TokenTypes.EXTENDS_CLAUSE) + .findFirstToken(TokenTypes.EXTENDS_CLAUSE) != null || classOrInterfaceDefAst - .branchContains(TokenTypes.IMPLEMENTS_CLAUSE)) + .findFirstToken(TokenTypes.IMPLEMENTS_CLAUSE) != null) && !isExtendsOrImplementsPrivate(classOrInterfaceDefAst); } @@ -284,7 +292,6 @@ private boolean isExtendsOrImplementsSmth(DetailAST classOrInterfaceDefAst) { .add(implementingOrExtendingAst.getText()); } } - } currentNode = Utils.getNextSubTreeNode(currentNode, classOrInterfaceDefAst); } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/StaticMethodCandidateCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/StaticMethodCandidateCheck.java index 1b9536996f..0247af7ea9 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/StaticMethodCandidateCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/StaticMethodCandidateCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -62,6 +62,7 @@ * *

      * @author Vladislav Lisetskiy + * @since 1.17.0 */ public class StaticMethodCandidateCheck extends AbstractCheck { @@ -247,11 +248,11 @@ private Frame createMethodFrame(Frame parentFrame, DetailAST ast) { final DetailAST modifiersAst = ast.findFirstToken(TokenTypes.MODIFIERS); final String methodName = ast.findFirstToken(TokenTypes.IDENT).getText(); final Frame frame = new Frame(parentFrame); - if (modifiersAst.branchContains(TokenTypes.LITERAL_PRIVATE) - && !modifiersAst.branchContains(TokenTypes.LITERAL_STATIC) + if (modifiersAst.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null + && modifiersAst.findFirstToken(TokenTypes.LITERAL_STATIC) == null && !skippedMethods.contains(methodName)) { frame.isPrivateMethod = true; - frame.lineNo = ast.getLineNo(); + frame.ast = ast; frame.frameName = getIdentText(ast); } else { @@ -270,7 +271,7 @@ private Frame createMethodFrame(Frame parentFrame, DetailAST ast) { private static boolean isAnonymousClass(DetailAST ast) { final int astType = ast.getType(); return astType == TokenTypes.LITERAL_NEW - && ast.branchContains(TokenTypes.LCURLY); + && ast.findFirstToken(TokenTypes.OBJBLOCK) != null; } /** @@ -332,7 +333,7 @@ && isFrameExpressionsAcceptable(frame) && isFrameTypesAcceptable(frame); if (frame.isPrivateMethod) { if (isStaticCandidate) { - log(frame.lineNo, MSG_KEY, frame.frameName); + log(frame.ast, MSG_KEY, frame.frameName); } } else if (!isStaticCandidate) { @@ -360,7 +361,7 @@ private static String getIdentText(DetailAST field) { */ private static boolean hasStaticModifier(DetailAST ast) { return ast.findFirstToken(TokenTypes.MODIFIERS) - .branchContains(TokenTypes.LITERAL_STATIC); + .findFirstToken(TokenTypes.LITERAL_STATIC) != null; } /** @@ -387,7 +388,7 @@ public boolean apply(DetailAST ast) { * is still a static method candidate. */ private static boolean isFrameTypesAcceptable(final Frame frame) { - Predicate predicate = new Predicate() { + final Predicate predicate = new Predicate() { @Override public boolean apply(String type) { final Optional typeFrame = findFrameByName(frame, type); @@ -643,7 +644,7 @@ private static boolean findStaticMethod(Frame startFrame, DetailAST methodCall, || parametersAst.branchContains(TokenTypes.ELLIPSIS))) { final DetailAST modifiersAst = method.findFirstToken(TokenTypes.MODIFIERS); - if (modifiersAst.branchContains(TokenTypes.LITERAL_STATIC)) { + if (modifiersAst.findFirstToken(TokenTypes.LITERAL_STATIC) != null) { // if a static method is found, we keep searching for a similar // non-static one to the end of the frame and if a non-static // method is not found, then the checked method is still @@ -695,6 +696,7 @@ private static boolean checkFieldLocation(DetailAST field, DetailAST objCalledOn * Contains information about the frame. */ private static class Frame { + /** Name of the class, enum or method. */ private String frameName; @@ -739,8 +741,8 @@ private static class Frame { /** Whether the frame has LITERAL_THIS or LITERAL_SUPER. */ private boolean hasLiteralThisOrSuper; - /** Number of the line where the frame is declared. */ - private int lineNo; + /** AST where the frame is declared. */ + private DetailAST ast; /** * Creates new frame. @@ -752,10 +754,10 @@ private static class Frame { /** * Add method call to this Frame. - * @param ast EXPR ast. + * @param exprAst EXPR ast. */ - public void addExpr(DetailAST ast) { - expressions.add(ast); + public void addExpr(DetailAST exprAst) { + expressions.add(exprAst); } /** @@ -835,5 +837,7 @@ public boolean apply(DetailAST enumConstant) { }; return Iterables.tryFind(enumConstants, predicate); } + } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/package-info.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/package-info.java index 181310faee..71f558e538 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/package-info.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/design/package-info.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/EnumValueNameCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/EnumValueNameCheck.java index 46589c9734..caaa672700 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/EnumValueNameCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/EnumValueNameCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,260 +19,69 @@ package com.github.sevntu.checkstyle.checks.naming; -import java.util.Collection; -import java.util.List; -import java.util.regex.Pattern; - -import com.google.common.collect.Lists; -import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; /** - * Check forces enum values to match the specific pattern. According to - * "Java Coding Style" by Achut Reddy p 3.3 constants include - * "all static final object reference types that are never followed by " - * ." (dot).", i.e. enums, which are followed by dot while used in the code are - * to be treated as static object references, while enums, that are not used - * with following dot, should be treated as constants. - *

      - * Enums are defined to be used as class have some own methods. This condition - * is used to distinguish between Values Enumeration and Class Enumeration. - * Values Enumeration looks like the following: - * enum SimpleErrorEnum - * { - * FIRST_SIMPLE, SECOND_SIMPLE, THIRD_SIMPLE; - * } - * - *

      - * While Class Enumeration has some methods, for example: - * enum SimpleErrorEnum - * { - * FIRST_SIMPLE, SECOND_SIMPLE, THIRD_SIMPLE; - * - * public String toString() { - * return Integer.toString(ordinal() + 10); - * } - * } - * *

      - * Name format for Class Enumeration values is specified with - * {@link #setObjFormat(String)} , while format for enum constants - with - * {@link #setConstFormat(String)} + * Checks that enumeration value names conform to a format specified + * by the format property. The format is a + * {@link java.util.regex.Pattern regular expression} and defaults to + * ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$. + *

      *

      - * To avoid assuming enum as static object reference, while using some specific - * methods, {@link #setExcludes(String[])} can be used. For example to make enum in - * the previous example a constant set Excludes property to a value - * toString + * An example of how to configure the check is: + *

      + *
      + * <module name="EnumValueName"/>
      + * 
      *

      - * By default toString is used as an exclusion. + * An example of how to configure the check for names that requires all names to be lowercase + * with underscores and digits is: + *

      + *
      + * <module name="EnumValueName">
      + *    <property name="format" value="^[a-z_0-9]+*$"/>
      + * </module>
      + * 
      * * @author Pavel Baranchikov - * - * @see - * Java Coding Style + * @since 1.24.0 */ -public class EnumValueNameCheck extends AbstractCheck { - /** - * A key is pointing to the warning message text in "messages.properties" - * file. - */ - public static final String MSG_CONST = "enum.name.const.invalidPattern"; - /** - * A key is pointing to the warning message text in "messages.properties" - * file. - */ - public static final String MSG_OBJ = "enum.name.obj.invalidPattern"; +public class EnumValueNameCheck extends AbstractNameCheck { /** * Default pattern for Values Enumeration names. */ - public static final String DEFAULT_CONST_PATTERN = + public static final String DEFAULT_PATTERN = "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"; /** - * Default pattern for Class Enumeration names. - */ - public static final String DEFAULT_OBJ_PATTERN = "^[A-Z][a-zA-Z0-9]*$"; - - /** - * Default exclusions value. - */ - private static final String[] DEFAULT_EXCLUSION = { - "toString", - }; - - /** - * Regular expression to test Class Enumeration names against. - */ - private Pattern objRegexp; - - /** - * Format for Class Enumeration names to check for. Compiled to - * {@link #objRegexp} - */ - private String objFormat; - - /** - * Regular expression to test Values Enumeration names against. - */ - private Pattern constRegexp; - - /** - * Format for Values Enumeration names to check for. Compiled to - * {@link #constRegexp} - */ - private String constFormat; - - /** - * Method and field names to exclude from check. - */ - private final List excludes; - - /** - * Constructs check with the default pattern.compile. + * Creates a new {@code EnumValueNameCheck} instance. */ public EnumValueNameCheck() { - setConstFormat(DEFAULT_CONST_PATTERN); - setObjFormat(DEFAULT_OBJ_PATTERN); - excludes = Lists.newArrayList(); - setExcludes(DEFAULT_EXCLUSION); - } - - /** - * Method sets format to match Class Enumeration names. - * @param newConstRegexp format to check against - */ - public final void setConstFormat(String newConstRegexp) { - this.constRegexp = Pattern.compile(newConstRegexp, 0); - constFormat = newConstRegexp; - } - - /** - * Method sets format to match Values Enumeration names. - * @param objectRegexp format to check against - */ - public final void setObjFormat(String objectRegexp) { - objRegexp = Pattern.compile(objectRegexp, 0); - objFormat = objectRegexp; - } - - /** - * Method sets method and field name exclusions. - * @param excludes - * comma separated list or regular expressions - */ - public final void setExcludes(String[] excludes) { - this.excludes.clear(); - for (String exclude: excludes) { - this.excludes.add(Pattern.compile(exclude)); - } + super(DEFAULT_PATTERN); } @Override public int[] getDefaultTokens() { - return new int[] { - TokenTypes.ENUM_CONSTANT_DEF, - }; + return getAcceptableTokens(); } @Override - public void visitToken(DetailAST ast) { - final DetailAST nameAST = ast.findFirstToken(TokenTypes.IDENT); - final boolean enumIsClass = isClassEnumeration(ast); - final Pattern pattern; - if (enumIsClass) { - pattern = objRegexp; - } - else { - pattern = constRegexp; - } - if (!pattern.matcher(nameAST.getText()).find()) { - final String format; - if (enumIsClass) { - format = objFormat; - } - else { - format = constFormat; - } - final String msg; - if (enumIsClass) { - msg = MSG_OBJ; - } - else { - msg = MSG_CONST; - } - log(nameAST.getLineNo(), - nameAST.getColumnNo(), - msg, - nameAST.getText(), - format); - } - } - - /** - * Method determines, whether the Enum, specified as parameter has any - * members. Method uses {@link #excludes} while looking though the tree - * nodes - * - * @param ast - * ast to check - * @return true if enum is a class enumeration - */ - private boolean isClassEnumeration(DetailAST ast) { - return hasMembers(ast, excludes); + public int[] getAcceptableTokens() { + return new int[] {TokenTypes.ENUM_CONSTANT_DEF}; } - /** - * Method determines whether the specified enum is a constant or is an - * object. - * - * @param ast - * token of a enum value definition - * @param excludes - * list of ignored member names - * @return true if enum is a class enumeration - */ - private static boolean - hasMembers(DetailAST ast, List excludes) { - final DetailAST objBlock = ast.getParent(); - assert objBlock.getType() == TokenTypes.OBJBLOCK; - boolean memberFound = false; - for (DetailAST member = objBlock.getFirstChild(); member != null; member = member - .getNextSibling()) { - if (member.getType() == TokenTypes.METHOD_DEF - || member.getType() == TokenTypes.VARIABLE_DEF) { - final DetailAST memberIdent = member - .findFirstToken(TokenTypes.IDENT); - assert memberIdent != null; - final String identifierStr = memberIdent.getText(); - if (!isAnyMatched(excludes, identifierStr)) { - memberFound = true; - break; - } - } - } - return memberFound; + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); } - /** - * Returns whether at least one of patterns are successfully matched arainst - * the specified string value - * @param patterns - * pattern list to match against - * @param value - * value to match - * @return true if at least one pattern have been successfully - * matched. - */ - private static boolean - isAnyMatched(Collection patterns, String value) { - for (Pattern pattern : patterns) { - if (pattern.matcher(value).find()) { - return true; - } - } - return false; + @Override + protected boolean mustCheckName(DetailAST ast) { + return true; } } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/InterfaceTypeParameterNameCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/InterfaceTypeParameterNameCheck.java index 676a2a8a7d..97f522502f 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/InterfaceTypeParameterNameCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/InterfaceTypeParameterNameCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -48,6 +48,7 @@ * * @author Dmitry Gridyushko * @version 1.0 +* @since 1.8.0 */ public class InterfaceTypeParameterNameCheck extends AbstractNameCheck { @@ -64,10 +65,21 @@ public final int[] getDefaultTokens() { }; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override protected final boolean mustCheckName(DetailAST ast) { final DetailAST location = ast.getParent().getParent(); return location.getType() == TokenTypes.INTERFACE_DEF; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/UniformEnumConstantNameCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/UniformEnumConstantNameCheck.java index 598a5782e4..5b751e70ea 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/UniformEnumConstantNameCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/UniformEnumConstantNameCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -74,8 +74,10 @@ * constant conform or there is no. * * @author Pavel Baranchikov + * @since 1.21.0 */ public class UniformEnumConstantNameCheck extends AbstractCheck { + /** * Message code for format violations. Used, when more than one format * violated. @@ -124,7 +126,7 @@ public UniformEnumConstantNameCheck() { * @param regexps format to check against */ public final void setFormats(String[] regexps) { - this.patterns = new ArrayList(regexps.length); + this.patterns = new ArrayList<>(regexps.length); for (final String regexp: regexps) { final Pattern pattern = Pattern.compile(regexp, 0); patterns.add(pattern); @@ -199,19 +201,19 @@ private void logViolation(DetailAST member, String enumName, BitSet violated) { } patternsString = violatedPatterns.toString(); } - log(member.getLineNo(), member.getColumnNo(), msgKey, enumName, + log(member, msgKey, enumName, patternsString); } /** * Matches the specified enum name against the patterns, specified by - * {@code conformedPattenrs}. + * {@code conformedPatterns}. * * @param name * name to validate * @param conformedPatterns * bit set of patterns, which the method should match against. - * @return bit set of matched patterns. Returned value is alwais a subset of + * @return bit set of matched patterns. Returned value is always a subset of * {@code conformedPatterns} */ private BitSet match(String name, BitSet conformedPatterns) { @@ -226,4 +228,5 @@ private BitSet match(String name, BitSet conformedPatterns) { } return result; } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/package-info.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/package-info.java index 4afeb328b3..49d366bfea 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/package-info.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/naming/package-info.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthExtendedCheck.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthExtendedCheck.java index e0de1f6369..2560ed4596 100644 --- a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthExtendedCheck.java +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthExtendedCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -24,8 +24,6 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -import org.apache.commons.beanutils.ConversionException; - import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; @@ -88,8 +86,10 @@ * * @author Lars Kühne * @author Ruslan Dyachenko + * @since 1.5.1 */ public class LineLengthExtendedCheck extends AbstractCheck { + /** Warning message key. */ public static final String MSG_KEY = "maxLineLen"; @@ -194,13 +194,24 @@ public int[] getDefaultTokens() { return returnTokens; } + @Override + public int[] getAcceptableTokens() { + return getDefaultTokens(); + } + + @Override + public int[] getRequiredTokens() { + return getDefaultTokens(); + } + @Override public void visitToken(DetailAST ast) { - final DetailAST endOfIgnoreLine = ast.findFirstToken(TokenTypes.SLIST); if (ast.getParent() != null && ast.getParent().getType() == TokenTypes.OBJBLOCK || ast.getType() == TokenTypes.CLASS_DEF) { final int mNumberOfLine = ast.getLineNo(); + final DetailAST endOfIgnoreLine = ast.findFirstToken(TokenTypes.SLIST); + if (endOfIgnoreLine == null) { lines[mNumberOfLine - 1] = null; } @@ -222,7 +233,6 @@ public void beginTree(DetailAST rootAST) { @Override public void finishTree(DetailAST rootAST) { for (int i = 0; i < lines.length; i++) { - if (lines[i] == null) { continue; } @@ -251,15 +261,16 @@ public void setMax(int length) { * * @param format * a String value - * @throws ConversionException + * @throws IllegalArgumentException * unable to parse aFormat */ - public final void setIgnorePattern(String format) throws ConversionException { + public final void setIgnorePattern(String format) { try { ignorePattern = Pattern.compile(format); } catch (final PatternSyntaxException ex) { - throw new ConversionException("unable to parse " + format, ex); + throw new IllegalArgumentException("unable to parse " + format, ex); } } + } diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/sizes/package-info.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/sizes/package-info.java new file mode 100644 index 0000000000..39638f5dda --- /dev/null +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/sizes/package-info.java @@ -0,0 +1,24 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +/** + * Contains the Size checks + * that are bundled with the main distribution. + */ +package com.github.sevntu.checkstyle.checks.sizes; diff --git a/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/package-info.java b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/package-info.java new file mode 100644 index 0000000000..aaf7c26f65 --- /dev/null +++ b/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/package-info.java @@ -0,0 +1,24 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +/** + * Contains the miscellaneous utilities that are bundled with the main distribution. + */ +package com.github.sevntu.checkstyle; + diff --git a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/annotation/messages.properties b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/annotation/messages.properties index 364c1c8aac..0e1fc4b4c7 100644 --- a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/annotation/messages.properties +++ b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/annotation/messages.properties @@ -1,16 +1,3 @@ -annotation.missing.deprecated=Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description. -annotation.missing.override=Must include @java.lang.Override annotation when '{'@inheritDoc'}' Javadoc tag exists. annotation.missing.required.parameter=The annotation {0} is missing required parameters {1}. -annotation.not.valid.on=The annotation {0} is not valid at this location. -annotation.incorrect.style=Annotation style must be ''{0}''. annotation.incorrect.target=Incorrect target: ''{0}'' for annotation: ''{1}''. -annotation.trailing.comma.missing=Annotation array values must contain trailing comma. -annotation.trailing.comma.present=Annotation array values cannot contain trailing comma. -annotation.parens.missing=Annotation must have closing parenthesis. -annotation.parens.present=Annotation cannot have closing parenthesis. -annotation.package.location=Package annotations must be in the package-info.java info. annotation.forbid.element.value=Forbidden element ''{0}'' in annotation ''{1}''. -suppressed.warning.not.allowed=The warning ''{0}'' cannot be suppressed at this location. -javadoc.duplicateTag=Duplicate {0} tag. -javadoc.missing=Missing a Javadoc comment. -tag.not.valid.on=The Javadoc {0} tag is not valid at this location. diff --git a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/coding/messages.properties b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/coding/messages.properties index 1db1574900..ff1ddb38b9 100644 --- a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/coding/messages.properties +++ b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/coding/messages.properties @@ -1,14 +1,8 @@ -array.trailing.comma=Array should contain trailing comma. -assignment.inner.avoid=Inner assignments should be avoided. -avoid.declare.constants=Constants declaration inside interfaces should be avoided. avoid.default.serializable.in.inner.classes=Inner class should not implement default Serializable interface. -avoid.finalizer.method=Usage of finalizer method should be avoided. -avoid.clone.method=Usage of 'clone' method should be avoided. avoid.hiding.cause.exception=Cause exception ''{0}'' was lost. avoid.not.short.circuit.operators.for.boolean=Short-circuit operator should be used instead of ''{0}''. avoid.modifiers.for.types=''{0}'' instance should not have ''{1}'' modifier. avoid.constant.as.first.operand.in.condition=Constant have to be second operand of ''{0}''. -covariant.equals=Covariant equals without overriding equals(java.lang.Object). confusing.condition.check=Avoid negation within an "if" expression with an "else" clause. custom.declaration.order.field=Field definition in wrong order. Expected ''{0}'' then ''{1}''. custom.declaration.order.constructor=Constructor definition in wrong order. Expected ''{0}'' then ''{1}''. @@ -17,87 +11,43 @@ custom.declaration.order.class=Class definition in wrong order. Expected ''{0}'' custom.declaration.order.interface=Interface definition in wrong order. Expected ''{0}'' then ''{1}''. custom.declaration.order.enum=Enum definition in wrong order. Expected ''{0}'' then ''{1}''. custom.declaration.order.invalid.setter=Setter ''{0}'' is in wrong order. Should be right after ''{1}''. -declaration.order.constructor=Constructor definition in wrong order. -declaration.order.method=Method definition in wrong order. -declaration.order.static=Static variable definition in wrong order. -declaration.order.instance=Instance variable definition in wrong order. -declaration.order.access=Variable access definition in wrong order. -default.comes.last=Default should be the last switch label. diamond.operator.for.variable.definition = Diamond operator expected. -doublechecked.locking.avoid=The double-checked locking idiom is broken and should be avoided. -empty.statement=Empty statement. +either.log.or.throw=Either log or throw exception. empty.public.ctor=This empty public constructor is useless. enum.trailing.comma=Enum constant should contain trailing comma. enum.trailing.comma.semi=Enum constant should contain trailing comma without semi-colon afterwards. -equals.avoid.null=String literal expressions should be on the left side of an equals comparison. -equals.noHashCode=Definition of ''equals()'' without corresponding definition of ''hashCode()''. -either.log.or.throw=Either log or throw exception. -explicit.init=Variable ''{0}'' explicitly initialized to ''{1}'' (default value for its type). -fall.through=Fall through from previous branch of the switch statement. -fall.through.last=Fall through from the last branch of the switch statement. -final.variable=Variable ''{0}'' should be declared final. finalize.implementation.missed.try.finally = finalize() method should contain try-finally block with super.finalize() call inside finally block. finalize.implementation.public = finalize() method should have a "protected" visibility. finalize.implementation.useless = finalize() method is useless: it does nothing except for calling super.finalize(). finalize.implementation.missed.super.finalize = You have to call super.finalize() right after finally opening brace. forbid.certain.imports=Import ''{1}'' should not match ''{0}'' pattern, it is forbidden. +forbid.certain.method=Call to ''{0}'' method (matches pattern ''{1}'') with ''{2}'' arguments (matches pattern ''{3}'') is forbidden. forbid.c.comments.in.the.method.body=C-style comments (/*...*/) inside method body are not allowed. forbid.return.in.finally.block=Finally block should not contain return statements. forbid.throw.anonymous.exception=Avoid throwing anonymous exception. -hidden.field=''{0}'' hides a field. illegal.catch=Catching ''{0}'' is not allowed. -illegal.throw=Throwing ''{0}'' is not allowed. forbid.instantiation=Instantiation of ''{0}'' is not allowed. -illegal.token=Usage of ''{0}'' is not allowed. -illegal.token.text=Token text matches an illegal pattern ''{0}''. -illegal.type=Declaring variables, return values or parameters of type ''{0}'' is not allowed. incorrect.getter.name=Unexpected getter name. incorrect.setter.name=Unexpected setter name. -inline.conditional.avoid=Inline conditionals should be avoided. -instantiation.avoid=Instantiation of {0} should be avoided. -junit.method.name=The method ''{0}'' should be named ''{1}''. -junit.method.return.type=The method ''{0}'' must be declared with a {1} return type. -junit.method.parameters=The method ''{0}'' must be declared with no parameters. -junit.method.public.and.static=The method ''{0}'' must be declared static. -junit.method.protected.or.public=The method ''{0}'' must be public or protected. -junit.method.static=The method ''{0}'' shouldn''t be static. logic.condition.need.optimization=Condition with {0} at line {1} position {2} need optimization. All method calls are advised to move to end of logic expression. -magic.number=''{0}'' is a magic number. map.iteration.entrySet=You are using both keys and values for this map. It is better to use entrySet() instead of keySet() + get(). map.iteration.keySet=It is better to use keySet() method to iterate over this map because you aren`t using values. map.iteration.values=You are using only values of this map. It is better to use values() to iterate this map. -redundant.return=Redundant return. -missing.ctor=Class should define a constructor. -missing.package.declaration=Missing package declaration. -missing.super.call=Method ''{0}'' should call ''super.{0}''. -missing.switch.default=switch without \"default\" clause. -modified.control.variable=Control variable ''{0}'' is modified. +move.variable.inside=Variable ''{0}'' can be moved inside the block at line ''{1}'' to restrict runtime creation. multiple.string.literal=The String {0} appears {1} times in the file. multiple.variable.declarations=Only one variable definition per line allowed. multiple.variable.declarations.comma=Each variable declaration must be in its own statement. name.convention.for.test.classes=JUnit test class name should match ''{0}'' pattern. -nested.if.depth=Nested if-else depth is {0,number,integer} (max allowed is {1,number,integer}). -nested.try.depth=Nested try depth is {0,number,integer} (max allowed is {1,number,integer}). no.null.for.collections=Method should return empty collection instead of null. numeric.literal.need.underscore=Numeric literal should have underscores. overridable.method=Overridable method ''{0}'' is called in {1} body. overridable.method.leads=Calling the method ''{0}'' in {1} body leads to the call of the overridable method ''{2}''. -parameter.assignment=Assignment of parameter ''{0}'' is not allowed. redundant.return.check=Redundant return. -redundant.throws.classInfo=Unable to get class information for {0}. -redundant.throws.duplicate=Redundant throws: ''{0}'' listed more then one time. -redundant.throws.subclass=Redundant throws: ''{0}'' is subclass of ''{1}''. -redundant.throws.unchecked=Redundant throws: ''{0}'' is unchecked exception. -require.this.variable=Reference to instance variable ''{0}'' needs \"this.\". -require.this.unfound.variable=Unable find where ''{0}'' is declared. -require.this.method=Method call to ''{0}'' needs \"this.\". +require.fail=try/catch either requires a fail at the end of the try clause for junit tests or to remove the try/catch completely. return.count.extended.method=Return count for ''{0}'' method is {1} (max allowed is {2}). return.count.extended.ctor=Return count for ''{0}'' constructor is {1} (max allowed is {2}). -return.depth=Return depth is {0,number,integer} (max allowed is {1,number,integer}). -simplify.boolreturn=Conditional logic can be removed. -simplify.expression=Expression can be simplified. +return.count.extended.lambda=Return count for the lambda is {0} (max allowed is {1}). single.break.or.continue.in.loops=Loops should not contain more than a single "break" or "continue" statement -string.literal.equality=Literal Strings should be compared using equals(), not ''{0}''. ternary.per.expression.count=More than {0} ternary operators in expression. unnecessary.paren.assign=Unnecessary parentheses around assignment right-hand side. unnecessary.paren.expr=Unnecessary parentheses around expression. diff --git a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/design/messages.properties b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/design/messages.properties index a80d88568c..d5ecc9e63e 100644 --- a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/design/messages.properties +++ b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/design/messages.properties @@ -4,14 +4,13 @@ avoid.nested.switch=Nested switch should be avoided, extract nested switch block avoid.main.method.in.abstract.class=Main method inside abstract class should be avoided. cause.parameter.in.exception=''{0}'' class should have a constructor with exception cause as parameter. child.block.length=Block length is {0} lines, but should be lesser or equal to {1} lines. -design.forExtension=Method ''{0}'' is not designed for extension - needs to be abstract, final or empty. -final.class=Class {0} should be declared as final. -interface.type=interfaces should describe a type and hence have methods. -variable.notPrivate=Variable ''{0}'' must be private and have accessor methods. -mutable.exception=The field ''{0}'' must be declared final. -throws.count=Throws count is {0,number,integer} (max allowed is {1,number,integer}). hide.utility.class=Utility classes should not have a public or default constructor. forbid.wildcard.as.return.type=Wildcard as return type should be avoided. public.reference.to.private.type=Reference to the the instance of private type: {0}. static.method.candidate=Method {0} should be declared as static. constructor.without.params=Calls to constructors of ''{0}'' should use at least one parameter. +tester.config.not.assigned=DefaultConfiguration not assigned. +tester.config.not.assigned.with=DefaultConfiguration was not assigned by an allowed create configuration method. +tester.config.not.assigned.properly=DefaultConfiguration was not assigned properly. +tester.unknown.property=Unknown property name/value. +tester.config.not.found=DefaultConfiguration was not found. diff --git a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/naming/messages.properties b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/naming/messages.properties index d4b7f4b6ed..0edc20059a 100644 --- a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/naming/messages.properties +++ b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/naming/messages.properties @@ -1,8 +1,3 @@ name.invalidPattern=Name ''{0}'' must match pattern ''{1}''. -illegal.abstract.class.name=Name ''{0}'' must match pattern ''{1}''. -no.abstract.class.modifier=Class ''{0}'' must has abstract modifier. -method.name.equals.class.name=Method Name ''{0}'' must not equal the enclosing class name. -enum.name.const.invalidPattern=Name of Values Enumeration ''{0}'' must match pattern ''{1}''. -enum.name.obj.invalidPattern=Name of Class Enumeration ''{0}'' must match pattern ''{1}''. enum.name.formats.violated=Name of enumeration value ''{0}'' must match one of patterns: {1}. enum.name.format.violated=Name of enumeration value ''{0}'' must match pattern {1}. diff --git a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/sizes/messages.properties b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/sizes/messages.properties index f62baa656c..8adbb4e74b 100644 --- a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/sizes/messages.properties +++ b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/sizes/messages.properties @@ -1,7 +1 @@ -executableStatementCount=Executable statement count is {0,number,integer} (max allowed is {1,number,integer}). -maxLen.file=File length is {0,number,integer} lines (max allowed is {1,number,integer}). -maxLen.method=Method length is {0,number,integer} lines (max allowed is {1,number,integer}). -maxLen.anonInner=Anonymous inner class length is {0,number,integer} lines (max allowed is {1,number,integer}). maxLineLen=Line is longer than {0,number,integer} characters. Current line length is {1,number,integer}. -maxOuterTypes=Outer types defined is {0,number,integer} (max allowed is {1,number,integer}). -maxParam=More than {0,number,integer} parameters. diff --git a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/whitespace/messages.properties b/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/whitespace/messages.properties deleted file mode 100644 index 3ebf816e2f..0000000000 --- a/sevntu-checks/src/main/resources/com/github/sevntu/checkstyle/checks/whitespace/messages.properties +++ /dev/null @@ -1 +0,0 @@ -single.space.separator=Use a single space to separate tokens. diff --git a/sevntu-checks/src/main/sh/ast.sh b/sevntu-checks/src/main/sh/ast.sh index 244d4e8e65..ba4db142a7 100755 --- a/sevntu-checks/src/main/sh/ast.sh +++ b/sevntu-checks/src/main/sh/ast.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash ################################################################################# -# This is a useful script which builds Checkstyle AST (abstract synthax tree) # +# This is a useful script which builds Checkstyle AST (abstract syntax tree) # # for custom Java file and opens it using simple built-in Checkstyle GUI. # ################################################################################# @@ -41,7 +41,7 @@ CHECKSTYLE_VERSION=5.7 ARCHIVE_FILE_NAME=checkstyle-${CHECKSTYLE_VERSION}-bin.tar.gz CHECKSTYLE_OUTPUT_FILE_NAME=checkstyle-${CHECKSTYLE_VERSION}-all.jar -# checking /tmp for existance +# checking /tmp for existence TMPDIR=/tmp if [ ! -d $TMPDIR ] then diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/BaseCheckTestSupport.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/BaseCheckTestSupport.java deleted file mode 100644 index c2600f8004..0000000000 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/BaseCheckTestSupport.java +++ /dev/null @@ -1,185 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.github.sevntu.checkstyle; - -import static java.text.MessageFormat.format; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintStream; -import java.net.URL; -import java.util.List; -import java.util.Locale; -import java.util.Properties; - -import org.junit.Assert; - -import com.google.common.collect.Lists; -import com.puppycrawl.tools.checkstyle.AuditEventUtFormatter; -import com.puppycrawl.tools.checkstyle.Checker; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.DefaultLogger; -import com.puppycrawl.tools.checkstyle.TreeWalker; -import com.puppycrawl.tools.checkstyle.api.AuditEvent; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public abstract class BaseCheckTestSupport extends Assert { - private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - private final PrintStream printStream = new PrintStream(baos); - - public static DefaultConfiguration createCheckConfig(Class clazz) { - return new DefaultConfiguration(clazz.getName()); - } - - protected void verify(Configuration config, String fileName, String[] expected) - throws Exception { - verify(createChecker(config), fileName, fileName, expected); - } - - protected void verify(Checker checker, String fileName, String[] expected) throws Exception { - verify(checker, fileName, fileName, expected); - } - - protected void verify(Checker checker, String processedFilename, String messageFileName, - String[] aExpected) throws Exception { - verify(checker, new File[] {new File(processedFilename)}, messageFileName, aExpected); - } - - protected void verify(Checker checker, File[] processedFiles, String messageFileName, - String[] expected) throws Exception { - printStream.flush(); - final List testInputFiles = Lists.newArrayList(processedFiles); - final int foundErrorsCount = checker.process(testInputFiles); - - // Process each output line - final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - final BufferedReader br = new BufferedReader(new InputStreamReader(bais)); - - try { - for (int i = 0; i < expected.length; i++) { - final String expectedResult = messageFileName + ":" + expected[i]; - final String actual = br.readLine(); - assertEquals("error message " + i, expectedResult, actual); - } - - assertEquals("Check generated unexpected warning: " + br.readLine(), expected.length, - foundErrorsCount); - checker.destroy(); - } - finally { - br.close(); - bais.close(); - } - } - - protected Checker createChecker(Configuration checkConfig) throws Exception { - final Checker checker = new Checker(); - // make sure the tests always run with english error messages - // so the tests don't fail in supported locales like german - final Locale locale = Locale.ENGLISH; - checker.setLocaleCountry(locale.getCountry()); - checker.setLocaleLanguage(locale.getLanguage()); - checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); - - final DefaultConfiguration defaultConfig = createCheckerConfig(checkConfig); - checker.configure(defaultConfig); - - checker.addListener(new BriefLogger(printStream)); - return checker; - } - - protected DefaultConfiguration createCheckerConfig(Configuration config) { - final DefaultConfiguration result = new DefaultConfiguration("configuration"); - final DefaultConfiguration treeWalkerConfig = createCheckConfig(TreeWalker.class); - // make sure that the tests always run with this charset - result.addAttribute("charset", "iso-8859-1"); - result.addChild(treeWalkerConfig); - treeWalkerConfig.addChild(config); - return result; - } - - protected String getPath(String filename) { - String result = null; - try { - final URL resource = getClass().getResource(filename); - if (resource == null) { - throw new RuntimeException(String.format("Resource '%s' can NOT be found " - + "(does not exist or just not visible for current classloader)", - filename)); - } - else { - result = new File(resource.getPath()).getCanonicalPath(); - } - } - catch (IOException ex) { - throw new RuntimeException("Error while getting path for resource: " + filename, ex); - } - return result; - } - - /** - * Gets the check message 'as is' from appropriate 'messages.properties' file. - * @param messageKey the key of message in 'messages.properties' file. - */ - public String getCheckMessage(String messageKey) { - final Properties pr = new Properties(); - try { - pr.load(getClass().getResourceAsStream("messages.properties")); - } - catch (IOException ex) { - return null; - } - return pr.getProperty(messageKey); - } - - /** - * Gets the check message 'as is' from appropriate 'messages.properties' file. - * @param messageKey the key of message in 'messages.properties' file. - * @param arguments the arguments of message in 'messages.properties' file. - */ - public String getCheckMessage(String messageKey, Object ... arguments) { - return format(getCheckMessage(messageKey), arguments); - } - - /** A brief logger that only display errors */ - protected static class BriefLogger extends DefaultLogger { - - public BriefLogger(OutputStream out) { - super(out, true, out, false, new AuditEventUtFormatter()); - } - - @Override - public void auditStarted(AuditEvent evt) { - } - - @Override - public void fileFinished(AuditEvent evt) { - } - - @Override - public void fileStarted(AuditEvent evt) { - } - } -} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/UtilsTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/UtilsTest.java new file mode 100644 index 0000000000..da1142cb05 --- /dev/null +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/UtilsTest.java @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle; + +import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.isUtilsClassHasPrivateConstructor; +import static org.junit.Assert.fail; + +import org.junit.Assert; +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.api.TokenTypes; + +public class UtilsTest { + + @Test + public void testIsProperUtilsClass() throws ReflectiveOperationException { + Assert.assertTrue("Constructor is not private", + isUtilsClassHasPrivateConstructor(Utils.class, true)); + } + + @Test + public void testReportInvalidToken() { + try { + Utils.reportInvalidToken(TokenTypes.CLASS_DEF); + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: CLASS_DEF", ex.getMessage()); + } + } + +} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationCheckTest.java new file mode 100644 index 0000000000..8f9df149e4 --- /dev/null +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationCheckTest.java @@ -0,0 +1,175 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.annotation; + +import static com.github.sevntu.checkstyle.checks.annotation.ForbidAnnotationCheck.MSG_KEY; + +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; + +/** + * Test that annotation's target is correct. + * + * @author Hidoyatov Victor + * + */ +public class ForbidAnnotationCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/annotation"; + } + + @Test + public void testDefaultCheck() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + final String[] expected1 = {}; + + verify(checkConfig, getPath("InputForbidAnnotationCheck2.java"), expected1); + } + + @Test + public void testNullProperties() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + checkConfig.addAttribute("annotationNames", null); + checkConfig.addAttribute("annotationTargets", null); + + final String[] expected1 = {}; + + verify(checkConfig, getPath("InputForbidAnnotationCheck2.java"), expected1); + } + + @Test + public void testFullAnnotationName() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + checkConfig.addAttribute("annotationNames", "Test"); + + final String[] expected1 = {}; + + verify(checkConfig, getPath("InputForbidAnnotationCheck2.java"), expected1); + } + + @Test + public void testVariableIsForbidden() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + checkConfig.addAttribute("annotationNames", + "Edible,Author,Author2,SuppressWarnings"); + checkConfig.addAttribute("annotationTargets", "VARIABLE_DEF"); + + final String[] expected2 = { + "13:5: " + getCheckMessage(MSG_KEY, "VARIABLE_DEF", "Edible"), + "20:7: " + getCheckMessage(MSG_KEY, "VARIABLE_DEF", "Author"), + "21:7: " + getCheckMessage(MSG_KEY, "VARIABLE_DEF", "Author2"), + "59:7: " + getCheckMessage(MSG_KEY, "VARIABLE_DEF", "SuppressWarnings"), + }; + + verify(checkConfig, getPath("InputForbidAnnotationCheck.java"), expected2); + } + + @Test + public void testMethodIsForbidden() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + checkConfig.addAttribute("annotationNames", "Twizzle,One,Two,Three,B"); + checkConfig.addAttribute("annotationTargets", "METHOD_DEF"); + + final String[] expected3 = { + "28:7: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "Twizzle"), + "39:7: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "One"), + "40:7: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "Two"), + "41:7: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "Three"), + "47:9: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "B"), + }; + + verify(checkConfig, getPath("InputForbidAnnotationCheck.java"), expected3); + } + + @Test + public void testClassAndConstuctorIsForbidden() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + checkConfig.addAttribute("annotationNames", "Test,ctor,ctor2"); + checkConfig.addAttribute("annotationTargets", "CLASS_DEF,CTOR_DEF"); + + final String[] expected4 = { + "6:1: " + getCheckMessage(MSG_KEY, "CLASS_DEF", "Test"), + "8:5: " + getCheckMessage(MSG_KEY, "CTOR_DEF", "ctor"), + "9:5: " + getCheckMessage(MSG_KEY, "CTOR_DEF", "ctor2"), + }; + + verify(checkConfig, getPath("InputForbidAnnotationCheck.java"), expected4); + } + + @Test + public void testAnnotationIsForbidden() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + checkConfig.addAttribute("annotationNames", "Retention,Target"); + checkConfig.addAttribute("annotationTargets", "ANNOTATION_DEF"); + + final String[] expected5 = { + "34:7: " + getCheckMessage(MSG_KEY, "ANNOTATION_DEF", "Retention"), + "35:7: " + getCheckMessage(MSG_KEY, "ANNOTATION_DEF", "Target"), + }; + + verify(checkConfig, getPath("InputForbidAnnotationCheck.java"), expected5); + } + + @Test + public void testParameterAndInterfaceIsForbidden() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + checkConfig.addAttribute("annotationNames", "MyAnnotation,A"); + checkConfig.addAttribute("annotationTargets", + "PARAMETER_DEF,INTERFACE_DEF"); + + final String[] expected6 = { + "43:17: " + getCheckMessage(MSG_KEY, "PARAMETER_DEF", "MyAnnotation"), + "45:7: " + getCheckMessage(MSG_KEY, "INTERFACE_DEF", "A"), + }; + + verify(checkConfig, getPath("InputForbidAnnotationCheck.java"), expected6); + } + + @Test + public void testEnumIsForbidden() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ForbidAnnotationCheck.class); + + checkConfig.addAttribute("annotationNames", "C,int1,int2,int3"); + checkConfig.addAttribute("annotationTargets", + "ENUM_DEF,ENUM_CONSTANT_DEF"); + + final String[] expected7 = { + "50:7: " + getCheckMessage(MSG_KEY, "ENUM_DEF", "C"), + "52:12: " + getCheckMessage(MSG_KEY, "ENUM_CONSTANT_DEF", "int1"), + "54:12: " + getCheckMessage(MSG_KEY, "ENUM_CONSTANT_DEF", "int2"), + "56:12: " + getCheckMessage(MSG_KEY, "ENUM_CONSTANT_DEF", "int3"), + }; + + verify(checkConfig, getPath("InputForbidAnnotationCheck.java"), expected7); + } + +} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationElementValueCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationElementValueCheckTest.java index b521fb119f..2fc041f004 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationElementValueCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationElementValueCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,14 +23,20 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class ForbidAnnotationElementValueCheckTest extends BaseCheckTestSupport { +public class ForbidAnnotationElementValueCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/annotation"; + } + @Test public void testAnnotationWithStringParameter() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "Anno1"); checkConfig.addAttribute("elementName", "str"); checkConfig.addAttribute("forbiddenElementValueRegexp", "someString\\d+"); @@ -45,7 +51,7 @@ public void testAnnotationWithStringParameter() throws Exception { @Test public void testAnnotationWithIntegerParameter() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "Anno2"); checkConfig.addAttribute("elementName", "intVal"); @@ -61,7 +67,7 @@ public void testAnnotationWithIntegerParameter() throws Exception { @Test public void testAnnotationWithFloatParameter() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "Anno3"); checkConfig.addAttribute("elementName", "floatVal"); @@ -77,7 +83,7 @@ public void testAnnotationWithFloatParameter() throws Exception { @Test public void testAnnotationWithBooleanParameter() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "Anno4"); checkConfig.addAttribute("elementName", "boolVal"); @@ -93,7 +99,7 @@ public void testAnnotationWithBooleanParameter() throws Exception { @Test public void testAnnotationWithDotSplittedParameter() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "Bean"); checkConfig.addAttribute("elementName", "name"); @@ -109,7 +115,7 @@ public void testAnnotationWithDotSplittedParameter() throws Exception { @Test public void testAnnotationWithSeveralParameters() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "Anno5"); checkConfig.addAttribute("elementName", "stringValue"); @@ -125,7 +131,7 @@ public void testAnnotationWithSeveralParameters() throws Exception { @Test public void testAnnotationWithSingleParameter() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "SuppressWarnings"); checkConfig.addAttribute("elementName", "value"); @@ -139,9 +145,9 @@ public void testAnnotationWithSingleParameter() throws Exception { } @Test - public void testAnnotationWtithBooleanParameterValueDoesntMatch() throws Exception { + public void testAnnotationWithBooleanParameterValueDoesntMatch() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "Anno4"); checkConfig.addAttribute("elementName", "boolVal"); @@ -155,7 +161,7 @@ public void testAnnotationWtithBooleanParameterValueDoesntMatch() throws Excepti @Test public void testAnnotationWithListAsParameterValue() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "SuppressWarnings"); checkConfig.addAttribute("elementName", "value"); @@ -172,7 +178,7 @@ public void testAnnotationWithListAsParameterValue() throws Exception { @Test public void testAnnotationWithAnnotationAsParameter() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "Name"); checkConfig.addAttribute("elementName", "last"); @@ -188,7 +194,7 @@ public void testAnnotationWithAnnotationAsParameter() throws Exception { @Test public void testAnnotationWithDefaultValues() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); final String[] expected = { "114:11: " + getCheckMessage(MSG_KEY, "expected", "Test"), @@ -200,7 +206,7 @@ public void testAnnotationWithDefaultValues() throws Exception { @Test public void testFullAnnotationClasspath() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidAnnotationElementValueCheck.class); + createModuleConfig(ForbidAnnotationElementValueCheck.class); checkConfig.addAttribute("annotationName", "SuppressWarnings"); checkConfig.addAttribute("elementName", "value"); @@ -212,4 +218,5 @@ public void testFullAnnotationClasspath() throws Exception { verify(checkConfig, getPath("InputForbidAnnotationElementValueCheck2.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationTest.java deleted file mode 100644 index 4651dffd54..0000000000 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/ForbidAnnotationTest.java +++ /dev/null @@ -1,146 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.github.sevntu.checkstyle.checks.annotation; - -import static com.github.sevntu.checkstyle.checks.annotation.ForbidAnnotationCheck.MSG_KEY; - -import org.junit.Test; - -import com.github.sevntu.checkstyle.BaseCheckTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; - -/** - * Test that annotation's target is correct. - * - * @author Hidoyatov Victor - * - */ -public class ForbidAnnotationTest extends BaseCheckTestSupport { - - @Test - public void testFullAnnotationName() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidAnnotationCheck.class); - - final String[] expected1 = {}; - - verify(checkConfig, getPath("InputForbidAnnotation2.java"), expected1); - } - - @Test - public void testVariableIsForbidden() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidAnnotationCheck.class); - - checkConfig.addAttribute("annotationNames", - "Edible,Author,Author2,SuppressWarnings"); - checkConfig.addAttribute("annotationTargets", "VARIABLE_DEF"); - - final String[] expected2 = { - "13: " + getCheckMessage(MSG_KEY, "VARIABLE_DEF", "Edible"), - "20: " + getCheckMessage(MSG_KEY, "VARIABLE_DEF", "Author"), - "21: " + getCheckMessage(MSG_KEY, "VARIABLE_DEF", "Author2"), - "59: " + getCheckMessage(MSG_KEY, "VARIABLE_DEF", "SuppressWarnings"), - }; - - verify(checkConfig, getPath("InputForbidAnnotation.java"), expected2); - } - - @Test - public void testMethodIsForbidden() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidAnnotationCheck.class); - - checkConfig.addAttribute("annotationNames", "Twizzle,One,Two,Three,B"); - checkConfig.addAttribute("annotationTargets", "METHOD_DEF"); - - final String[] expected3 = { - "28: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "Twizzle"), - "39: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "One"), - "40: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "Two"), - "41: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "Three"), - "47: " + getCheckMessage(MSG_KEY, "METHOD_DEF", "B"), - }; - - verify(checkConfig, getPath("InputForbidAnnotation.java"), expected3); - } - - @Test - public void testClassAndConstuctorIsForbidden() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidAnnotationCheck.class); - - checkConfig.addAttribute("annotationNames", "Test,ctor,ctor2"); - checkConfig.addAttribute("annotationTargets", "CLASS_DEF,CTOR_DEF"); - - final String[] expected4 = { - "6: " + getCheckMessage(MSG_KEY, "CLASS_DEF", "Test"), - "8: " + getCheckMessage(MSG_KEY, "CTOR_DEF", "ctor"), - "9: " + getCheckMessage(MSG_KEY, "CTOR_DEF", "ctor2"), - }; - - verify(checkConfig, getPath("InputForbidAnnotation.java"), expected4); - } - - @Test - public void testAnnotationIsForbidden() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidAnnotationCheck.class); - - checkConfig.addAttribute("annotationNames", "Retention,Target"); - checkConfig.addAttribute("annotationTargets", "ANNOTATION_DEF"); - - final String[] expected5 = { - "34: " + getCheckMessage(MSG_KEY, "ANNOTATION_DEF", "Retention"), - "35: " + getCheckMessage(MSG_KEY, "ANNOTATION_DEF", "Target"), - }; - - verify(checkConfig, getPath("InputForbidAnnotation.java"), expected5); - } - - @Test - public void testParameterAndInterfaceIsForbidden() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidAnnotationCheck.class); - - checkConfig.addAttribute("annotationNames", "MyAnnotation,A"); - checkConfig.addAttribute("annotationTargets", - "PARAMETER_DEF,INTERFACE_DEF"); - - final String[] expected6 = { - "43: " + getCheckMessage(MSG_KEY, "PARAMETER_DEF", "MyAnnotation"), - "45: " + getCheckMessage(MSG_KEY, "INTERFACE_DEF", "A"), - }; - - verify(checkConfig, getPath("InputForbidAnnotation.java"), expected6); - } - - @Test - public void testEnumIsForbidden() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidAnnotationCheck.class); - - checkConfig.addAttribute("annotationNames", "C,int1,int2,int3"); - checkConfig.addAttribute("annotationTargets", - "ENUM_DEF,ENUM_CONSTANT_DEF"); - - final String[] expected7 = { - "50: " + getCheckMessage(MSG_KEY, "ENUM_DEF", "C"), - "52: " + getCheckMessage(MSG_KEY, "ENUM_CONSTANT_DEF", "int1"), - "54: " + getCheckMessage(MSG_KEY, "ENUM_CONSTANT_DEF", "int2"), - "56: " + getCheckMessage(MSG_KEY, "ENUM_CONSTANT_DEF", "int3"), - }; - - verify(checkConfig, getPath("InputForbidAnnotation.java"), expected7); - } -} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/RequiredParameterForAnnotationCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/RequiredParameterForAnnotationCheckTest.java index 9345af0357..000ba85d3c 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/RequiredParameterForAnnotationCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/annotation/RequiredParameterForAnnotationCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -24,16 +24,21 @@ import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class RequiredParameterForAnnotationCheckTest extends BaseCheckTestSupport { +public class RequiredParameterForAnnotationCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/annotation"; + } @Test public void testValidateRequiredParameter() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(RequiredParameterForAnnotationCheck.class); + createModuleConfig(RequiredParameterForAnnotationCheck.class); checkConfig.addAttribute("annotationName", "testAnnotation1"); checkConfig.addAttribute("requiredParameters", "firstParameter"); @@ -53,7 +58,7 @@ public void testValidateRequiredParameter() public void testMultipleProperties1() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(RequiredParameterForAnnotationCheck.class); + createModuleConfig(RequiredParameterForAnnotationCheck.class); checkConfig.addAttribute("annotationName", "testAnnotation1"); checkConfig.addAttribute("requiredParameters", @@ -93,7 +98,7 @@ public void testMultipleProperties1() public void testMultipleProperties2() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(RequiredParameterForAnnotationCheck.class); + createModuleConfig(RequiredParameterForAnnotationCheck.class); checkConfig.addAttribute("annotationName", "testAnnotation1"); checkConfig.addAttribute("requiredParameters", "firstParameter,secondParameter"); @@ -122,7 +127,7 @@ public void testMultipleProperties2() public void testForAnnotationWithCanonicalName() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(RequiredParameterForAnnotationCheck.class); + createModuleConfig(RequiredParameterForAnnotationCheck.class); checkConfig.addAttribute("annotationName", "com.github.sevntu.checkstyle.checks" + ".annotation.InputRequiredParameterForAnnotationCheck.testAnnotation2"); @@ -152,7 +157,7 @@ public void testForAnnotationWithCanonicalName() public void testMultipleParametersForAnnotationWithCanonicalName() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(RequiredParameterForAnnotationCheck.class); + createModuleConfig(RequiredParameterForAnnotationCheck.class); checkConfig.addAttribute("annotationName", "com.github.sevntu.checkstyle.checks" + ".annotation.InputRequiredParameterForAnnotationCheck.testAnnotation2"); diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidConstantAsFirstOperandInConditionCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidConstantAsFirstOperandInConditionCheckTest.java index 45ef254886..fc24702e5b 100755 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidConstantAsFirstOperandInConditionCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidConstantAsFirstOperandInConditionCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,57 +23,133 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class AvoidConstantAsFirstOperandInConditionCheckTest extends BaseCheckTestSupport { +public class AvoidConstantAsFirstOperandInConditionCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testAll() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(AvoidConstantAsFirstOperandInConditionCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidConstantAsFirstOperandInConditionCheck.class); final String[] expected = { - "24: " + getCheckMessage(MSG_KEY, "=="), - "25: " + getCheckMessage(MSG_KEY, "=="), - "27: " + getCheckMessage(MSG_KEY, "=="), - "28: " + getCheckMessage(MSG_KEY, "=="), - "29: " + getCheckMessage(MSG_KEY, "=="), - "30: " + getCheckMessage(MSG_KEY, "=="), - "31: " + getCheckMessage(MSG_KEY, "=="), - "46: " + getCheckMessage(MSG_KEY, "=="), - "47: " + getCheckMessage(MSG_KEY, "!="), - "52: " + getCheckMessage(MSG_KEY, "=="), - "53: " + getCheckMessage(MSG_KEY, "!="), - "58: " + getCheckMessage(MSG_KEY, "=="), - "59: " + getCheckMessage(MSG_KEY, "!="), - "67: " + getCheckMessage(MSG_KEY, "=="), - "71: " + getCheckMessage(MSG_KEY, "=="), - "72: " + getCheckMessage(MSG_KEY, "=="), - "73: " + getCheckMessage(MSG_KEY, "=="), - "74: " + getCheckMessage(MSG_KEY, "=="), - "76: " + getCheckMessage(MSG_KEY, "=="), - "77: " + getCheckMessage(MSG_KEY, "=="), - "78: " + getCheckMessage(MSG_KEY, "=="), - "84: " + getCheckMessage(MSG_KEY, "=="), - "85: " + getCheckMessage(MSG_KEY, "=="), - "86: " + getCheckMessage(MSG_KEY, "=="), - "97: " + getCheckMessage(MSG_KEY, "=="), - "101: " + getCheckMessage(MSG_KEY, "=="), - "111: " + getCheckMessage(MSG_KEY, "=="), - "112: " + getCheckMessage(MSG_KEY, "=="), + "24:20: " + getCheckMessage(MSG_KEY, "=="), + "25:15: " + getCheckMessage(MSG_KEY, "=="), + "27:18: " + getCheckMessage(MSG_KEY, "=="), + "28:18: " + getCheckMessage(MSG_KEY, "=="), + "29:16: " + getCheckMessage(MSG_KEY, "=="), + "30:18: " + getCheckMessage(MSG_KEY, "=="), + "31:19: " + getCheckMessage(MSG_KEY, "=="), + "46:18: " + getCheckMessage(MSG_KEY, "=="), + "47:18: " + getCheckMessage(MSG_KEY, "!="), + "52:18: " + getCheckMessage(MSG_KEY, "=="), + "53:18: " + getCheckMessage(MSG_KEY, "!="), + "58:18: " + getCheckMessage(MSG_KEY, "=="), + "59:18: " + getCheckMessage(MSG_KEY, "!="), + "67:30: " + getCheckMessage(MSG_KEY, "=="), + "71:36: " + getCheckMessage(MSG_KEY, "=="), + "72:37: " + getCheckMessage(MSG_KEY, "=="), + "73:19: " + getCheckMessage(MSG_KEY, "=="), + "74:37: " + getCheckMessage(MSG_KEY, "=="), + "76:42: " + getCheckMessage(MSG_KEY, "=="), + "77:18: " + getCheckMessage(MSG_KEY, "=="), + "78:18: " + getCheckMessage(MSG_KEY, "=="), + "78:42: " + getCheckMessage(MSG_KEY, "=="), + "84:25: " + getCheckMessage(MSG_KEY, "=="), + "85:23: " + getCheckMessage(MSG_KEY, "=="), + "86:33: " + getCheckMessage(MSG_KEY, "=="), + "97:21: " + getCheckMessage(MSG_KEY, "=="), + "101:23: " + getCheckMessage(MSG_KEY, "=="), + "111:19: " + getCheckMessage(MSG_KEY, "=="), + "112:40: " + getCheckMessage(MSG_KEY, "=="), + "118:15: " + getCheckMessage(MSG_KEY, "=="), + "119:15: " + getCheckMessage(MSG_KEY, "!="), + "120:15: " + getCheckMessage(MSG_KEY, "!="), + "121:18: " + getCheckMessage(MSG_KEY, "!="), + "129:15: " + getCheckMessage(MSG_KEY, "<"), + "130:15: " + getCheckMessage(MSG_KEY, "<="), + "131:15: " + getCheckMessage(MSG_KEY, ">"), + "132:15: " + getCheckMessage(MSG_KEY, ">="), }; - verify(checkConfig, getPath("InputAvoidConstantAsFirstOperandInConditionCheck.java"), expected); + verify(checkConfig, getPath("InputAvoidConstantAsFirstOperandInConditionCheck.java"), + expected); } @Test public void testAttributes() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(AvoidConstantAsFirstOperandInConditionCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidConstantAsFirstOperandInConditionCheck.class); checkConfig.addAttribute("targetConstantTypes", "LITERAL_FALSE,NUM_INT,NUM_FLOAT"); final String[] expected = { - "25: " + getCheckMessage(MSG_KEY, "=="), - "28: " + getCheckMessage(MSG_KEY, "=="), - "31: " + getCheckMessage(MSG_KEY, "=="), + "25:15: " + getCheckMessage(MSG_KEY, "=="), + "28:18: " + getCheckMessage(MSG_KEY, "=="), + "31:19: " + getCheckMessage(MSG_KEY, "=="), + "118:15: " + getCheckMessage(MSG_KEY, "=="), + "119:15: " + getCheckMessage(MSG_KEY, "!="), + "120:15: " + getCheckMessage(MSG_KEY, "!="), + "129:15: " + getCheckMessage(MSG_KEY, "<"), + "130:15: " + getCheckMessage(MSG_KEY, "<="), + "131:15: " + getCheckMessage(MSG_KEY, ">"), + "132:15: " + getCheckMessage(MSG_KEY, ">="), + }; + verify(checkConfig, getPath("InputAvoidConstantAsFirstOperandInConditionCheck.java"), + expected); + } + + @Test + public void testNullProperties() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidConstantAsFirstOperandInConditionCheck.class); + + checkConfig.addAttribute("targetConstantTypes", null); + + final String[] expected = { + "24:20: " + getCheckMessage(MSG_KEY, "=="), + "25:15: " + getCheckMessage(MSG_KEY, "=="), + "27:18: " + getCheckMessage(MSG_KEY, "=="), + "28:18: " + getCheckMessage(MSG_KEY, "=="), + "29:16: " + getCheckMessage(MSG_KEY, "=="), + "30:18: " + getCheckMessage(MSG_KEY, "=="), + "31:19: " + getCheckMessage(MSG_KEY, "=="), + "46:18: " + getCheckMessage(MSG_KEY, "=="), + "47:18: " + getCheckMessage(MSG_KEY, "!="), + "52:18: " + getCheckMessage(MSG_KEY, "=="), + "53:18: " + getCheckMessage(MSG_KEY, "!="), + "58:18: " + getCheckMessage(MSG_KEY, "=="), + "59:18: " + getCheckMessage(MSG_KEY, "!="), + "67:30: " + getCheckMessage(MSG_KEY, "=="), + "71:36: " + getCheckMessage(MSG_KEY, "=="), + "72:37: " + getCheckMessage(MSG_KEY, "=="), + "73:19: " + getCheckMessage(MSG_KEY, "=="), + "74:37: " + getCheckMessage(MSG_KEY, "=="), + "76:42: " + getCheckMessage(MSG_KEY, "=="), + "77:18: " + getCheckMessage(MSG_KEY, "=="), + "78:18: " + getCheckMessage(MSG_KEY, "=="), + "78:42: " + getCheckMessage(MSG_KEY, "=="), + "84:25: " + getCheckMessage(MSG_KEY, "=="), + "85:23: " + getCheckMessage(MSG_KEY, "=="), + "86:33: " + getCheckMessage(MSG_KEY, "=="), + "97:21: " + getCheckMessage(MSG_KEY, "=="), + "101:23: " + getCheckMessage(MSG_KEY, "=="), + "111:19: " + getCheckMessage(MSG_KEY, "=="), + "112:40: " + getCheckMessage(MSG_KEY, "=="), + "118:15: " + getCheckMessage(MSG_KEY, "=="), + "119:15: " + getCheckMessage(MSG_KEY, "!="), + "120:15: " + getCheckMessage(MSG_KEY, "!="), + "121:18: " + getCheckMessage(MSG_KEY, "!="), + "129:15: " + getCheckMessage(MSG_KEY, "<"), + "130:15: " + getCheckMessage(MSG_KEY, "<="), + "131:15: " + getCheckMessage(MSG_KEY, ">"), + "132:15: " + getCheckMessage(MSG_KEY, ">="), }; - verify(checkConfig, getPath("InputAvoidConstantAsFirstOperandInConditionCheck.java"), expected); + verify(checkConfig, getPath("InputAvoidConstantAsFirstOperandInConditionCheck.java"), + expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidDefaultSerializableInInnerClassesCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidDefaultSerializableInInnerClassesCheckTest.java index 76ae99715b..69cce8b6ce 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidDefaultSerializableInInnerClassesCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidDefaultSerializableInInnerClassesCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,79 +23,93 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class AvoidDefaultSerializableInInnerClassesCheckTest extends - BaseCheckTestSupport { +public class AvoidDefaultSerializableInInnerClassesCheckTest extends AbstractModuleTestSupport { + private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test - public void testWithAllowPartiaFalse() + public void testWithAllowPartialFalse() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(AvoidDefaultSerializableInInnerClassesCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidDefaultSerializableInInnerClassesCheck.class); final String[] expected = { - "33: " + warningMessage, - "45: " + warningMessage, - "52: " + warningMessage, - "59: " + warningMessage, - "67: " + warningMessage, - "74: " + warningMessage, - "97: " + warningMessage, - "104: " + warningMessage, - "121: " + warningMessage, - "134: " + warningMessage, - "145: " + warningMessage, - "159: " + warningMessage, - "171: " + warningMessage, - "179: " + warningMessage, - "187: " + warningMessage, + "33:48: " + warningMessage, + "45:31: " + warningMessage, + "52:31: " + warningMessage, + "59:30: " + warningMessage, + "67:9: " + warningMessage, + "74:30: " + warningMessage, + "97:30: " + warningMessage, + "104:34: " + warningMessage, + "121:30: " + warningMessage, + "134:30: " + warningMessage, + "145:36: " + warningMessage, + "159:42: " + warningMessage, + "171:39: " + warningMessage, + "179:42: " + warningMessage, + "187:35: " + warningMessage, }; - verify(checkConfig, getPath("InputAvoidDefaultSerializableInInnerClasses1.java"), expected); + verify(checkConfig, getPath("InputAvoidDefaultSerializableInInnerClassesCheck1.java"), + expected); } @Test public void testPrivateNotRealReadObject() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(AvoidDefaultSerializableInInnerClassesCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidDefaultSerializableInInnerClassesCheck.class); checkConfig.addAttribute("allowPartialImplementation", "true"); final String[] expected = { - "10: " + warningMessage, + "10:22: " + warningMessage, }; - verify(checkConfig, getPath("InputAvoidDefaultSerializableInInnerClasses2.java"), expected); + verify(checkConfig, getPath("InputAvoidDefaultSerializableInInnerClassesCheck2.java"), + expected); } @Test public void testRealReadObjectNotRealReadObjectRealPrivate() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(AvoidDefaultSerializableInInnerClassesCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidDefaultSerializableInInnerClassesCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputAvoidDefaultSerializableInInnerClasses3.java"), expected); + verify(checkConfig, getPath("InputAvoidDefaultSerializableInInnerClassesCheck3.java"), + expected); } @Test - public void testWithAllowPartiaTrue() + public void testWithAllowPartialTrue() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(AvoidDefaultSerializableInInnerClassesCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidDefaultSerializableInInnerClassesCheck.class); checkConfig.addAttribute("allowPartialImplementation", "true"); final String[] expected = { - "33: " + warningMessage, - "59: " + warningMessage, - "67: " + warningMessage, - "74: " + warningMessage, - "97: " + warningMessage, - "104: " + warningMessage, - "121: " + warningMessage, - "134: " + warningMessage, - "145: " + warningMessage, - "171: " + warningMessage, - "187: " + warningMessage, + "33:48: " + warningMessage, + "59:30: " + warningMessage, + "67:9: " + warningMessage, + "74:30: " + warningMessage, + "97:30: " + warningMessage, + "104:34: " + warningMessage, + "121:30: " + warningMessage, + "134:30: " + warningMessage, + "145:36: " + warningMessage, + "171:39: " + warningMessage, + "187:35: " + warningMessage, }; - verify(checkConfig, getPath("InputAvoidDefaultSerializableInInnerClasses1.java"), expected); + verify(checkConfig, getPath("InputAvoidDefaultSerializableInInnerClassesCheck1.java"), + expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidHidingCauseExceptionCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidHidingCauseExceptionCheckTest.java index be0bf6f7f4..e53606524d 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidHidingCauseExceptionCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidHidingCauseExceptionCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,14 +23,21 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; -public class AvoidHidingCauseExceptionCheckTest extends BaseCheckTestSupport { +public class AvoidHidingCauseExceptionCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public final void issue52Test() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(AvoidHidingCauseExceptionCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidHidingCauseExceptionCheck.class); final String[] expected = {}; @@ -39,7 +46,8 @@ public final void issue52Test() throws Exception { @Test public final void test() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(AvoidHidingCauseExceptionCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidHidingCauseExceptionCheck.class); final String[] expected = { "18:13: " + getCheckMessage(MSG_KEY, "e"), @@ -63,5 +71,14 @@ public final void test() throws Exception { verify(checkConfig, getPath("InputAvoidHidingCauseExceptionCheck.java"), expected); } + @Test + public final void testWrappingException() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidHidingCauseExceptionCheck.class); + + verify(checkConfig, getPath("InputAvoidHidingCauseExceptionCheckWrapping.java"), + CommonUtils.EMPTY_STRING_ARRAY); + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidModifiersForTypesCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidModifiersForTypesCheckTest.java index 609a281043..b48891a06f 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidModifiersForTypesCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidModifiersForTypesCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,11 +20,12 @@ package com.github.sevntu.checkstyle.checks.coding; import static com.github.sevntu.checkstyle.checks.coding.AvoidModifiersForTypesCheck.MSG_KEY; +import static org.junit.Assert.fail; import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; @@ -35,31 +36,27 @@ * @author Yasser Aziza *

      */ -public class AvoidModifiersForTypesCheckTest extends BaseCheckTestSupport { +public class AvoidModifiersForTypesCheckTest extends AbstractModuleTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(AvoidModifiersForTypesCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testFinal() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = "InputAvoidModifiersForTypesCheck"; - final String staticRegexp = null; - final String transientRegexp = null; - final String volatileRegexp = null; - final String publicRegexp = null; - final String packagePrivateRegexp = null; - final String protectedRegexp = null; - final String privateRegexp = null; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", null); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); final String[] expected = { "19:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "final"), @@ -73,29 +70,24 @@ public void testFinal() throws Exception { @Test public void testPackagePrivate() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = null; - final String staticRegexp = null; - final String transientRegexp = null; - final String volatileRegexp = null; - final String privateRegexp = null; - final String packagePrivateRegexp = "InputAvoidModifiersForTypesCheck"; - final String protectedRegexp = null; - final String publicRegexp = null; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", null); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", null); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", null); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", null); final String[] expected = { - "23:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "package-private"), - "24:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "package-private"), + "23:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", + "package-private"), + "24:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", + "package-private"), }; verify(checkConfig, getPath("InputAvoidModifiersForTypesCheck.java"), expected); @@ -103,25 +95,17 @@ public void testPackagePrivate() throws Exception { @Test public void testAnnotationPrivateStatic() throws Exception { - final String annotationRegexp = "File"; - final String finalRegexp = null; - final String staticRegexp = "File"; - final String transientRegexp = null; - final String volatileRegexp = null; - final String privateRegexp = "File"; - final String packagePrivateRegexp = null; - final String protectedRegexp = null; - final String publicRegexp = null; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", "File"); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", null); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", "File"); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", "File"); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", null); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", null); final String[] expected = { "18:5: " + getCheckMessage(MSG_KEY, "File", "annotation"), @@ -134,25 +118,19 @@ public void testAnnotationPrivateStatic() throws Exception { @Test public void testProtectedAndTransient() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = null; - final String staticRegexp = null; - final String transientRegexp = "InputAvoidModifiersForTypesCheck"; - final String volatileRegexp = null; - final String privateRegexp = null; - final String packagePrivateRegexp = null; - final String protectedRegexp = "InputAvoidModifiersForTypesCheck"; - final String publicRegexp = null; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", null); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", null); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", null); final String[] expected = { "21:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "protected"), @@ -164,25 +142,19 @@ public void testProtectedAndTransient() throws Exception { @Test public void testPublicAndVolatile() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = null; - final String staticRegexp = null; - final String transientRegexp = null; - final String volatileRegexp = "InputAvoidModifiersForTypesCheck"; - final String privateRegexp = null; - final String packagePrivateRegexp = null; - final String protectedRegexp = null; - final String publicRegexp = "InputAvoidModifiersForTypesCheck"; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", null); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", null); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", null); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", + "InputAvoidModifiersForTypesCheck"); final String[] expected = { "22:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "public"), @@ -194,32 +166,28 @@ public void testPublicAndVolatile() throws Exception { @Test public void testFinalAndPrivatePackage() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = "InputAvoidModifiersForTypesCheck"; - final String staticRegexp = null; - final String transientRegexp = null; - final String volatileRegexp = null; - final String privateRegexp = null; - final String packagePrivateRegexp = "InputAvoidModifiersForTypesCheck"; - final String protectedRegexp = null; - final String publicRegexp = null; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", null); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", null); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", null); final String[] expected = { "19:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "final"), "20:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "final"), - "23:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "package-private"), + "23:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", + "package-private"), "24:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "final"), - "24:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "package-private"), + "24:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", + "package-private"), "29:9: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "final"), }; @@ -228,25 +196,19 @@ public void testFinalAndPrivatePackage() throws Exception { @Test public void testFinalAndStatic() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = "InputAvoidModifiersForTypesCheck"; - final String staticRegexp = "InputAvoidModifiersForTypesCheck"; - final String transientRegexp = null; - final String volatileRegexp = null; - final String privateRegexp = null; - final String packagePrivateRegexp = null; - final String protectedRegexp = null; - final String publicRegexp = null; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", null); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", null); final String[] expected = { "19:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "final"), @@ -261,25 +223,18 @@ public void testFinalAndStatic() throws Exception { @Test public void testProtected() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = null; - final String staticRegexp = null; - final String transientRegexp = null; - final String volatileRegexp = null; - final String privateRegexp = null; - final String packagePrivateRegexp = null; - final String protectedRegexp = "InputAvoidModifiersForTypesCheck"; - final String publicRegexp = null; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", null); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", null); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", + "InputAvoidModifiersForTypesCheck"); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", null); final String[] expected = { "21:5: " + getCheckMessage(MSG_KEY, "InputAvoidModifiersForTypesCheck", "protected"), @@ -290,25 +245,17 @@ public void testProtected() throws Exception { @Test public void testLogger() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = null; - final String staticRegexp = null; - final String transientRegexp = null; - final String volatileRegexp = null; - final String privateRegexp = null; - final String packagePrivateRegexp = "Logger"; - final String protectedRegexp = "Logger"; - final String publicRegexp = "Logger"; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", null); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", null); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", "Logger"); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", "Logger"); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", "Logger"); final String[] expected = { "36:9: " + getCheckMessage(MSG_KEY, "Logger", "protected"), @@ -321,25 +268,17 @@ public void testLogger() throws Exception { @Test public void testAnyFile() throws Exception { - final String annotationRegexp = null; - final String finalRegexp = null; - final String staticRegexp = null; - final String transientRegexp = null; - final String volatileRegexp = null; - final String privateRegexp = null; - final String packagePrivateRegexp = null; - final String protectedRegexp = null; - final String publicRegexp = null; - - checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", annotationRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpFinal", finalRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpStatic", staticRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpTransient", transientRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpVolatile", volatileRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPrivate", privateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", packagePrivateRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpProtected", protectedRegexp); - checkConfig.addAttribute("forbiddenClassesRegexpPublic", publicRegexp); + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidModifiersForTypesCheck.class); + checkConfig.addAttribute("forbiddenClassesRegexpAnnotation", null); + checkConfig.addAttribute("forbiddenClassesRegexpFinal", null); + checkConfig.addAttribute("forbiddenClassesRegexpStatic", null); + checkConfig.addAttribute("forbiddenClassesRegexpTransient", null); + checkConfig.addAttribute("forbiddenClassesRegexpVolatile", null); + checkConfig.addAttribute("forbiddenClassesRegexpPrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpPackagePrivate", null); + checkConfig.addAttribute("forbiddenClassesRegexpProtected", null); + checkConfig.addAttribute("forbiddenClassesRegexpPublic", null); final String[] expected = {}; @@ -384,4 +323,5 @@ public void testUnsupportedModifier() { Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); } } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidNotShortCircuitOperatorsForBooleanCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidNotShortCircuitOperatorsForBooleanCheckTest.java index 402db71962..23612c23b5 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidNotShortCircuitOperatorsForBooleanCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/AvoidNotShortCircuitOperatorsForBooleanCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,15 +23,21 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; -public class AvoidNotShortCircuitOperatorsForBooleanCheckTest extends BaseCheckTestSupport { +public class AvoidNotShortCircuitOperatorsForBooleanCheckTest extends AbstractModuleTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(AvoidNotShortCircuitOperatorsForBooleanCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public final void testAll() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidNotShortCircuitOperatorsForBooleanCheck.class); final String[] expected = { "6:23: " + getCheckMessage(MSG_KEY, "|"), @@ -50,6 +56,26 @@ public final void testAll() throws Exception { "97:11: " + getCheckMessage(MSG_KEY, "|="), }; - verify(checkConfig, getPath("InputAvoidNotShortCircuitOperatorsForBooleanCheck.java"), expected); + verify(checkConfig, getPath("InputAvoidNotShortCircuitOperatorsForBooleanCheck.java"), + expected); + } + + @Test + public final void testNonClasses() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidNotShortCircuitOperatorsForBooleanCheck.class); + verify(checkConfig, + getPath("InputAvoidNotShortCircuitOperatorsForBooleanCheckNonClasses.java"), + CommonUtils.EMPTY_STRING_ARRAY); + } + + @Test + public final void testExpressionBeforeTry() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidNotShortCircuitOperatorsForBooleanCheck.class); + verify(checkConfig, + getPath("InputAvoidNotShortCircuitOperatorsForBooleanCheckLambdaWithMultiCatch.java"), + CommonUtils.EMPTY_STRING_ARRAY); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ConfusingConditionCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ConfusingConditionCheckTest.java index 21a0942293..dbc85bb2d9 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ConfusingConditionCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ConfusingConditionCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,45 +23,124 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; /** * @author Vadim Panasiuk */ -public class ConfusingConditionCheckTest extends BaseCheckTestSupport { +public class ConfusingConditionCheckTest extends AbstractModuleTestSupport { private final String warningMessage = getCheckMessage(MSG_KEY); - private final DefaultConfiguration checkConfig = createCheckConfig(ConfusingConditionCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testDefault() throws Exception { - checkConfig.addAttribute("ignoreInnerIf", "true"); - checkConfig.addAttribute("ignoreNullCaseInIf", "true"); - checkConfig.addAttribute("ignoreSequentialIf", "true"); - checkConfig.addAttribute("ignoreThrowInElse", "true"); - checkConfig.addAttribute("multiplyFactorForElseBlocks", "4"); + final DefaultConfiguration checkConfig = createModuleConfig(ConfusingConditionCheck.class); + + final String[] expected = { + "10:9: " + warningMessage, + "13:9: " + warningMessage, + "16:9: " + warningMessage, + "19:9: " + warningMessage, + "22:9: " + warningMessage, + "105:9: " + warningMessage, + "108:9: " + warningMessage, + "111:9: " + warningMessage, + "149:9: " + warningMessage, + "166:9: " + warningMessage, + "177:14: " + warningMessage, + "181:9: " + warningMessage, + "200:13: " + warningMessage, + "215:9: " + warningMessage, + "231:13: " + warningMessage, + "250:14: " + warningMessage, + "259:14: " + warningMessage, + }; + + verify(checkConfig, getPath("InputConfusingConditionCheck.java"), + expected); + } + + @Test + public void testFalseProperties() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ConfusingConditionCheck.class); + + checkConfig.addAttribute("ignoreInnerIf", "false"); + checkConfig.addAttribute("ignoreNullCaseInIf", "false"); + checkConfig.addAttribute("ignoreSequentialIf", "false"); + checkConfig.addAttribute("ignoreThrowInElse", "false"); + + final String[] expected = { + "10:9: " + warningMessage, + "13:9: " + warningMessage, + "16:9: " + warningMessage, + "19:9: " + warningMessage, + "22:9: " + warningMessage, + "105:9: " + warningMessage, + "108:9: " + warningMessage, + "111:9: " + warningMessage, + "127:21: " + warningMessage, + "134:9: " + warningMessage, + "138:9: " + warningMessage, + "145:9: " + warningMessage, + "149:9: " + warningMessage, + "157:9: " + warningMessage, + "160:9: " + warningMessage, + "162:9: " + warningMessage, + "166:9: " + warningMessage, + "177:14: " + warningMessage, + "181:9: " + warningMessage, + "199:9: " + warningMessage, + "200:13: " + warningMessage, + "215:9: " + warningMessage, + "227:9: " + warningMessage, + "231:13: " + warningMessage, + "247:9: " + warningMessage, + "250:14: " + warningMessage, + "257:9: " + warningMessage, + "259:14: " + warningMessage, + }; + + verify(checkConfig, getPath("InputConfusingConditionCheck.java"), + expected); + } + + @Test + public void testMultiplyFactor() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ConfusingConditionCheck.class); + + checkConfig.addAttribute("multiplyFactorForElseBlocks", "0"); final String[] expected = { - "10: " + warningMessage, - "13: " + warningMessage, - "16: " + warningMessage, - "19: " + warningMessage, - "22: " + warningMessage, - "105: " + warningMessage, - "108: " + warningMessage, - "111: " + warningMessage, - "149: " + warningMessage, - "166: " + warningMessage, - "177: " + warningMessage, - "181: " + warningMessage, - "200: " + warningMessage, - "215: " + warningMessage, - "231: " + warningMessage, + "10:9: " + warningMessage, + "13:9: " + warningMessage, + "16:9: " + warningMessage, + "19:9: " + warningMessage, + "22:9: " + warningMessage, + "105:9: " + warningMessage, + "108:9: " + warningMessage, + "111:9: " + warningMessage, + "177:14: " + warningMessage, + "259:14: " + warningMessage, }; verify(checkConfig, getPath("InputConfusingConditionCheck.java"), expected); } + + @Test + public void testExceptions() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ConfusingConditionCheck.class); + + final String[] expected = {}; + + verify(checkConfig, getPath("InputConfusingConditionCheck2.java"), + expected); + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/CustomDeclarationOrderCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/CustomDeclarationOrderCheckTest.java index 9688dbe786..fcf2c9141d 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/CustomDeclarationOrderCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/CustomDeclarationOrderCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -28,25 +28,41 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class CustomDeclarationOrderCheckTest extends BaseCheckTestSupport { +public class CustomDeclarationOrderCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test - public void testCustomDecrationOrder() throws Exception { + public void testCustomDeclarationOrder() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(CustomDeclarationOrderCheck.class); + createModuleConfig(CustomDeclarationOrderCheck.class); final String[] expected = { - "10:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(private static final long serialVersionUID)", "Field(.*final public .*|.*public final .*)"), + "10:5: " + getCheckMessage(MSG_KEY_FIELD, + "Field(private static final long serialVersionUID)", + "Field(.*final public .*|.*public final .*)"), "20:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(protected .*)", "Field(private .*)"), - "22:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(@SuppressWarnings(.*serial.*).*)", "Field(private .*)"), - "45:5: " + getCheckMessage(MSG_KEY_CONSTRUCTOR, "Ctor()", "Method(.*abstract .*public .*|.*public .*abstract .*|protected .*)"), - "52:5: " + getCheckMessage(MSG_KEY_METHOD, "Method(public static .*(new|edit|create).*)", "Method(.*abstract .*public .*|.*public .*abstract .*|protected .*)"), - "60:9: " + getCheckMessage(MSG_KEY_FIELD, "Field(.*final public .*|.*public final .*)", "Field(private .*)"), - "80:9: " + getCheckMessage(MSG_KEY_CLASS, "InnerClass (public .*abstract .*)", "InnerClass (private .*)"), - "84:5: " + getCheckMessage(MSG_KEY_METHOD, "Method(@Deprecated .*)", "InnerClass (private .*)"), - "95:5: " + getCheckMessage(MSG_KEY_METHOD, "Method(.*abstract .*public .*|.*public .*abstract .*|protected .*)", "InnerClass (private .*)"), + "22:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(@SuppressWarnings(.*serial.*).*)", + "Field(private .*)"), + "45:5: " + getCheckMessage(MSG_KEY_CONSTRUCTOR, "Ctor()", + "Method(.*abstract .*public .*|.*public .*abstract .*|protected .*)"), + "52:5: " + getCheckMessage(MSG_KEY_METHOD, + "Method(public static .*(new|edit|create).*)", + "Method(.*abstract .*public .*|.*public .*abstract .*|protected .*)"), + "60:9: " + getCheckMessage(MSG_KEY_FIELD, "Field(.*final public .*|.*public final .*)", + "Field(private .*)"), + "80:9: " + getCheckMessage(MSG_KEY_CLASS, "InnerClass (public .*abstract .*)", + "InnerClass (private .*)"), + "84:5: " + getCheckMessage(MSG_KEY_METHOD, "Method(@Deprecated .*)", + "InnerClass (private .*)"), + "95:5: " + getCheckMessage(MSG_KEY_METHOD, + "Method(.*abstract .*public .*|.*public .*abstract .*|protected .*)", + "InnerClass (private .*)"), "105:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(private .*)", "Ctor()"), }; checkConfig.addAttribute("customDeclarationOrder", @@ -59,32 +75,38 @@ public void testCustomDecrationOrder() throws Exception { + "Method(@Deprecated .*) ###" + "Method(public static .*(new|edit|create).*) ###" + "Method() ###" - + "Method(.*abstract .*public .*|.*public .*abstract .*|protected .*) ###" + + "Method(.*abstract .*public .*|.*public .*abstract .*|" + + "protected .*) ###" + "InnerClass (public .*abstract .*) ###" + "InnerClass (private .*)"); checkConfig.addAttribute("caseSensitive", "true"); - verify(checkConfig, getPath("InputCustomDeclarationOrder.java"), expected); - checkConfig.addAttribute("customDeclarationOrder", "Field .*final.*public|.*public.*final)"); + verify(checkConfig, getPath("InputCustomDeclarationOrderCheck.java"), expected); + checkConfig + .addAttribute("customDeclarationOrder", "Field .*final.*public|.*public.*final)"); } @Test public void anonymousClasses() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(CustomDeclarationOrderCheck.class); + createModuleConfig(CustomDeclarationOrderCheck.class); final String[] expected = { - "39:5: " + getCheckMessage(MSG_KEY_FIELD, "DeclareAnnonClassField(private .*)", "Field(public .*)"), - "54:5: " + getCheckMessage(MSG_KEY_FIELD, "DeclareAnnonClassField(private .*)", "Field(private .*)"), - "66:5: " + getCheckMessage(MSG_KEY_FIELD, "DeclareAnnonClassField()", "Ctor(public .*)"), - "95:9: " + getCheckMessage(MSG_KEY_FIELD, "DeclareAnnonClassField(private .*)", "Field(private .*)"), + "39:5: " + getCheckMessage(MSG_KEY_FIELD, "DeclareAnonClassField(private .*)", + "Field(public .*)"), + "54:5: " + getCheckMessage(MSG_KEY_FIELD, "DeclareAnonClassField(private .*)", + "Field(private .*)"), + "66:5: " + getCheckMessage(MSG_KEY_FIELD, "DeclareAnonClassField()", + "Ctor(public .*)"), + "95:9: " + getCheckMessage(MSG_KEY_FIELD, "DeclareAnonClassField(private .*)", + "Field(private .*)"), }; checkConfig .addAttribute( "customDeclarationOrder", - "DeclareAnnonClassField(private .*) ###" - + "DeclareAnnonClassField(protected .*) ###" - + "DeclareAnnonClassField() ###" - + "DeclareAnnonClassField(public .*) ###" + "DeclareAnonClassField(private .*) ###" + + "DeclareAnonClassField(protected .*) ###" + + "DeclareAnonClassField() ###" + + "DeclareAnonClassField(public .*) ###" + "Field(private .*) ###" + "Field(public .*) ###" + "Ctor(public .*) ###" @@ -99,7 +121,7 @@ public void anonymousClasses() public void gettersSetters() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(CustomDeclarationOrderCheck.class); + createModuleConfig(CustomDeclarationOrderCheck.class); final String[] expected = { "50:5: " + getCheckMessage(MSG_KEY_METHOD, "GetterSetter(.*)", "Method(.*)"), "56:5: " + getCheckMessage(MSG_KEY_METHOD, "GetterSetter(.*)", "Method(.*)"), @@ -107,11 +129,11 @@ public void gettersSetters() "66:5: " + getCheckMessage(MSG_KEY_METHOD, "GetterSetter(.*)", "Method(.*)"), "71:5: " + getCheckMessage(MSG_KEY_METHOD, "GetterSetter(.*)", "Method(.*)"), "76:5: " + getCheckMessage(MSG_KEY_METHOD, "GetterSetter(.*)", "Method(.*)"), - "91: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setField", "getField"), - "128: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setField", "getField"), - "133: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setX", "getX"), - "138: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setVisible", "isVisible"), - "168: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setField", "getField"), + "91:5: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setField", "getField"), + "128:5: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setField", "getField"), + "133:5: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setX", "getX"), + "138:5: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setVisible", "isVisible"), + "168:5: " + getCheckMessage(MSG_KEY_INVALID_SETTER, "setField", "getField"), "176:5: " + getCheckMessage(MSG_KEY_METHOD, "GetterSetter(.*)", "Method(.*)"), "180:5: " + getCheckMessage(MSG_KEY_METHOD, "GetterSetter(.*)", "Method(.*)"), "282:5: " + getCheckMessage(MSG_KEY_METHOD, "GetterSetter(.*)", "Method(.*)"), @@ -123,14 +145,15 @@ public void gettersSetters() "GetterSetter(.*) ### Method(.*)" ); checkConfig.addAttribute("caseSensitive", "false"); - verify(checkConfig, getPath("InputCustomDeclarationOrderCheckGettersSetters.java"), expected); + verify(checkConfig, getPath("InputCustomDeclarationOrderCheckGettersSetters.java"), + expected); } @Test public void innerInterfacesAndEnums() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(CustomDeclarationOrderCheck.class); + createModuleConfig(CustomDeclarationOrderCheck.class); final String[] expected = { "41:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(private )", "InnerInterface(.*)"), "49:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(private )", "InnerEnum(.*)"), @@ -140,17 +163,19 @@ public void innerInterfacesAndEnums() checkConfig.addAttribute( "customDeclarationOrder", - "Field(private ) ### Field(public ) ### Method(.*) ### InnerInterface(.*) ### InnerEnum(.*)" + "Field(private ) ### Field(public ) ### Method(.*) ### InnerInterface(.*) ### " + + "InnerEnum(.*)" ); checkConfig.addAttribute("caseSensitive", "true"); - verify(checkConfig, getPath("InputCustomDeclarationOrderCheckInnerInterfaceEnum.java"), expected); + verify(checkConfig, getPath("InputCustomDeclarationOrderCheckInnerInterfaceEnum.java"), + expected); } @Test public void mainMethod() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(CustomDeclarationOrderCheck.class); + createModuleConfig(CustomDeclarationOrderCheck.class); final String[] expected = { "10:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(private )", "MainMethod(.*)"), "17:5: " + getCheckMessage(MSG_KEY_FIELD, "Field(private )", "MainMethod(.*)"), @@ -163,4 +188,5 @@ public void mainMethod() checkConfig.addAttribute("caseSensitive", "false"); verify(checkConfig, getPath("InputCustomDeclarationOrderCheckMainMethod.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/DiamondOperatorForVariableDefinitionCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/DiamondOperatorForVariableDefinitionCheckTest.java index a7d3c3d4b9..3dfdc15dae 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/DiamondOperatorForVariableDefinitionCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/DiamondOperatorForVariableDefinitionCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,14 +23,20 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class DiamondOperatorForVariableDefinitionCheckTest extends BaseCheckTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(DiamondOperatorForVariableDefinitionCheck.class); +public class DiamondOperatorForVariableDefinitionCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testDefault() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(DiamondOperatorForVariableDefinitionCheck.class); final String[] expected = { "25:58: " + getCheckMessage(MSG_KEY), "27:26: " + getCheckMessage(MSG_KEY), diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/EitherLogOrThrowCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/EitherLogOrThrowCheckTest.java index adb45f6f96..a57219b820 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/EitherLogOrThrowCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/EitherLogOrThrowCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,41 +23,47 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; /** * Test for EitherLogOrThrowCheck. * @author Baratali Izmailov */ -public class EitherLogOrThrowCheckTest extends BaseCheckTestSupport { +public class EitherLogOrThrowCheckTest extends AbstractModuleTestSupport { + private final String warningMessage = getCheckMessage(MSG_KEY); - private final DefaultConfiguration checkConfig = createCheckConfig(EitherLogOrThrowCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void test() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(EitherLogOrThrowCheck.class); checkConfig.addAttribute("loggerFullyQualifiedClassName", "org.slf4j.Logger"); checkConfig.addAttribute("loggingMethodNames", "error, warn"); final String[] expected = { - "19: " + warningMessage, - "31: " + warningMessage, - "43: " + warningMessage, - "82: " + warningMessage, - "93: " + warningMessage, - "102: " + warningMessage, - "112: " + warningMessage, - "124: " + warningMessage, - "154: " + warningMessage, - "164: " + warningMessage, - "207: " + warningMessage, - "231: " + warningMessage, - "241: " + warningMessage, - "252: " + warningMessage, - "262: " + warningMessage, + "19:28: " + warningMessage, + "31:27: " + warningMessage, + "43:31: " + warningMessage, + "82:28: " + warningMessage, + "93:28: " + warningMessage, + "102:28: " + warningMessage, + "112:22: " + warningMessage, + "124:23: " + warningMessage, + "154:28: " + warningMessage, + "164:28: " + warningMessage, + "207:28: " + warningMessage, + "231:30: " + warningMessage, + "241:30: " + warningMessage, + "252:25: " + warningMessage, + "262:38: " + warningMessage, }; verify(checkConfig, getPath("InputEitherLogOrThrowCheck.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/EmptyPublicCtorInClassCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/EmptyPublicCtorInClassCheckTest.java index 54bca63757..251ac16369 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/EmptyPublicCtorInClassCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/EmptyPublicCtorInClassCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,105 +20,174 @@ package com.github.sevntu.checkstyle.checks.coding; import static com.github.sevntu.checkstyle.checks.coding.EmptyPublicCtorInClassCheck.MSG_KEY; +import static org.junit.Assert.fail; +import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; + +public class EmptyPublicCtorInClassCheckTest extends AbstractModuleTestSupport { -public class EmptyPublicCtorInClassCheckTest extends BaseCheckTestSupport { private final String message = getCheckMessage(MSG_KEY); - private DefaultConfiguration checkConfig = createCheckConfig(EmptyPublicCtorInClassCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testEmptyPublicCtor() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(EmptyPublicCtorInClassCheck.class); final String[] expected = { "5:5: " + message, }; - verify(checkConfig, getPath("InputEmptyPublicCtorInClass1.java"), expected); + verify(checkConfig, getPath("InputEmptyPublicCtorInClassCheck1.java"), expected); } @Test public void testEmptyPrivateCtor() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(EmptyPublicCtorInClassCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputEmptyPublicCtorInClass2.java"), expected); + verify(checkConfig, getPath("InputEmptyPublicCtorInClassCheck2.java"), expected); } @Test public void testEmptyProtectedCtor() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(EmptyPublicCtorInClassCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputEmptyPublicCtorInClass6.java"), expected); + verify(checkConfig, getPath("InputEmptyPublicCtorInClassCheck6.java"), expected); } @Test public void testClassWithMultiplePublicCtors() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(EmptyPublicCtorInClassCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputEmptyPublicCtorInClass3.java"), expected); + verify(checkConfig, getPath("InputEmptyPublicCtorInClassCheck3.java"), expected); } @Test public void testPublicNotEmptyCtor() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(EmptyPublicCtorInClassCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputEmptyPublicCtorInClass4.java"), expected); + verify(checkConfig, getPath("InputEmptyPublicCtorInClassCheck4.java"), expected); } @Test public void testClassWithInnerClasses() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(EmptyPublicCtorInClassCheck.class); final String[] expected = { "5:5: " + message, "14:9: " + message, }; - verify(checkConfig, getPath("InputEmptyPublicCtorInClass5.java"), expected); + verify(checkConfig, getPath("InputEmptyPublicCtorInClassCheck5.java"), expected); } @Test public void testCtorAnnotatedWithAnnotation() throws Exception { - final DefaultConfiguration config = createCheckConfig(EmptyPublicCtorInClassCheck.class); + final DefaultConfiguration config = createModuleConfig(EmptyPublicCtorInClassCheck.class); - config.addAttribute("ctorAnnotationNames", "com\\.github\\.sevntu\\.checkstyle\\.checks\\.coding\\.AnnotationName"); + config.addAttribute("ctorAnnotationNames", "com\\.github\\.sevntu\\.checkstyle\\.checks\\." + + "coding\\.AnnotationName"); final String[] expected = {}; - verify(config, getPath("InputEmptyPublicCtorInClass7.java"), expected); + verify(config, getPath("InputEmptyPublicCtorInClassCheck7.java"), expected); } @Test public void testClassAnnotatedWithAnnotation1() throws Exception { - final DefaultConfiguration config = createCheckConfig(EmptyPublicCtorInClassCheck.class); + final DefaultConfiguration config = createModuleConfig(EmptyPublicCtorInClassCheck.class); config.addAttribute("classAnnotationNames", "com\\.github\\.sevntu\\.checkstyle\\.checks\\.coding\\.AnnotationName|" + "org\\.junit\\.runner\\.RunWith|" + "org\\.junit\\.Ignore|" - + "com\\.github\\.sevntu\\.checkstyle\\.checks\\.coding\\.InputEmptyPublicCtorInClass9\\.InnerAnnotation"); + + "com\\.github\\.sevntu\\.checkstyle\\.checks\\.coding\\." + + "InputEmptyPublicCtorInClassCheck9\\.InnerAnnotation"); final String[] expected = {}; - verify(config, getPath("InputEmptyPublicCtorInClass8.java"), expected); + verify(config, getPath("InputEmptyPublicCtorInClassCheck8.java"), expected); } @Test public void testClassAnnotatedWithAnnotation2() throws Exception { - final DefaultConfiguration config = createCheckConfig(EmptyPublicCtorInClassCheck.class); + final DefaultConfiguration config = createModuleConfig(EmptyPublicCtorInClassCheck.class); config.addAttribute("classAnnotationNames", "org\\.junit\\.runner\\.RunWith|org\\.junit\\.Ignore|"); final String[] expected = {}; - verify(config, getPath("InputEmptyPublicCtorInClass10.java"), expected); + verify(config, getPath("InputEmptyPublicCtorInClassCheck10.java"), expected); + } + + @Test + public void testNullProperties1() throws Exception { + final DefaultConfiguration config = createModuleConfig(EmptyPublicCtorInClassCheck.class); + + config.addAttribute("classAnnotationNames", null); + config.addAttribute("ctorAnnotationNames", null); + + final String[] expected = { + "5:5: " + message, + "14:9: " + message, + }; + + verify(config, getPath("InputEmptyPublicCtorInClassCheck5.java"), expected); + } + + @Test + public void testNullProperties2() throws Exception { + final DefaultConfiguration config = createModuleConfig(EmptyPublicCtorInClassCheck.class); + + config.addAttribute("classAnnotationNames", ""); + config.addAttribute("ctorAnnotationNames", ""); + + final String[] expected = { + "5:5: " + message, + "14:9: " + message, + }; + + verify(config, getPath("InputEmptyPublicCtorInClassCheck5.java"), expected); + } + + @Test + public void testUnsupportedNode() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final EmptyPublicCtorInClassCheck check = new EmptyPublicCtorInClassCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/FinalizeImplementationCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/FinalizeImplementationCheckTest.java index 738f93bace..e54560826a 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/FinalizeImplementationCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/FinalizeImplementationCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -26,29 +26,43 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class FinalizeImplementationCheckTest extends BaseCheckTestSupport { +public class FinalizeImplementationCheckTest extends AbstractModuleTestSupport { - /** - * Default check configuration - */ - private final DefaultConfiguration checkConfig = - createCheckConfig(FinalizeImplementationCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public final void basicTest() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(FinalizeImplementationCheck.class); final String[] expected = { - "22: " + getCheckMessage(MSG_KEY_MISSED_TRY_FINALLY), - "35: " + getCheckMessage(MSG_KEY_MISSED_TRY_FINALLY), - "48: " + getCheckMessage(MSG_KEY_PUBLIC_FINALIZE), - "62: " + getCheckMessage(MSG_KEY_USELESS_FINALIZE), - "75: " + getCheckMessage(MSG_KEY_MISSED_SUPER_FINALIZE_CALL), + "22:5: " + getCheckMessage(MSG_KEY_MISSED_TRY_FINALLY), + "35:5: " + getCheckMessage(MSG_KEY_MISSED_TRY_FINALLY), + "48:5: " + getCheckMessage(MSG_KEY_PUBLIC_FINALIZE), + "62:5: " + getCheckMessage(MSG_KEY_USELESS_FINALIZE), + "75:3: " + getCheckMessage(MSG_KEY_MISSED_SUPER_FINALIZE_CALL), }; verify(checkConfig, getPath("InputFinalizeImplementationCheck.java"), expected); } + + @Test + public final void testSpecialFinalize() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(FinalizeImplementationCheck.class); + final String[] expected = { + "5:5: " + getCheckMessage(MSG_KEY_MISSED_TRY_FINALLY), + "18:5: " + getCheckMessage(MSG_KEY_MISSED_TRY_FINALLY), + }; + + verify(checkConfig, getPath("InputFinalizeImplementationCheckSpecial.java"), + expected); + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCCommentsInMethodsCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCCommentsInMethodsCheckTest.java index f7ff490fe8..174b60a09c 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCCommentsInMethodsCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCCommentsInMethodsCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,44 +23,53 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class ForbidCCommentsInMethodsCheckTest extends - BaseCheckTestSupport { +public class ForbidCCommentsInMethodsCheckTest extends AbstractModuleTestSupport { + private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void defaultTest() throws Exception { - - final DefaultConfiguration checkConfig = createCheckConfig(ForbidCCommentsInMethodsCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCCommentsInMethodsCheck.class); final String[] expected = { - "10: " + warningMessage, - "17: " + warningMessage, - "26: " + warningMessage, - "33: " + warningMessage, - "45: " + warningMessage, - "52: " + warningMessage, - "61: " + warningMessage, - "68: " + warningMessage, + "10:9: " + warningMessage, + "17:9: " + warningMessage, + "26:13: " + warningMessage, + "33:13: " + warningMessage, + "45:9: " + warningMessage, + "52:9: " + warningMessage, + "61:13: " + warningMessage, + "68:13: " + warningMessage, + "78:22: " + warningMessage, }; - verify(checkConfig, getPath("InputForbidCCommentsInMethods.java"), expected); + verify(checkConfig, getPath("InputForbidCCommentsInMethodsCheck.java"), expected); } @Test public void testFileWithoutComments() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidCCommentsInMethodsCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCCommentsInMethodsCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputForbidCCommentsInMethods2.java"), expected); + verify(checkConfig, getPath("InputForbidCCommentsInMethodsCheck2.java"), expected); } @Test public void testInterface() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidCCommentsInMethodsCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCCommentsInMethodsCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputForbidCCommentsInMethods3.java"), expected); + verify(checkConfig, getPath("InputForbidCCommentsInMethodsCheck3.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainImportsCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainImportsCheckTest.java index ec6a82ae6d..c3dc6f239f 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainImportsCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainImportsCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,79 +20,198 @@ package com.github.sevntu.checkstyle.checks.coding; import static com.github.sevntu.checkstyle.checks.coding.ForbidCertainImportsCheck.MSG_KEY; +import static org.junit.Assert.fail; +import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * @author Daniil * Yaroslavtsev */ -public class ForbidCertainImportsCheckTest extends BaseCheckTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(ForbidCertainImportsCheck.class); +public class ForbidCertainImportsCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testNormalWork() throws Exception { - final String importRegexp = ".+\\.api\\..+"; - + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); checkConfig.addAttribute("packageNameRegexp", ".+\\.sevntu\\..+"); - checkConfig.addAttribute("forbiddenImportsRegexp", importRegexp); + checkConfig.addAttribute("forbiddenImportsRegexp", ".+\\.api\\..+"); checkConfig.addAttribute("forbiddenImportsExcludesRegexp", ""); final String[] expected = { - "3: " + getCheckMessage(MSG_KEY, importRegexp, "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), - "9: " + getCheckMessage(MSG_KEY, importRegexp, "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), - "21: " + getCheckMessage(MSG_KEY, importRegexp, "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), + "3:1: " + getCheckMessage(MSG_KEY, ".+\\.api\\..+", + "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), + "9:1: " + getCheckMessage(MSG_KEY, ".+\\.api\\..+", + "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), + "21:30: " + getCheckMessage(MSG_KEY, ".+\\.api\\..+", + "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), }; - verify(checkConfig, getPath("InputForbidsCertainImports.java"), expected); + verify(checkConfig, getPath("InputForbidCertainImportsCheck.java"), expected); } @Test - public void testNormalWorkWithExcludes() throws Exception { - final String importRegexp = ".+\\.api\\..+"; + public void testNoPackageMatch() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); + checkConfig.addAttribute("packageNameRegexp", ".+\\.BAD\\..+"); + checkConfig.addAttribute("forbiddenImportsRegexp", ".+\\.api\\..+"); + checkConfig.addAttribute("forbiddenImportsExcludesRegexp", ""); + final String[] expected = {}; + + verify(checkConfig, getPath("InputForbidCertainImportsCheck.java"), expected); + } + + @Test + public void testNormalWorkWithExcludes() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); checkConfig.addAttribute("packageNameRegexp", ".+\\.sevntu\\..+"); - checkConfig.addAttribute("forbiddenImportsRegexp", importRegexp); + checkConfig.addAttribute("forbiddenImportsRegexp", ".+\\.api\\..+"); checkConfig.addAttribute("forbiddenImportsExcludesRegexp", "com.puppycrawl.+"); final String[] expected = {}; - verify(checkConfig, getPath("InputForbidsCertainImports.java"), expected); + verify(checkConfig, getPath("InputForbidCertainImportsCheck.java"), expected); } @Test public void testEmptyImportsAndDefaultPackage() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); checkConfig.addAttribute("packageNameRegexp", ".+\\.old\\..+"); checkConfig.addAttribute("forbiddenImportsRegexp", ".+\\.api\\..+"); checkConfig.addAttribute("forbiddenImportsExcludesRegexp", ""); final String[] expected = {}; - verify(checkConfig, getPath("InputForbidCertainImportsDefaultPackageWithoutImports.java"), expected); + verify(checkConfig, + getPath("InputForbidCertainImportsCheckDefaultPackageWithoutImports.java"), + expected); } @Test public void testEmptyParams() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); checkConfig.addAttribute("packageNameRegexp", ""); checkConfig.addAttribute("forbiddenImportsRegexp", ""); checkConfig.addAttribute("forbiddenImportsExcludesRegexp", ""); final String[] expected = {}; - verify(checkConfig, getPath("InputForbidCertainImportsDefaultPackageWithoutImports.java"), expected); + verify(checkConfig, + getPath("InputForbidCertainImportsCheckDefaultPackageWithoutImports.java"), + expected); + } + + @Test + public void testNullParams() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); + checkConfig.addAttribute("packageNameRegexp", null); + checkConfig.addAttribute("forbiddenImportsRegexp", null); + checkConfig.addAttribute("forbiddenImportsExcludesRegexp", null); + + final String[] expected = {}; + + verify(checkConfig, + getPath("InputForbidCertainImportsCheckDefaultPackageWithoutImports.java"), + expected); + } + + @Test + public void testPackageMatchButNullParams() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); + checkConfig.addAttribute("packageNameRegexp", ".+\\.sevntu\\..+"); + checkConfig.addAttribute("forbiddenImportsRegexp", null); + checkConfig.addAttribute("forbiddenImportsExcludesRegexp", null); + + final String[] expected = {}; + + verify(checkConfig, getPath("InputForbidCertainImportsCheck.java"), expected); + } + + @Test + public void testPackageForbiddenImportMatchButNullExclude() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); + checkConfig.addAttribute("packageNameRegexp", ".+\\.sevntu\\..+"); + checkConfig.addAttribute("forbiddenImportsRegexp", ".+\\.api\\..+"); + checkConfig.addAttribute("forbiddenImportsExcludesRegexp", null); + + final String[] expected = { + "3:1: " + getCheckMessage(MSG_KEY, ".+\\.api\\..+", + "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), + "9:1: " + getCheckMessage(MSG_KEY, ".+\\.api\\..+", + "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), + "21:30: " + getCheckMessage(MSG_KEY, ".+\\.api\\..+", + "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), + }; + + verify(checkConfig, getPath("InputForbidCertainImportsCheck.java"), expected); } @Test public void testNoImports() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); checkConfig.addAttribute("packageNameRegexp", ""); checkConfig.addAttribute("forbiddenImportsRegexp", ""); checkConfig.addAttribute("forbiddenImportsExcludesRegexp", ""); final String[] expected = {}; - verify(checkConfig, getPath("InputForbidCertainImportsDefaultPackageWithoutImports.java"), expected); + verify(checkConfig, + getPath("InputForbidCertainImportsCheckDefaultPackageWithoutImports.java"), + expected); + } + + @Test + public void testSinglePackage() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainImportsCheck.class); + checkConfig.addAttribute("packageNameRegexp", "sevntu"); + checkConfig.addAttribute("forbiddenImportsRegexp", ".+\\.api\\..+"); + checkConfig.addAttribute("forbiddenImportsExcludesRegexp", ""); + + final String[] expected = { + "3:1: " + getCheckMessage(MSG_KEY, ".+\\.api\\..+", + "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), + "10:30: " + getCheckMessage(MSG_KEY, ".+\\.api\\..+", + "com.puppycrawl.tools.checkstyle.api.AutomaticBean"), + }; + + verify(checkConfig, getPath("InputForbidCertainImportsCheckSinglePackage.java"), expected); + } + + @Test + public void testUnsupportedNode() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final ForbidCertainImportsCheck check = new ForbidCertainImportsCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainMethodCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainMethodCheckTest.java new file mode 100644 index 0000000000..bc63bda6e9 --- /dev/null +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidCertainMethodCheckTest.java @@ -0,0 +1,352 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.coding; + +import static com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck.MSG_KEY; + +import org.junit.Assert; +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; + +public class ForbidCertainMethodCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + + @Test + public void testEmptyRules() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java")); + } + + @Test + public void testNoArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "exit"); + final String[] expected = { + "22:20: " + getCheckMessage(MSG_KEY, "exit", "exit", "1", "0-"), + }; + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java"), expected); + } + + @Test + public void testWithEmptyArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "exit2"); + checkConfig.addAttribute("argumentCount", ""); + try { + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java")); + Assert.fail("Expecting CheckstyleException"); + } + catch (CheckstyleException ex) { + checkExceptionMessage(ex, + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to '' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + } + + @Test + public void testWithSpacesForArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "exit2"); + checkConfig.addAttribute("argumentCount", " "); + try { + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java")); + Assert.fail("Expecting CheckstyleException"); + } + catch (CheckstyleException ex) { + checkExceptionMessage(ex, + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to ' ' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + } + + @Test + public void testWithSpacesAndCommaForArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "exit2"); + checkConfig.addAttribute("argumentCount", " , "); + try { + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java")); + Assert.fail("Expecting CheckstyleException"); + } + catch (CheckstyleException ex) { + checkExceptionMessage(ex, + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to ' , ' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + } + + @Test + public void testWithNullArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "exit2"); + checkConfig.addAttribute("argumentCount", null); + try { + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java")); + Assert.fail("Expecting CheckstyleException"); + } + catch (CheckstyleException ex) { + checkExceptionMessage(ex, + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to 'null' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + } + + @Test + public void testWithRegexForMethodName() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "assert(True|False)"); + checkConfig.addAttribute("argumentCount", "1"); + + final String[] expected = { + "29:26: " + getCheckMessage(MSG_KEY, "assertTrue", "assert(True|False)", 1, + "1"), + }; + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java"), expected); + } + + @Test + public void testUnsupportedToken() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + try { + final ForbidCertainMethodCheck check = new ForbidCertainMethodCheck(); + check.visitToken(sync); + Assert.fail("Expecting IllegalArgumentException"); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } + } + + @Test + public void testNullMethodNameRegex() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", null); + try { + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java")); + Assert.fail("Expecting CheckstyleException"); + } + catch (CheckstyleException ex) { + checkExceptionMessage(ex, + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'methodName' to 'null' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + } + + @Test + public void testEmptyMethodNameRegex() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", ""); + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java")); + } + + @Test + public void testBadMethodNameRegex() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "[exit"); + try { + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java")); + Assert.fail("Expecting CheckstyleException"); + } + catch (CheckstyleException ex) { + checkExceptionMessage(ex, + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'methodName' to '[exit' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + } + + @Test + public void testBadRangeForArgumentCount() throws Exception { + testBadRangeInner("badArgCount", + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to 'badArgCount' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + + @Test + public void testBadRange2ForArgumentCount() throws Exception { + testBadRangeInner("badStart-badEnd", + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to 'badStart-badEnd' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + + @Test + public void testBadRange3ForArgumentCount() throws Exception { + testBadRangeInner("2, badStart-badEnd", + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to '2, badStart-badEnd' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + + @Test + public void testBadRange4ForArgumentCount() throws Exception { + testBadRangeInner(" , 1-4 ", + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to ' , 1-4 ' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + + @Test + public void testUnboundedRangeForArgumentCount() throws Exception { + testBadRangeInner(" - ", + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to ' - ' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + + @Test + public void testRangeWithBadBoundsForArgumentCount() throws Exception { + testBadRangeInner("10-1", + "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'argumentCount' to '10-1' in module " + + "com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck"); + } + + private void testBadRangeInner(String value, String expectedMessage) throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "exit"); + checkConfig.addAttribute("argumentCount", value); + final String[] expected = { + }; + try { + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java"), expected); + Assert.fail("Expecting CheckstyleException"); + } + catch (CheckstyleException ex) { + checkExceptionMessage(ex, + expectedMessage); + } + } + + @Test + public void testRangeForArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "assert(True|False)"); + checkConfig.addAttribute("argumentCount", "0-1"); + + final String[] expected = { + "29:26: " + getCheckMessage(MSG_KEY, "assertTrue", "assert(True|False)", 1, + "0-1"), + }; + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java"), expected); + } + + @Test + public void testRangeWithSpaceForArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "assert(True|False)"); + checkConfig.addAttribute("argumentCount", " 0 - 1 "); + + final String[] expected = { + "29:26: " + getCheckMessage(MSG_KEY, "assertTrue", "assert(True|False)", 1, + " 0 - 1 "), + }; + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java"), expected); + } + + @Test + public void testLeftOpenRangeForArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "assert(True|False)"); + checkConfig.addAttribute("argumentCount", "-1"); + + final String[] expected = { + "29:26: " + getCheckMessage(MSG_KEY, "assertTrue", "assert(True|False)", 1, + "-1"), + }; + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java"), expected); + } + + @Test + public void testRightOpenRangeForArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "assert(True|False)"); + checkConfig.addAttribute("argumentCount", "0-"); + + final String[] expected = { + "29:26: " + getCheckMessage(MSG_KEY, + "assertTrue", "assert(True|False)", 1, "0-"), + "30:26: " + getCheckMessage(MSG_KEY, + "assertTrue", "assert(True|False)", 2, "0-"), + }; + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java"), expected); + } + + @Test + public void testMultipleRangesForArgumentCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidCertainMethodCheck.class); + checkConfig.addAttribute("methodName", "asList"); + // allow arg count 4, 8 + checkConfig.addAttribute("argumentCount", "-3, 5-7, 9-"); + + final String[] expected = { + "43:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 1, "-3, 5-7, 9-"), + "44:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 2, "-3, 5-7, 9-"), + "45:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 3, "-3, 5-7, 9-"), + "47:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 5, "-3, 5-7, 9-"), + "48:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 6, "-3, 5-7, 9-"), + "49:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 7, "-3, 5-7, 9-"), + "51:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 9, "-3, 5-7, 9-"), + "52:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 10, "-3, 5-7, 9-"), + "53:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 11, "-3, 5-7, 9-"), + "54:26: " + getCheckMessage(MSG_KEY, "asList", "asList", 12, "-3, 5-7, 9-"), + }; + verify(checkConfig, getPath("InputForbidCertainMethodCheck.java"), expected); + } + + private static void checkExceptionMessage(Exception exception, String expectedMessage) { + Assert.assertEquals("Exception did not have correct error message.", + expectedMessage, + exception.getMessage()); + } + +} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidInstantiationCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidInstantiationCheckTest.java index 8641b14ca1..1eca4183ba 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidInstantiationCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidInstantiationCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,22 +20,42 @@ package com.github.sevntu.checkstyle.checks.coding; import static com.github.sevntu.checkstyle.checks.coding.ForbidInstantiationCheck.MSG_KEY; +import static org.junit.Assert.fail; +import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * @author Daniil * Yaroslavtsev */ -public class ForbidInstantiationCheckTest extends BaseCheckTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(ForbidInstantiationCheck.class); +public class ForbidInstantiationCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test - public void testNullPointerException() throws Exception { + public void testNullProperties() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidInstantiationCheck.class); + checkConfig.addAttribute("forbiddenClasses", null); + final String[] expected = {}; + + verify(checkConfig, getPath("InputForbidInstantiationCheck.java"), expected); + } + + @Test + public void testNullPointerException() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidInstantiationCheck.class); checkConfig.addAttribute("forbiddenClasses", "java.lang.NullPointerException"); final String[] expected = { @@ -48,7 +68,8 @@ public void testNullPointerException() throws Exception { @Test public void testNormalWork() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidInstantiationCheck.class); checkConfig.addAttribute("forbiddenClasses", "java.io.File , java.lang.String , "); final String[] expected = { @@ -62,11 +83,13 @@ public void testNormalWork() throws Exception { @Test public void testNormalWork2() throws Exception { - - checkConfig.addAttribute("forbiddenClasses", "com.github.sevntu.checkstyle.checks.test.utils.File"); + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidInstantiationCheck.class); + checkConfig.addAttribute("forbiddenClasses", + "com.github.sevntu.checkstyle.checks.coding.InputForbidInstantiationCheck"); final String[] expected = { - "12:68: " + getCheckMessage(MSG_KEY, "File"), + "12:89: " + getCheckMessage(MSG_KEY, "InputForbidInstantiationCheck"), }; verify(checkConfig, getPath("InputForbidInstantiationCheckWithoutDots.java"), expected); @@ -74,7 +97,8 @@ public void testNormalWork2() throws Exception { @Test public void testNormalWork3() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidInstantiationCheck.class); checkConfig.addAttribute("forbiddenClasses", "java.io.File , java.lang.String , "); final String[] expected = { @@ -87,7 +111,8 @@ public void testNormalWork3() throws Exception { @Test public void testAsteriskInInput() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidInstantiationCheck.class); checkConfig.addAttribute("forbiddenClasses", "java.io.File , java.lang.String , "); final String[] expected = { @@ -98,4 +123,21 @@ public void testAsteriskInInput() throws Exception { verify(checkConfig, getPath("InputForbidInstantiationCheckWithAsterisk.java"), expected); } + + @Test + public void testUnsupportedNode() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final ForbidInstantiationCheck check = new ForbidInstantiationCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidReturnInFinallyBlockCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidReturnInFinallyBlockCheckTest.java index d828d87b38..4467855e3a 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidReturnInFinallyBlockCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidReturnInFinallyBlockCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,28 +23,35 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class ForbidReturnInFinallyBlockCheckTest - extends BaseCheckTestSupport { +public class ForbidReturnInFinallyBlockCheckTest extends AbstractModuleTestSupport { + /** * An error message for current check. */ private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void testDefault() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(ForbidReturnInFinallyBlockCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidReturnInFinallyBlockCheck.class); final String[] expected = { - "13: " + warningMessage, - "28: " + warningMessage, - "49: " + warningMessage, - "56: " + warningMessage, - "82: " + warningMessage, + "13:13: " + warningMessage, + "28:13: " + warningMessage, + "49:13: " + warningMessage, + "56:17: " + warningMessage, + "82:13: " + warningMessage, }; verify(checkConfig, getPath("InputForbidReturnInFinallyBlockCheck.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsCheckTest.java similarity index 50% rename from sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsTest.java rename to sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsCheckTest.java index 0ba3bc31d8..621e0ee4ca 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ForbidThrowAnonymousExceptionsCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,67 +23,70 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class ForbidThrowAnonymousExceptionsTest extends BaseCheckTestSupport { +public class ForbidThrowAnonymousExceptionsCheckTest extends AbstractModuleTestSupport { - /** - * Default check configuration - */ - private final DefaultConfiguration checkConfig = - createCheckConfig(ForbidThrowAnonymousExceptionsCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public final void anonymousExceptionTest() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidThrowAnonymousExceptionsCheck.class); final String[] expected = { - "8: " + getCheckMessage(MSG_KEY), + "8:23: " + getCheckMessage(MSG_KEY), }; verify(checkConfig, - getPath("InputForbidThrowAnonymousExceptions.java"), expected); + getPath("InputForbidThrowAnonymousExceptionsCheck.java"), expected); } @Test public final void preDefinedAnonymousExceptionTest() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidThrowAnonymousExceptionsCheck.class); final String[] expected = { - "8: " + getCheckMessage(MSG_KEY), - "30: " + getCheckMessage(MSG_KEY), + "8:15: " + getCheckMessage(MSG_KEY), + "30:13: " + getCheckMessage(MSG_KEY), }; verify(checkConfig, - getPath("InputForbidThrowAnonymousExceptions2.java"), expected); + getPath("InputForbidThrowAnonymousExceptionsCheck2.java"), expected); } @Test public final void sameNameExceptionsTest() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidThrowAnonymousExceptionsCheck.class); final String[] expected = { - "12: " + getCheckMessage(MSG_KEY), - "23: " + getCheckMessage(MSG_KEY), - "66: " + getCheckMessage(MSG_KEY), - "88: " + getCheckMessage(MSG_KEY), - "107: " + getCheckMessage(MSG_KEY), - "127: " + getCheckMessage(MSG_KEY), + "12:15: " + getCheckMessage(MSG_KEY), + "23:13: " + getCheckMessage(MSG_KEY), + "66:9: " + getCheckMessage(MSG_KEY), + "88:9: " + getCheckMessage(MSG_KEY), + "107:9: " + getCheckMessage(MSG_KEY), + "127:9: " + getCheckMessage(MSG_KEY), }; verify(checkConfig, - getPath("InputForbidThrowAnonymousExceptions3.java"), expected); + getPath("InputForbidThrowAnonymousExceptionsCheck3.java"), expected); } @Test public final void nonStandardExceptionClassNameTest() throws Exception { - final String exceptionNameRegex = "^.*bla"; - checkConfig.addAttribute("exceptionClassNameRegex", exceptionNameRegex); + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidThrowAnonymousExceptionsCheck.class); + checkConfig.addAttribute("exceptionClassNameRegex", "^.*bla"); final String[] expected = { - "10: " + getCheckMessage(MSG_KEY), - "12: " + getCheckMessage(MSG_KEY), + "10:13: " + getCheckMessage(MSG_KEY), + "12:13: " + getCheckMessage(MSG_KEY), }; verify(checkConfig, - getPath("InputForbidThrowAnonymousExceptionsAnotherClassName.java"), expected); + getPath("InputForbidThrowAnonymousExceptionsCheckAnotherClassName.java"), expected); } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/IllegalCatchExtendedCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/IllegalCatchExtendedCheckTest.java index 2d12d622a5..faf851ca94 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/IllegalCatchExtendedCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/IllegalCatchExtendedCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,15 +23,20 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class IllegalCatchExtendedCheckTest extends BaseCheckTestSupport { +public class IllegalCatchExtendedCheckTest extends AbstractModuleTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(IllegalCatchExtendedCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public final void testDefault() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(IllegalCatchExtendedCheck.class); final String[] expected = { "9:9: " + getCheckMessage(MSG_KEY, "RuntimeException"), "11:9: " + getCheckMessage(MSG_KEY, "java.lang.Exception"), @@ -44,12 +49,13 @@ public final void testDefault() throws Exception { checkConfig.addAttribute("allowThrow", "false"); checkConfig.addAttribute("allowRethrow", "false"); - verify(checkConfig, getPath("InputIllegalCatchCheckNew.java"), expected); + verify(checkConfig, getPath("InputIllegalCatchExtendedCheckNew.java"), expected); } @Test public final void testThrowPermit() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(IllegalCatchExtendedCheck.class); final String[] expected = { "9:9: " + getCheckMessage(MSG_KEY, "RuntimeException"), "11:9: " + getCheckMessage(MSG_KEY, "java.lang.Exception"), @@ -61,11 +67,13 @@ public final void testThrowPermit() throws Exception { checkConfig.addAttribute("allowThrow", "true"); checkConfig.addAttribute("allowRethrow", "false"); - verify(checkConfig, getPath("InputIllegalCatchCheckNew.java"), expected); + verify(checkConfig, getPath("InputIllegalCatchExtendedCheckNew.java"), expected); } @Test public final void testReThrowPermit() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(IllegalCatchExtendedCheck.class); checkConfig.addAttribute("illegalClassNames", "java.lang.Error, java.lang.Exception, java.lang.Throwable"); @@ -77,7 +85,25 @@ public final void testReThrowPermit() throws Exception { checkConfig.addAttribute("allowThrow", "false"); checkConfig.addAttribute("allowRethrow", "true"); - verify(checkConfig, getPath("InputIllegalCatchCheckNew.java"), expected); + verify(checkConfig, getPath("InputIllegalCatchExtendedCheckNew.java"), expected); + } + + @Test + public void testIllegalClassNames() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(IllegalCatchExtendedCheck.class); + checkConfig.addAttribute("illegalClassNames", + "java.lang.Error, java.lang.Exception, NullPointerException"); + + // check that incorrect names don't break the Check + checkConfig.addAttribute("illegalClassNames", + "java.lang.IOException."); + + final String[] expected = { + "11:9: " + getCheckMessage(MSG_KEY, "java.lang.Exception"), + }; + + verify(checkConfig, getPath("InputIllegalCatchExtendedCheckNew.java"), expected); } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/LogicConditionNeedOptimizationCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/LogicConditionNeedOptimizationCheckTest.java index a00adcfb5a..b934a057a5 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/LogicConditionNeedOptimizationCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/LogicConditionNeedOptimizationCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,33 +23,47 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class LogicConditionNeedOptimizationCheckTest extends BaseCheckTestSupport { +public class LogicConditionNeedOptimizationCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void test() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(LogicConditionNeedOptimizationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(LogicConditionNeedOptimizationCheck.class); final String[] expected = { - "26: " + getCheckMessage(MSG_KEY, "&&", 26, 27), - "28: " + getCheckMessage(MSG_KEY, "&&", 28, 21), - "28: " + getCheckMessage(MSG_KEY, "||", 28, 31), - "38: " + getCheckMessage(MSG_KEY, "&&", 38, 21), - "40: " + getCheckMessage(MSG_KEY, "&&", 40, 38), - "45: " + getCheckMessage(MSG_KEY, "&&", 45, 25), - "47: " + getCheckMessage(MSG_KEY, "&&", 47, 42), - "57: " + getCheckMessage(MSG_KEY, "&&", 57, 18), - "59: " + getCheckMessage(MSG_KEY, "&&", 59, 35), - "60: " + getCheckMessage(MSG_KEY, "&&", 60, 19), - "60: " + getCheckMessage(MSG_KEY, "&&", 60, 29), - "62: " + getCheckMessage(MSG_KEY, "&&", 62, 21), - "66: " + getCheckMessage(MSG_KEY, "&&", 66, 19), - "67: " + getCheckMessage(MSG_KEY, "&&", 67, 38), - "69: " + getCheckMessage(MSG_KEY, "&&", 69, 35), - "72: " + getCheckMessage(MSG_KEY, "&&", 72, 19), - "93: " + getCheckMessage(MSG_KEY, "||", 93, 33), + "26:42: " + getCheckMessage(MSG_KEY, "&&", 26, 27), + "28:36: " + getCheckMessage(MSG_KEY, "&&", 28, 21), + "28:46: " + getCheckMessage(MSG_KEY, "||", 28, 31), + "38:36: " + getCheckMessage(MSG_KEY, "&&", 38, 21), + "40:53: " + getCheckMessage(MSG_KEY, "&&", 40, 38), + "45:40: " + getCheckMessage(MSG_KEY, "&&", 45, 25), + "47:57: " + getCheckMessage(MSG_KEY, "&&", 47, 42), + "57:33: " + getCheckMessage(MSG_KEY, "&&", 57, 18), + "59:50: " + getCheckMessage(MSG_KEY, "&&", 59, 35), + "60:34: " + getCheckMessage(MSG_KEY, "&&", 60, 19), + "60:44: " + getCheckMessage(MSG_KEY, "&&", 60, 29), + "62:36: " + getCheckMessage(MSG_KEY, "&&", 62, 21), + "66:34: " + getCheckMessage(MSG_KEY, "&&", 66, 19), + "67:53: " + getCheckMessage(MSG_KEY, "&&", 67, 38), + "69:50: " + getCheckMessage(MSG_KEY, "&&", 69, 35), + "72:34: " + getCheckMessage(MSG_KEY, "&&", 72, 19), + "93:34: " + getCheckMessage(MSG_KEY, "||", 93, 33), + "103:35: " + getCheckMessage(MSG_KEY, "&&", 103, 34), + "104:46: " + getCheckMessage(MSG_KEY, "&&", 104, 45), + "105:47: " + getCheckMessage(MSG_KEY, "&&", 105, 46), + "106:47: " + getCheckMessage(MSG_KEY, "||", 106, 46), + "110:33: " + getCheckMessage(MSG_KEY, "&&", 110, 32), + "117:29: " + getCheckMessage(MSG_KEY, "&&", 117, 28), + "118:29: " + getCheckMessage(MSG_KEY, "&&", 118, 28), }; - verify(checkConfig, getPath("InputLogicConditionsNeedOptimizationCheck.java"), expected); + verify(checkConfig, getPath("InputLogicConditionNeedOptimizationCheck.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopCheckTest.java similarity index 66% rename from sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopTest.java rename to sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopCheckTest.java index 8df50b3e8b..73e787744b 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MapIterationInForEachLoopCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -25,19 +25,21 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; -public class MapIterationInForEachLoopTest extends BaseCheckTestSupport { +public class MapIterationInForEachLoopCheckTest extends AbstractModuleTestSupport { - /** - * Default check configuration - */ - private final DefaultConfiguration checkConfig = - createCheckConfig(MapIterationInForEachLoopCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public final void basicTest() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MapIterationInForEachLoopCheck.class); checkConfig.addAttribute("proposeValuesUsage", "true"); checkConfig.addAttribute("proposeKeySetUsage", "true"); checkConfig.addAttribute("proposeEntrySetUsage", "true"); @@ -55,11 +57,13 @@ public final void basicTest() throws Exception { }; verify(checkConfig, - getPath("InputMapIterationInForEachLoop.java"), expected); + getPath("InputMapIterationInForEachLoopCheck.java"), expected); } @Test public final void importsWithoutFullPathTest() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MapIterationInForEachLoopCheck.class); checkConfig.addAttribute("proposeValuesUsage", "true"); checkConfig.addAttribute("proposeKeySetUsage", "true"); checkConfig.addAttribute("proposeEntrySetUsage", "true"); @@ -68,31 +72,40 @@ public final void importsWithoutFullPathTest() throws Exception { "12:9: " + getCheckMessage(MSG_KEY_ENTRYSET), }; verify(checkConfig, - getPath("InputMapIterationInForEachLoopImport.java"), + getPath("InputMapIterationInForEachLoopCheckImport.java"), expected); } @Test public final void skipIfConditionTest() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MapIterationInForEachLoopCheck.class); checkConfig.addAttribute("proposeValuesUsage", "false"); checkConfig.addAttribute("proposeKeySetUsage", "true"); checkConfig.addAttribute("proposeEntrySetUsage", "true"); - - final String supportedMapImplQualifiedNames = - "java.util.Map, " - + "java.util.HashMap, java.util.TreeMap, " - + "com.myTest.MyMap"; - checkConfig.addAttribute("supportedMapImplQualifiedNames", - supportedMapImplQualifiedNames); + "java.util.Map, java.util.HashMap, java.util.TreeMap, com.myTest.InputMyMap"); final String[] expected = { "14:9: " + getCheckMessage(MSG_KEY_ENTRYSET), }; verify(checkConfig, - getPath("InputMapIterationInForEachLoopSkipIf.java"), + getPath("InputMapIterationInForEachLoopCheckSkipIf.java"), expected); } + @Test + public final void testClassExtendingMap() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MapIterationInForEachLoopCheck.class); + checkConfig.addAttribute("proposeValuesUsage", "true"); + checkConfig.addAttribute("proposeKeySetUsage", "true"); + checkConfig.addAttribute("proposeEntrySetUsage", "true"); + + verify(checkConfig, + getPath("InputMapIterationInForEachLoopCheckExtendingMap.java"), + CommonUtils.EMPTY_STRING_ARRAY); + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MoveVariableInsideIfCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MoveVariableInsideIfCheckTest.java new file mode 100644 index 0000000000..4780171115 --- /dev/null +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MoveVariableInsideIfCheckTest.java @@ -0,0 +1,72 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.coding; + +import static com.github.sevntu.checkstyle.checks.coding.MoveVariableInsideIfCheck.MSG_KEY; + +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; + +public class MoveVariableInsideIfCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + + @Test + public final void testNoViolations() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MoveVariableInsideIfCheck.class); + verify(checkConfig, getPath("InputMoveVariableInsideIfCheckNoViolations.java"), + CommonUtils.EMPTY_STRING_ARRAY); + } + + @Test + public final void testViolations() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MoveVariableInsideIfCheck.class); + final String[] expected = { + "5:9: " + getCheckMessage(MSG_KEY, "variable", "7"), + "13:9: " + getCheckMessage(MSG_KEY, "variable", "15"), + "24:9: " + getCheckMessage(MSG_KEY, "variable", "26"), + "33:9: " + getCheckMessage(MSG_KEY, "variable", "38"), + "44:9: " + getCheckMessage(MSG_KEY, "variable", "48"), + }; + verify(checkConfig, getPath("InputMoveVariableInsideIfCheckViolations.java"), expected); + } + + @Test + public final void testFalsePositives() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MoveVariableInsideIfCheck.class); + final String[] expected = { + "9:9: " + getCheckMessage(MSG_KEY, "variable", "12"), + "18:9: " + getCheckMessage(MSG_KEY, "variable", "24"), + "30:9: " + getCheckMessage(MSG_KEY, "variable", "34"), + }; + verify(checkConfig, getPath("InputMoveVariableInsideIfCheckFalsePositives.java"), + expected); + } + +} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleStringLiteralsExtendedCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleStringLiteralsExtendedCheckTest.java index 8faeda24c7..092e886557 100755 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleStringLiteralsExtendedCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleStringLiteralsExtendedCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,14 +23,20 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class MultipleStringLiteralsExtendedCheckTest extends BaseCheckTestSupport { +public class MultipleStringLiteralsExtendedCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(MultipleStringLiteralsExtendedCheck.class); + createModuleConfig(MultipleStringLiteralsExtendedCheck.class); checkConfig.addAttribute("allowedDuplicates", "2"); checkConfig.addAttribute("ignoreStringsRegexp", ""); checkConfig.addAttribute("highlightAllDuplicates", "false"); @@ -41,13 +47,14 @@ public void testIt() throws Exception { "10:23: " + getCheckMessage(MSG_KEY, "\", \"", 3), }; - verify(checkConfig, getPath("InputMultipleStringLiterals.java"), expected); + verify(checkConfig, getPath("InputMultipleStringLiteralsExtendedCheck.java"), expected); } @Test public void testItAndShowAllWarnings() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(MultipleStringLiteralsExtendedCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(MultipleStringLiteralsExtendedCheck.class); checkConfig.addAttribute("allowedDuplicates", "2"); checkConfig.addAttribute("ignoreStringsRegexp", ""); checkConfig.addAttribute("highlightAllDuplicates", "true"); @@ -65,13 +72,13 @@ public void testItAndShowAllWarnings() "14:28: " + getCheckMessage(MSG_KEY, "\"StringContents\"", 3), }; - verify(checkConfig, getPath("InputMultipleStringLiterals.java"), expected); + verify(checkConfig, getPath("InputMultipleStringLiteralsExtendedCheck.java"), expected); } @Test public void testItIgnoreEmpty() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(MultipleStringLiteralsExtendedCheck.class); + createModuleConfig(MultipleStringLiteralsExtendedCheck.class); checkConfig.addAttribute("allowedDuplicates", "2"); checkConfig.addAttribute("highlightAllDuplicates", "false"); @@ -80,13 +87,13 @@ public void testItIgnoreEmpty() throws Exception { "10:23: " + getCheckMessage(MSG_KEY, "\", \"", 3), }; - verify(checkConfig, getPath("InputMultipleStringLiterals.java"), expected); + verify(checkConfig, getPath("InputMultipleStringLiteralsExtendedCheck.java"), expected); } @Test public void testItIgnoreEmptyAndComaSpace() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(MultipleStringLiteralsExtendedCheck.class); + createModuleConfig(MultipleStringLiteralsExtendedCheck.class); checkConfig.addAttribute("allowedDuplicates", "2"); checkConfig.addAttribute("ignoreStringsRegexp", "^((\"\")|(\", \"))$"); checkConfig.addAttribute("highlightAllDuplicates", "false"); @@ -95,13 +102,13 @@ public void testItIgnoreEmptyAndComaSpace() throws Exception { "5:16: " + getCheckMessage(MSG_KEY, "\"StringContents\"", 3), }; - verify(checkConfig, getPath("InputMultipleStringLiterals.java"), expected); + verify(checkConfig, getPath("InputMultipleStringLiteralsExtendedCheck.java"), expected); } @Test public void testItWithoutIgnoringAnnotations() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(MultipleStringLiteralsExtendedCheck.class); + createModuleConfig(MultipleStringLiteralsExtendedCheck.class); checkConfig.addAttribute("allowedDuplicates", "3"); checkConfig.addAttribute("ignoreOccurrenceContext", ""); checkConfig.addAttribute("highlightAllDuplicates", "false"); @@ -110,7 +117,34 @@ public void testItWithoutIgnoringAnnotations() throws Exception { "19:23: " + getCheckMessage(MSG_KEY, "\"unchecked\"", 4), }; - verify(checkConfig, getPath("InputMultipleStringLiterals.java"), expected); + verify(checkConfig, getPath("InputMultipleStringLiteralsExtendedCheck.java"), expected); + } + + @Test + public void testNullProperty() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MultipleStringLiteralsExtendedCheck.class); + checkConfig.addAttribute("ignoreStringsRegexp", null); + + final String[] expected = { + "5:16: " + getCheckMessage(MSG_KEY, "\"StringContents\"", 3), + "7:17: " + getCheckMessage(MSG_KEY, "\"DoubleString\"", 2), + "8:17: " + getCheckMessage(MSG_KEY, "\"\"", 4), + "10:23: " + getCheckMessage(MSG_KEY, "\", \"", 3), + }; + + verify(checkConfig, getPath("InputMultipleStringLiteralsExtendedCheck.java"), expected); + } + + @Test + public void testIgnoreOccurrenceContextProperty() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(MultipleStringLiteralsExtendedCheck.class); + checkConfig.addAttribute("ignoreOccurrenceContext", "EXPR, PLUS"); + + final String[] expected = {}; + + verify(checkConfig, getPath("InputMultipleStringLiteralsExtendedCheck.java"), expected); } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsExtendedCheckTest.java similarity index 77% rename from sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java rename to sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsExtendedCheckTest.java index 6815d56143..da4b5352d3 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/MultipleVariableDeclarationsExtendedCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -24,17 +24,24 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; /** Test class. */ -public class MultipleVariableDeclarationsCheckTest extends BaseCheckTestSupport { +public class MultipleVariableDeclarationsExtendedCheckTest extends AbstractModuleTestSupport { + private final String msgVarDeclarationsComa = getCheckMessage(MSG_VAR_DECLARATIONS_COMMA); private final String msgVarDeclarations = getCheckMessage(MSG_VAR_DECLARATIONS); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void testStandartSituation() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(MultipleVariableDeclarationsExtendedCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(MultipleVariableDeclarationsExtendedCheck.class); final String[] expected = { "3:5: " + msgVarDeclarationsComa, @@ -49,12 +56,14 @@ public void testStandartSituation() throws Exception { checkConfig.addAttribute("ignoreCycles", "false"); checkConfig.addAttribute("ignoreMethods", "false"); - verify(checkConfig, getPath("InputMultipleVariableDeclarations.java"), expected); + verify(checkConfig, getPath("InputMultipleVariableDeclarationsExtendedCheck.java"), + expected); } @Test public void testIgnoreCycles() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(MultipleVariableDeclarationsExtendedCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(MultipleVariableDeclarationsExtendedCheck.class); final String[] expected = { "3:5: " + msgVarDeclarationsComa, @@ -67,12 +76,14 @@ public void testIgnoreCycles() throws Exception { checkConfig.addAttribute("ignoreCycles", "true"); checkConfig.addAttribute("ignoreMethods", "false"); - verify(checkConfig, getPath("InputMultipleVariableDeclarations.java"), expected); + verify(checkConfig, getPath("InputMultipleVariableDeclarationsExtendedCheck.java"), + expected); } @Test public void testIgnoreMethods() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(MultipleVariableDeclarationsExtendedCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(MultipleVariableDeclarationsExtendedCheck.class); final String[] expected = { "3:5: " + msgVarDeclarationsComa, @@ -84,12 +95,14 @@ public void testIgnoreMethods() throws Exception { checkConfig.addAttribute("ignoreCycles", "false"); checkConfig.addAttribute("ignoreMethods", "true"); - verify(checkConfig, getPath("InputMultipleVariableDeclarations.java"), expected); + verify(checkConfig, getPath("InputMultipleVariableDeclarationsExtendedCheck.java"), + expected); } @Test public void testIgnoreMethodsAndIgnoreCycles() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(MultipleVariableDeclarationsExtendedCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(MultipleVariableDeclarationsExtendedCheck.class); final String[] expected = { "3:5: " + msgVarDeclarationsComa, @@ -100,7 +113,8 @@ public void testIgnoreMethodsAndIgnoreCycles() throws Exception { checkConfig.addAttribute("ignoreCycles", "true"); checkConfig.addAttribute("ignoreMethods", "true"); - verify(checkConfig, getPath("InputMultipleVariableDeclarations.java"), expected); + verify(checkConfig, getPath("InputMultipleVariableDeclarationsExtendedCheck.java"), + expected); } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NameConventionForJunit4TestClassesCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NameConventionForJunit4TestClassesCheckTest.java index 915f37cbb0..04ccb97dfe 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NameConventionForJunit4TestClassesCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NameConventionForJunit4TestClassesCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,135 +19,199 @@ package com.github.sevntu.checkstyle.checks.coding; -import java.text.MessageFormat; - import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; /** * @author Denis Antonenkov * @author Zuy Alexey */ -public class NameConventionForJunit4TestClassesCheckTest extends BaseCheckTestSupport { - private final String msgFormat = - getCheckMessage(NameConventionForJunit4TestClassesCheck.MSG_KEY); - - private final String defaultTestClassName = - ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"; +public class NameConventionForJunit4TestClassesCheckTest extends AbstractModuleTestSupport { - private final DefaultConfiguration checkConfig = - buildConfiguration(defaultTestClassName, "", "Test"); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testAnnotatedClass() throws Exception { - final DefaultConfiguration customConfig = - buildConfiguration(defaultTestClassName, "RunWith", ""); + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + customConfig.addAttribute("expectedClassNameRegex", + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"); + customConfig.addAttribute("classAnnotationNameRegex", "RunWith"); + customConfig.addAttribute("methodAnnotationNameRegex", ""); final String[] expected = { - buildMesssage("14:18: ", defaultTestClassName), + "14:18: " + getCheckMessage(NameConventionForJunit4TestClassesCheck.MSG_KEY, + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"), }; - verify(customConfig, getPath("InputNameConventionForTest1.java"), expected); + verify(customConfig, getPath("InputNameConventionForJunit4TestClassesCheck1.java"), + expected); } @Test public void testAnnotatedMethod() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + checkConfig.addAttribute("expectedClassNameRegex", + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"); + checkConfig.addAttribute("classAnnotationNameRegex", ""); + checkConfig.addAttribute("methodAnnotationNameRegex", "Test"); + final String[] expected = { - buildMesssage("8:18: ", defaultTestClassName), + "8:18: " + getCheckMessage(NameConventionForJunit4TestClassesCheck.MSG_KEY, + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"), }; - verify(checkConfig, getPath("InputNameConventionForTest2.java"), expected); + verify(checkConfig, getPath("InputNameConventionForJunit4TestClassesCheck2.java"), + expected); } @Test public void testClassIsNotTest() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + checkConfig.addAttribute("expectedClassNameRegex", + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"); + checkConfig.addAttribute("classAnnotationNameRegex", ""); + checkConfig.addAttribute("methodAnnotationNameRegex", "Test"); + final String[] expected = { }; - verify(checkConfig, getPath("InputNameConventionForTest3.java"), expected); + verify(checkConfig, getPath("InputNameConventionForJunit4TestClassesCheck3.java"), + expected); } @Test public void testRegex() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + checkConfig.addAttribute("expectedClassNameRegex", + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"); + checkConfig.addAttribute("classAnnotationNameRegex", ""); + checkConfig.addAttribute("methodAnnotationNameRegex", "Test"); + final String[] expected = { - buildMesssage("7:18: ", defaultTestClassName), + "7:18: " + getCheckMessage(NameConventionForJunit4TestClassesCheck.MSG_KEY, + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"), }; - verify(checkConfig, getPath("InputNameConventionForTest4.java"), expected); + verify(checkConfig, getPath("InputNameConventionForJunit4TestClassesCheck4.java"), + expected); } @Test public void testQualifiedAnnotationName() throws Exception { final DefaultConfiguration customConfig = - buildConfiguration(defaultTestClassName, "", "org.junit.Test"); + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + customConfig.addAttribute("expectedClassNameRegex", + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"); + customConfig.addAttribute("classAnnotationNameRegex", ""); + customConfig.addAttribute("methodAnnotationNameRegex", "org.junit.Test"); final String[] expected = { - buildMesssage("8:18: ", defaultTestClassName), + "8:18: " + getCheckMessage(NameConventionForJunit4TestClassesCheck.MSG_KEY, + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"), }; - verify(customConfig, getPath("InputNameConventionForTest5.java"), expected); + verify(customConfig, getPath("InputNameConventionForJunit4TestClassesCheck5.java"), + expected); } @Test public void testJunitClassTestAnnotationNamesRegexOption() throws Exception { final DefaultConfiguration customConfig = - buildConfiguration(defaultTestClassName, "SomeTestAnnotation", ""); + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + customConfig.addAttribute("expectedClassNameRegex", + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"); + customConfig.addAttribute("classAnnotationNameRegex", "SomeTestAnnotation"); + customConfig.addAttribute("methodAnnotationNameRegex", ""); final String[] expected = { - buildMesssage("7:18: ", defaultTestClassName), + "7:18: " + getCheckMessage(NameConventionForJunit4TestClassesCheck.MSG_KEY, + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"), }; - verify(customConfig, getPath("InputNameConventionForTest6.java"), expected); + verify(customConfig, getPath("InputNameConventionForJunit4TestClassesCheck6.java"), + expected); } @Test public void testJunitMethodTestAnnotationNamesRegexOption() throws Exception { final DefaultConfiguration customConfig = - buildConfiguration(defaultTestClassName, "", "SomeTestAnnotation"); + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + customConfig.addAttribute("expectedClassNameRegex", + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"); + customConfig.addAttribute("classAnnotationNameRegex", ""); + customConfig.addAttribute("methodAnnotationNameRegex", "SomeTestAnnotation"); final String[] expected = { - buildMesssage("6:18: ", defaultTestClassName), + "6:18: " + getCheckMessage(NameConventionForJunit4TestClassesCheck.MSG_KEY, + ".+Test\\d*|.+Tests\\d*|Test.+|Tests.+|.+IT|.+ITs|.+TestCase|.+TestCases"), }; - verify(customConfig, getPath("InputNameConventionForTest7.java"), expected); + verify(customConfig, getPath("InputNameConventionForJunit4TestClassesCheck7.java"), + expected); } @Test public void testCorrectTestClassNameRegexOption() throws Exception { final DefaultConfiguration customConfig = - buildConfiguration("Hello*", "", "Test"); + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + customConfig.addAttribute("expectedClassNameRegex", "Hello*"); + customConfig.addAttribute("classAnnotationNameRegex", ""); + customConfig.addAttribute("methodAnnotationNameRegex", "Test"); final String[] expected = { - buildMesssage("5:14: ", "Hello*"), + "5:14: " + + getCheckMessage(NameConventionForJunit4TestClassesCheck.MSG_KEY, "Hello*"), }; - verify(customConfig, getPath("InputNameConventionForTest8.java"), expected); + verify(customConfig, getPath("InputNameConventionForJunit4TestClassesCheck8.java"), + expected); } - private static DefaultConfiguration buildConfiguration(String expectedNameRegex, - String classAnnotationNameRegex, String methodAnnotationNameRegex) { - final DefaultConfiguration config = - createCheckConfig(NameConventionForJunit4TestClassesCheck.class); + @Test + public void testNullProperties() + throws Exception { + final DefaultConfiguration customConfig = + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + customConfig.addAttribute("expectedClassNameRegex", null); + customConfig.addAttribute("classAnnotationNameRegex", null); + customConfig.addAttribute("methodAnnotationNameRegex", null); - config.addAttribute("expectedClassNameRegex", expectedNameRegex); - config.addAttribute("classAnnotationNameRegex", classAnnotationNameRegex); - config.addAttribute("methodAnnotationNameRegex", methodAnnotationNameRegex); + final String[] expected = {}; - return config; + verify(customConfig, getPath("InputNameConventionForJunit4TestClassesCheck8.java"), + expected); } - private String buildMesssage(String lineNumber, String arguments) { - return lineNumber + MessageFormat.format(msgFormat, arguments); + @Test + public void testEmptyProperties() + throws Exception { + final DefaultConfiguration customConfig = + createModuleConfig(NameConventionForJunit4TestClassesCheck.class); + customConfig.addAttribute("expectedClassNameRegex", ""); + customConfig.addAttribute("classAnnotationNameRegex", ""); + customConfig.addAttribute("methodAnnotationNameRegex", ""); + + final String[] expected = {}; + + verify(customConfig, getPath("InputNameConventionForJunit4TestClassesCheck8.java"), + expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NoNullForCollectionReturnCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NoNullForCollectionReturnCheckTest.java index 74793f9582..de88008c57 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NoNullForCollectionReturnCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NoNullForCollectionReturnCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,21 +23,27 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class NoNullForCollectionReturnCheckTest extends BaseCheckTestSupport { +public class NoNullForCollectionReturnCheckTest extends AbstractModuleTestSupport { private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void testArraysNotDeep() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); final String[] expected = { - "11: " + warningMessage, - "46: " + warningMessage, - "54: " + warningMessage, - "59: " + warningMessage, + "11:9: " + warningMessage, + "46:13: " + warningMessage, + "54:13: " + warningMessage, + "59:17: " + warningMessage, }; verify(checkConfig, getPath("InputNoNullForCollectionReturnCheck1.java"), expected); @@ -45,14 +51,15 @@ public void testArraysNotDeep() throws Exception { @Test public void testArraysDeep() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); checkConfig.addAttribute("searchThroughMethodBody", "true"); final String[] expected = { - "11: " + warningMessage, - "18: " + warningMessage, - "46: " + warningMessage, - "54: " + warningMessage, - "59: " + warningMessage, + "11:9: " + warningMessage, + "18:9: " + warningMessage, + "46:13: " + warningMessage, + "54:13: " + warningMessage, + "59:17: " + warningMessage, }; verify(checkConfig, getPath("InputNoNullForCollectionReturnCheck1.java"), expected); @@ -60,17 +67,18 @@ public void testArraysDeep() throws Exception { @Test public void testCollections() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); - final String listOfCollecton = "Collection ArrayList LinkedList Stack Vector HashSet TreeSet"; - checkConfig.addAttribute("collectionList", listOfCollecton); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); + checkConfig.addAttribute("collectionList", + "Collection ArrayList LinkedList Stack Vector HashSet TreeSet"); final String[] expected = { - "7: " + warningMessage, - "17: " + warningMessage, - "27: " + warningMessage, - "37: " + warningMessage, - "47: " + warningMessage, - "57: " + warningMessage, - "67: " + warningMessage, + "7:9: " + warningMessage, + "17:9: " + warningMessage, + "27:9: " + warningMessage, + "37:9: " + warningMessage, + "47:9: " + warningMessage, + "57:9: " + warningMessage, + "67:9: " + warningMessage, }; verify(checkConfig, getPath("InputNoNullForCollectionReturnCheck2.java"), expected); @@ -78,10 +86,11 @@ public void testCollections() throws Exception { @Test public void testRevereCode() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); final String[] expected = { - "13: " + warningMessage, - "16: " + warningMessage, + "13:25: " + warningMessage, + "16:25: " + warningMessage, }; verify(checkConfig, getPath("InputNoNullForCollectionReturnCheck3.java"), expected); @@ -89,11 +98,12 @@ public void testRevereCode() throws Exception { @Test public void testRevereCodeDeep() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); checkConfig.addAttribute("searchThroughMethodBody", "true"); final String[] expected = { - "13: " + warningMessage, - "16: " + warningMessage, + "13:25: " + warningMessage, + "16:25: " + warningMessage, }; verify(checkConfig, getPath("InputNoNullForCollectionReturnCheck3.java"), expected); @@ -101,7 +111,8 @@ public void testRevereCodeDeep() throws Exception { @Test public void testInterface() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); final String[] expected = { }; @@ -110,12 +121,13 @@ public void testInterface() throws Exception { @Test public void testInnerClasses() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); final String[] expected = { - "17: " + warningMessage, - "25: " + warningMessage, - "27: " + warningMessage, - "39: " + warningMessage, + "17:17: " + warningMessage, + "25:13: " + warningMessage, + "27:9: " + warningMessage, + "39:13: " + warningMessage, }; verify(checkConfig, getPath("InputNoNullForCollectionReturnCheck5.java"), expected); @@ -123,7 +135,8 @@ public void testInnerClasses() throws Exception { @Test public void testRealCode() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); checkConfig.addAttribute("searchThroughMethodBody", "true"); final String[] expected = { }; @@ -134,9 +147,10 @@ public void testRealCode() throws Exception { @Test public void testIss148() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); final String[] expected = { - "8: " + warningMessage, + "8:9: " + warningMessage, }; verify(checkConfig, getPath("InputNoNullForCollectionReturnCheck7.java"), expected); @@ -145,12 +159,27 @@ public void testIss148() @Test public void testIss148Deep() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NoNullForCollectionReturnCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); checkConfig.addAttribute("searchThroughMethodBody", "true"); final String[] expected = { - "8: " + warningMessage, + "8:9: " + warningMessage, }; verify(checkConfig, getPath("InputNoNullForCollectionReturnCheck7.java"), expected); } + + @Test + public void testConstructor() + throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(NoNullForCollectionReturnCheck.class); + final String[] expected = { + "5:9: " + warningMessage, + }; + + verify(checkConfig, getPath("InputNoNullForCollectionReturnCheckConstructor.java"), + expected); + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NumericLiteralNeedsUnderscoreCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NumericLiteralNeedsUnderscoreCheckTest.java index c99c66539e..0cfff8677e 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NumericLiteralNeedsUnderscoreCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/NumericLiteralNeedsUnderscoreCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,6 +20,7 @@ package com.github.sevntu.checkstyle.checks.coding; import static com.github.sevntu.checkstyle.checks.coding.NumericLiteralNeedsUnderscoreCheck.MSG_KEY; +import static org.junit.Assert.fail; import java.io.File; @@ -31,62 +32,69 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.internal.WhiteboxImpl; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; import com.github.sevntu.checkstyle.checks.coding.NumericLiteralNeedsUnderscoreCheck.NumericType; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @RunWith(PowerMockRunner.class) @PrepareForTest(NumericType.class) -public class NumericLiteralNeedsUnderscoreCheckTest extends BaseCheckTestSupport { +public class NumericLiteralNeedsUnderscoreCheckTest extends AbstractModuleTestSupport { private static final String EXCEPTION_MESSAGE = "Unexpected numeric type "; private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void test() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NumericLiteralNeedsUnderscoreCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NumericLiteralNeedsUnderscoreCheck.class); final String[] expected = { - "27: " + warningMessage, - "28: " + warningMessage, - "29: " + warningMessage, - "30: " + warningMessage, - "31: " + warningMessage, - "32: " + warningMessage, - "33: " + warningMessage, - "50: " + warningMessage, - "51: " + warningMessage, - "52: " + warningMessage, - "53: " + warningMessage, - "54: " + warningMessage, - "55: " + warningMessage, - "56: " + warningMessage, - "57: " + warningMessage, - "75: " + warningMessage, - "76: " + warningMessage, - "77: " + warningMessage, - "78: " + warningMessage, - "79: " + warningMessage, - "80: " + warningMessage, - "81: " + warningMessage, - "82: " + warningMessage, - "83: " + warningMessage, - "84: " + warningMessage, - "85: " + warningMessage, - "99: " + warningMessage, - "100: " + warningMessage, - "101: " + warningMessage, - "102: " + warningMessage, - "103: " + warningMessage, - "104: " + warningMessage, + "27:22: " + warningMessage, + "28:25: " + warningMessage, + "29:25: " + warningMessage, + "30:26: " + warningMessage, + "31:28: " + warningMessage, + "32:22: " + warningMessage, + "33:25: " + warningMessage, + "50:23: " + warningMessage, + "51:23: " + warningMessage, + "52:23: " + warningMessage, + "53:24: " + warningMessage, + "54:24: " + warningMessage, + "55:24: " + warningMessage, + "56:24: " + warningMessage, + "57:24: " + warningMessage, + "75:23: " + warningMessage, + "76:23: " + warningMessage, + "77:23: " + warningMessage, + "78:23: " + warningMessage, + "79:23: " + warningMessage, + "80:25: " + warningMessage, + "81:25: " + warningMessage, + "82:27: " + warningMessage, + "83:27: " + warningMessage, + "84:29: " + warningMessage, + "85:29: " + warningMessage, + "99:23: " + warningMessage, + "100:23: " + warningMessage, + "101:25: " + warningMessage, + "102:25: " + warningMessage, + "103:25: " + warningMessage, + "104:25: " + warningMessage, }; - verify(checkConfig, getPath("InputNumericLiteralNeedUnderscoreCheck.java"), + verify(checkConfig, getPath("InputNumericLiteralNeedsUnderscoreCheck.java"), expected); } @Test public void testWithConfig() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NumericLiteralNeedsUnderscoreCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(NumericLiteralNeedsUnderscoreCheck.class); checkConfig.addAttribute("minDecimalSymbolLength", "1"); checkConfig.addAttribute("maxDecimalSymbolsUntilUnderscore", "3"); checkConfig.addAttribute("minHexSymbolLength", "1"); @@ -94,131 +102,145 @@ public void testWithConfig() throws Exception { checkConfig.addAttribute("minBinarySymbolLength", "1"); checkConfig.addAttribute("maxBinarySymbolsUntilUnderscore", "4"); final String[] expected = { - "23: " + warningMessage, - "24: " + warningMessage, - "25: " + warningMessage, - "26: " + warningMessage, - "27: " + warningMessage, - "28: " + warningMessage, - "44: " + warningMessage, - "45: " + warningMessage, - "46: " + warningMessage, - "47: " + warningMessage, - "48: " + warningMessage, - "49: " + warningMessage, - "50: " + warningMessage, - "67: " + warningMessage, - "68: " + warningMessage, - "69: " + warningMessage, - "70: " + warningMessage, - "71: " + warningMessage, - "72: " + warningMessage, - "73: " + warningMessage, - "74: " + warningMessage, - "86: " + warningMessage, - "87: " + warningMessage, - "88: " + warningMessage, - "89: " + warningMessage, + "23:22: " + warningMessage, + "24:24: " + warningMessage, + "25:26: " + warningMessage, + "26:28: " + warningMessage, + "27:22: " + warningMessage, + "28:25: " + warningMessage, + "44:23: " + warningMessage, + "45:23: " + warningMessage, + "46:23: " + warningMessage, + "47:24: " + warningMessage, + "48:24: " + warningMessage, + "49:24: " + warningMessage, + "50:24: " + warningMessage, + "67:23: " + warningMessage, + "68:23: " + warningMessage, + "69:23: " + warningMessage, + "70:25: " + warningMessage, + "71:27: " + warningMessage, + "72:27: " + warningMessage, + "73:29: " + warningMessage, + "74:29: " + warningMessage, + "86:23: " + warningMessage, + "87:23: " + warningMessage, + "88:25: " + warningMessage, + "89:25: " + warningMessage, }; - verify(checkConfig, getPath("InputNumericLiteralNeedUnderscoreCheck2.java"), + verify(checkConfig, getPath("InputNumericLiteralNeedsUnderscoreCheck2.java"), expected); } @Test public void testIgnore() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(NumericLiteralNeedsUnderscoreCheck.class); + createModuleConfig(NumericLiteralNeedsUnderscoreCheck.class); final String[] expected = { - "7: " + warningMessage, - "8: " + warningMessage, - "10: " + warningMessage, - "15: " + warningMessage, - "16: " + warningMessage, - "17: " + warningMessage, - "22: " + warningMessage, - "24: " + warningMessage, - "30: " + warningMessage, - "31: " + warningMessage, - "32: " + warningMessage, - "33: " + warningMessage, - "40: " + warningMessage, + "7:36: " + warningMessage, + "8:37: " + warningMessage, + "10:30: " + warningMessage, + "15:44: " + warningMessage, + "16:44: " + warningMessage, + "17:39: " + warningMessage, + "22:28: " + warningMessage, + "24:24: " + warningMessage, + "30:19: " + warningMessage, + "31:19: " + warningMessage, + "32:19: " + warningMessage, + "33:19: " + warningMessage, + "40:32: " + warningMessage, }; - verify(checkConfig, new File("src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/" - + "coding/InputNumericLiteralNeedUnderscoreCheck3.java").getCanonicalPath(), - expected); + verify(checkConfig, + new File("src/test/resources-noncompilable/com/github/sevntu/" + + "checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck3.java") + .getCanonicalPath(), expected); } @Test public void testConfiguredIgnore() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(NumericLiteralNeedsUnderscoreCheck.class); + createModuleConfig(NumericLiteralNeedsUnderscoreCheck.class); checkConfig.addAttribute("ignoreFieldNamePattern", "RED"); checkConfig.addAttribute("minDecimalSymbolLength", "1"); final String[] expected = { - "7: " + warningMessage, - "8: " + warningMessage, - "10: " + warningMessage, - "14: " + warningMessage, - "15: " + warningMessage, - "17: " + warningMessage, - "22: " + warningMessage, - "24: " + warningMessage, - "30: " + warningMessage, - "31: " + warningMessage, - "32: " + warningMessage, - "33: " + warningMessage, - "38: " + warningMessage, + "7:36: " + warningMessage, + "8:37: " + warningMessage, + "10:30: " + warningMessage, + "14:59: " + warningMessage, + "15:44: " + warningMessage, + "17:39: " + warningMessage, + "22:28: " + warningMessage, + "24:24: " + warningMessage, + "30:19: " + warningMessage, + "31:19: " + warningMessage, + "32:19: " + warningMessage, + "33:19: " + warningMessage, + "38:55: " + warningMessage, }; - verify(checkConfig, new File("src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/" - + "coding/InputNumericLiteralNeedUnderscoreCheck3.java").getCanonicalPath(), - expected); + verify(checkConfig, + new File("src/test/resources-noncompilable/com/github/sevntu/" + + "checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck3.java") + .getCanonicalPath(), expected); } @Test public void testMinSymbolsBeforeCheckingSwitchReflection() throws Exception { try { - final NumericLiteralNeedsUnderscoreCheck check = new NumericLiteralNeedsUnderscoreCheck(); + final NumericLiteralNeedsUnderscoreCheck check = + new NumericLiteralNeedsUnderscoreCheck(); final NumericType mockType = PowerMockito.mock(NumericType.class); WhiteboxImpl.invokeMethod(check, "minSymbolsBeforeChecking", mockType); + fail(); } catch (IllegalStateException ex) { - Assert.assertTrue(ex.getMessage().startsWith(EXCEPTION_MESSAGE)); + Assert.assertTrue("Exception's message does not start with: " + EXCEPTION_MESSAGE, + ex.getMessage().startsWith(EXCEPTION_MESSAGE)); } } @Test public void testMaxSymbolsUntilUnderscoreSwitchReflection() throws Exception { try { - final NumericLiteralNeedsUnderscoreCheck check = new NumericLiteralNeedsUnderscoreCheck(); + final NumericLiteralNeedsUnderscoreCheck check = + new NumericLiteralNeedsUnderscoreCheck(); final NumericType mockType = PowerMockito.mock(NumericType.class); WhiteboxImpl.invokeMethod(check, "maxSymbolsUntilUnderscore", mockType); + fail(); } catch (IllegalStateException ex) { - Assert.assertTrue(ex.getMessage().startsWith(EXCEPTION_MESSAGE)); + Assert.assertTrue("Exception's message does not start with: " + EXCEPTION_MESSAGE, + ex.getMessage().startsWith(EXCEPTION_MESSAGE)); } } @Test public void testGetNumericSegmentsSwitchReflection() throws Exception { try { - final NumericLiteralNeedsUnderscoreCheck check = new NumericLiteralNeedsUnderscoreCheck(); + final NumericLiteralNeedsUnderscoreCheck check = + new NumericLiteralNeedsUnderscoreCheck(); final NumericType mockType = PowerMockito.mock(NumericType.class); WhiteboxImpl.invokeMethod(check, "getNumericSegments", "", mockType); + fail(); } catch (IllegalStateException ex) { - Assert.assertTrue(ex.getMessage().startsWith(EXCEPTION_MESSAGE)); + Assert.assertTrue("Exception's message does not start with: " + EXCEPTION_MESSAGE, + ex.getMessage().startsWith(EXCEPTION_MESSAGE)); } } @Test public void testRemovePrePostfixByTypeSwitchReflection() throws Exception { try { - final NumericLiteralNeedsUnderscoreCheck check = new NumericLiteralNeedsUnderscoreCheck(); + final NumericLiteralNeedsUnderscoreCheck check = + new NumericLiteralNeedsUnderscoreCheck(); final NumericType mockType = PowerMockito.mock(NumericType.class); WhiteboxImpl.invokeMethod(check, "removePrePostfixByType", "", mockType); + fail(); } catch (IllegalStateException ex) { - Assert.assertTrue(ex.getMessage().startsWith(EXCEPTION_MESSAGE)); + Assert.assertTrue("Exception's message does not start with: " + EXCEPTION_MESSAGE, + ex.getMessage().startsWith(EXCEPTION_MESSAGE)); } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheckTest.java index 8fe8cbab68..aa8e982c9c 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -24,19 +24,24 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class OverridableMethodInConstructorCheckTest extends BaseCheckTestSupport { +public class OverridableMethodInConstructorCheckTest extends AbstractModuleTestSupport { private static final String CTOR_KEY = "constructor"; private static final String CLONE_KEY = "'clone()' method"; private static final String READ_OBJECT_KEY = "'readObject()' method"; - private final DefaultConfiguration checkConfig = createCheckConfig(OverridableMethodInConstructorCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public final void revereCodeTest() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "false"); checkConfig.addAttribute("checkReadObjectMethod", "false"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -45,11 +50,13 @@ public final void revereCodeTest() throws Exception { "11:17: " + getCheckMessage(MSG_KEY_LEADS, "init", CTOR_KEY, "getPart"), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor26.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck26.java"), expected); } @Test - public final void newFeauture() throws Exception { + public final void newFeature() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -59,11 +66,13 @@ public final void newFeauture() throws Exception { "15:21: " + getCheckMessage(MSG_KEY, "init", CTOR_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor27.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck27.java"), expected); } @Test - public final void newFeautureWithoutMethodsByArgCount() throws Exception { + public final void newFeatureWithoutMethodsByArgCount() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "false"); @@ -72,22 +81,26 @@ public final void newFeautureWithoutMethodsByArgCount() throws Exception { "15:21: " + getCheckMessage(MSG_KEY, "init", CTOR_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor27.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck27.java"), expected); } @Test public final void testNoWarnings() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor1.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck1.java"), expected); } @Test public final void testWarning() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "false"); @@ -96,11 +109,13 @@ public final void testWarning() throws Exception { "10:27: " + getCheckMessage(MSG_KEY, "overrideMe", CTOR_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor2.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck2.java"), expected); } @Test public final void test2WarningsIn2Ctors() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -111,11 +126,13 @@ public final void test2WarningsIn2Ctors() throws Exception { "16:27: " + getCheckMessage(MSG_KEY, "overrideMe", CTOR_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor3.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck3.java"), expected); } @Test public final void testWarningInSecondDepth() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -124,11 +141,13 @@ public final void testWarningInSecondDepth() throws Exception { "10:32: " + getCheckMessage(MSG_KEY_LEADS, "overrideMe", CTOR_KEY, "overrideMe2"), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor4.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck4.java"), expected); } @Test public final void testWarningsInThirdDepth() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -138,33 +157,39 @@ public final void testWarningsInThirdDepth() throws Exception { "11:27: " + getCheckMessage(MSG_KEY_LEADS, "overrideMe", CTOR_KEY, "overrideMe3"), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor5.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck5.java"), expected); } @Test public final void testCloneNoWarningsSimple() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor6.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck6.java"), expected); } @Test public final void testCloneNoWarnings() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor7.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck7.java"), expected); } @Test public final void testCloneWarnings() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -174,11 +199,13 @@ public final void testCloneWarnings() throws Exception { "37:37: " + getCheckMessage(MSG_KEY, "doSmth", CLONE_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor8.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck8.java"), expected); } @Test public final void testCloneSecondDepth() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -188,11 +215,13 @@ public final void testCloneSecondDepth() throws Exception { "26:20: " + getCheckMessage(MSG_KEY, "doSmth2", CLONE_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor9.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck9.java"), expected); } @Test public final void testCloneThirdDepthImplementation() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -205,22 +234,26 @@ public final void testCloneThirdDepthImplementation() throws Exception { "63:37: " + getCheckMessage(MSG_KEY, "doSmth", CLONE_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor13.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck13.java"), expected); } @Test public final void testSerializableNoWarnings() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor10.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck10.java"), expected); } @Test public final void testSerializableWarning() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -229,11 +262,13 @@ public final void testSerializableWarning() throws Exception { "31:20: " + getCheckMessage(MSG_KEY, "doSmth", READ_OBJECT_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor11.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck11.java"), expected); } @Test public final void testStaticModifiers() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -241,12 +276,14 @@ public final void testStaticModifiers() throws Exception { final String[] expected = { }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor12.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck12.java"), expected); } @Test public final void testSerializableThirdDepthImplementation() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -263,33 +300,39 @@ public final void testSerializableThirdDepthImplementation() "81:29: " + getCheckMessage(MSG_KEY_LEADS, "doSmth2", READ_OBJECT_KEY, "doSmth"), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor14.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck14.java"), expected); } @Test public final void testCtorOverloadedMethods() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor15.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck15.java"), expected); } @Test public final void test2EqualMethodNamesWithNoWarning() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor16.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck16.java"), expected); } @Test public final void test2EqualMethodNamesWithoutWarning2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -299,55 +342,65 @@ public final void test2EqualMethodNamesWithoutWarning2() throws Exception { "18:45: " + getCheckMessage(MSG_KEY, "doSmth", READ_OBJECT_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor17.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck17.java"), expected); } @Test public final void testCallMethodIsNotInBuildPath2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor18.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck18.java"), expected); } @Test public final void testCallMethodIsNotInBuildPath() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor19.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck19.java"), expected); } @Test public final void testReadObjectInInterface() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor20.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck20.java"), expected); } @Test public final void testStackOverFlowError() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor21.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck21.java"), expected); } @Test public final void testStackOverFlowErrorWithWarning() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -356,22 +409,26 @@ public final void testStackOverFlowErrorWithWarning() throws Exception { "5:15: " + getCheckMessage(MSG_KEY_LEADS, "doSMTH", CTOR_KEY, "doPublic"), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor22.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck22.java"), expected); } @Test public final void testStackOverFlowErrorWithoutWarning() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor23.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck23.java"), expected); } @Test public final void testAbstractMethodCall() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); @@ -380,17 +437,33 @@ public final void testAbstractMethodCall() throws Exception { "11:22: " + getCheckMessage(MSG_KEY, "buildGetter", CTOR_KEY), }; - verify(checkConfig, getPath("InputOverridableMethodInConstructor24.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck24.java"), expected); } @Test public final void testFinalClass() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); checkConfig.addAttribute("checkCloneMethod", "true"); checkConfig.addAttribute("checkReadObjectMethod", "true"); checkConfig.addAttribute("matchMethodsByArgCount", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputOverridableMethodInConstructor25.java"), expected); + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck25.java"), expected); } + + @Test + public final void testExtendsSimilarNamedClass() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(OverridableMethodInConstructorCheck.class); + checkConfig.addAttribute("checkCloneMethod", "true"); + checkConfig.addAttribute("checkReadObjectMethod", "true"); + checkConfig.addAttribute("matchMethodsByArgCount", "true"); + + final String[] expected = {}; + + verify(checkConfig, getPath("InputOverridableMethodInConstructorCheck28.java"), expected); + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/RedundantReturnCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/RedundantReturnCheckTest.java index f8d2fe20ca..ff95a8aa76 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/RedundantReturnCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/RedundantReturnCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,101 +20,147 @@ package com.github.sevntu.checkstyle.checks.coding; import static com.github.sevntu.checkstyle.checks.coding.RedundantReturnCheck.MSG_KEY; +import static org.junit.Assert.fail; +import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; + +public class RedundantReturnCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } -public class RedundantReturnCheckTest extends BaseCheckTestSupport { @Test public void testInputWithIgnoreEmptyConstructorsTrue() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(RedundantReturnCheck.class); + final DefaultConfiguration checkConfig = createModuleConfig(RedundantReturnCheck.class); checkConfig.addAttribute("allowReturnInEmptyMethodsAndConstructors", "false"); final String[] expected = { - "10: " + getCheckMessage(MSG_KEY), - "17: " + getCheckMessage(MSG_KEY), - "22: " + getCheckMessage(MSG_KEY), - "32: " + getCheckMessage(MSG_KEY), - "39: " + getCheckMessage(MSG_KEY), - "52: " + getCheckMessage(MSG_KEY), - "56: " + getCheckMessage(MSG_KEY), - "60: " + getCheckMessage(MSG_KEY), - "87: " + getCheckMessage(MSG_KEY), - "100: " + getCheckMessage(MSG_KEY), - "104: " + getCheckMessage(MSG_KEY), - "117: " + getCheckMessage(MSG_KEY), - "128: " + getCheckMessage(MSG_KEY), - "140: " + getCheckMessage(MSG_KEY), - "151: " + getCheckMessage(MSG_KEY), - "181: " + getCheckMessage(MSG_KEY), + "10:17: " + getCheckMessage(MSG_KEY), + "17:17: " + getCheckMessage(MSG_KEY), + "22:17: " + getCheckMessage(MSG_KEY), + "32:33: " + getCheckMessage(MSG_KEY), + "39:17: " + getCheckMessage(MSG_KEY), + "52:25: " + getCheckMessage(MSG_KEY), + "56:25: " + getCheckMessage(MSG_KEY), + "60:25: " + getCheckMessage(MSG_KEY), + "87:25: " + getCheckMessage(MSG_KEY), + "100:25: " + getCheckMessage(MSG_KEY), + "104:25: " + getCheckMessage(MSG_KEY), + "117:13: " + getCheckMessage(MSG_KEY), + "128:33: " + getCheckMessage(MSG_KEY), + "140:33: " + getCheckMessage(MSG_KEY), + "151:33: " + getCheckMessage(MSG_KEY), + "181:49: " + getCheckMessage(MSG_KEY), }; - verify(checkConfig, getPath("InputRedundantReturn.java"), expected); + verify(checkConfig, getPath("InputRedundantReturnCheck.java"), expected); } @Test public void testInputWithIgnoreEmptyConstructorsFalse() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(RedundantReturnCheck.class); + final DefaultConfiguration checkConfig = createModuleConfig(RedundantReturnCheck.class); checkConfig.addAttribute("allowReturnInEmptyMethodsAndConstructors", "true"); final String[] expected = { - "17: " + getCheckMessage(MSG_KEY), - "32: " + getCheckMessage(MSG_KEY), - "39: " + getCheckMessage(MSG_KEY), - "52: " + getCheckMessage(MSG_KEY), - "56: " + getCheckMessage(MSG_KEY), - "60: " + getCheckMessage(MSG_KEY), - "100: " + getCheckMessage(MSG_KEY), - "104: " + getCheckMessage(MSG_KEY), - "117: " + getCheckMessage(MSG_KEY), - "128: " + getCheckMessage(MSG_KEY), - "140: " + getCheckMessage(MSG_KEY), - "151: " + getCheckMessage(MSG_KEY), - "181: " + getCheckMessage(MSG_KEY), + "17:17: " + getCheckMessage(MSG_KEY), + "32:33: " + getCheckMessage(MSG_KEY), + "39:17: " + getCheckMessage(MSG_KEY), + "52:25: " + getCheckMessage(MSG_KEY), + "56:25: " + getCheckMessage(MSG_KEY), + "60:25: " + getCheckMessage(MSG_KEY), + "100:25: " + getCheckMessage(MSG_KEY), + "104:25: " + getCheckMessage(MSG_KEY), + "117:13: " + getCheckMessage(MSG_KEY), + "128:33: " + getCheckMessage(MSG_KEY), + "140:33: " + getCheckMessage(MSG_KEY), + "151:33: " + getCheckMessage(MSG_KEY), + "181:49: " + getCheckMessage(MSG_KEY), }; - verify(checkConfig, getPath("InputRedundantReturn.java"), expected); + verify(checkConfig, getPath("InputRedundantReturnCheck.java"), expected); + } + @Test + public void testInputNestedMethods() + throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(RedundantReturnCheck.class); + + final String[] expected = { + "29:17: " + getCheckMessage(MSG_KEY), + }; + + verify(checkConfig, getPath("InputRedundantReturnCheckNestedMethods.java"), expected); } @Test public void testForNullPointerExceptionsPresence() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(RedundantReturnCheck.class); + final DefaultConfiguration checkConfig = createModuleConfig(RedundantReturnCheck.class); final String[] expected = {}; verify(checkConfig, "src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/" - + "coding/InputRedundantReturnTestNPE.java", expected); - + + "coding/InputRedundantReturnCheckTestNPE.java", expected); } @Test public void testForNullPointerExceptionsInInterface() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(RedundantReturnCheck.class); + final DefaultConfiguration checkConfig = createModuleConfig(RedundantReturnCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputRedundantReturnMethodInInterface.java"), expected); + verify(checkConfig, getPath("InputRedundantReturnCheckMethodInInterface.java"), expected); + } + + @Test + public void testForNullPointerExceptionsInEmptyMethod() + throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(RedundantReturnCheck.class); + checkConfig.addAttribute("allowReturnInEmptyMethodsAndConstructors", + "true"); + + final String[] expected = {}; + verify(checkConfig, getPath("InputRedundantReturnCheckMethodInEmptyMethod.java"), expected); } @Test public void testSomeFalsePositiveCase() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(RedundantReturnCheck.class); + final DefaultConfiguration checkConfig = createModuleConfig(RedundantReturnCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputRedundantReturnFalsePositive.java"), expected); + verify(checkConfig, getPath("InputRedundantReturnCheckFalsePositive.java"), expected); + } + @Test + public void testUnsupportedNode() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final RedundantReturnCheck check = new RedundantReturnCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/RequireFailForTryCatchInJunitCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/RequireFailForTryCatchInJunitCheckTest.java new file mode 100644 index 0000000000..b1933a15aa --- /dev/null +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/RequireFailForTryCatchInJunitCheckTest.java @@ -0,0 +1,115 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.coding; + +import static com.github.sevntu.checkstyle.checks.coding.RequireFailForTryCatchInJunitCheck.MSG_KEY; +import static org.junit.Assert.fail; + +import org.junit.Assert; +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; + +public class RequireFailForTryCatchInJunitCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + + @Test + public void testIndifferent1() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(RequireFailForTryCatchInJunitCheck.class); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + verify(checkConfig, getPath("InputRequireFailForTryCatchInJunitCheck1.java"), expected); + } + + @Test + public void testIndifferent2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(RequireFailForTryCatchInJunitCheck.class); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + verify(checkConfig, getPath("InputRequireFailForTryCatchInJunitCheck2.java"), expected); + } + + @Test + public void testBad1() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(RequireFailForTryCatchInJunitCheck.class); + final String[] expected = { + "8:9: " + getCheckMessage(MSG_KEY), + "12:9: " + getCheckMessage(MSG_KEY), + "18:9: " + getCheckMessage(MSG_KEY), + "23:9: " + getCheckMessage(MSG_KEY), + "28:9: " + getCheckMessage(MSG_KEY), + "33:9: " + getCheckMessage(MSG_KEY), + "42:9: " + getCheckMessage(MSG_KEY), + "46:9: " + getCheckMessage(MSG_KEY), + "52:9: " + getCheckMessage(MSG_KEY), + "57:9: " + getCheckMessage(MSG_KEY), + "62:9: " + getCheckMessage(MSG_KEY), + "67:9: " + getCheckMessage(MSG_KEY), + "76:9: " + getCheckMessage(MSG_KEY), + }; + verify(checkConfig, getPath("InputRequireFailForTryCatchInJunitCheck3.java"), expected); + } + + @Test + public void testBad2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(RequireFailForTryCatchInJunitCheck.class); + final String[] expected = { + "9:9: " + getCheckMessage(MSG_KEY), + "14:9: " + getCheckMessage(MSG_KEY), + }; + verify(checkConfig, getPath("InputRequireFailForTryCatchInJunitCheck4.java"), expected); + } + + @Test + public void testGood() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(RequireFailForTryCatchInJunitCheck.class); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + verify(checkConfig, getPath("InputRequireFailForTryCatchInJunitCheck5.java"), expected); + } + + @Test + public void testUnsupportedNode() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final RequireFailForTryCatchInJunitCheck check = + new RequireFailForTryCatchInJunitCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } + } + +} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnBooleanFromTernaryCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnBooleanFromTernaryCheckTest.java index e1f4f4ee11..d25217bf44 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnBooleanFromTernaryCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnBooleanFromTernaryCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,24 +23,32 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class ReturnBooleanFromTernaryCheckTest extends BaseCheckTestSupport { +public class ReturnBooleanFromTernaryCheckTest extends AbstractModuleTestSupport { - private final String warninigMessage = getCheckMessage(MSG_KEY); + private final String warningMessage = getCheckMessage(MSG_KEY); + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ReturnBooleanFromTernaryCheck.class); + createModuleConfig(ReturnBooleanFromTernaryCheck.class); final String[] expected = { - "6:35: " + warninigMessage, - "7:38: " + warninigMessage, - "8:38: " + warninigMessage, - "9:35: " + warninigMessage, - "9:43: " + warninigMessage, + "6:35: " + warningMessage, + "7:38: " + warningMessage, + "8:38: " + warningMessage, + "9:35: " + warningMessage, + "9:43: " + warningMessage, + "10:28: " + warningMessage, + "11:27: " + warningMessage, }; - verify(checkConfig, getPath("InputReturnBooleanFromTernary.java"), expected); + verify(checkConfig, getPath("InputReturnBooleanFromTernaryCheck.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheckTest.java index 89ac76c840..47839b808f 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,20 +20,41 @@ package com.github.sevntu.checkstyle.checks.coding; import static com.github.sevntu.checkstyle.checks.coding.ReturnCountExtendedCheck.MSG_KEY_CTOR; +import static com.github.sevntu.checkstyle.checks.coding.ReturnCountExtendedCheck.MSG_KEY_LAMBDA; import static com.github.sevntu.checkstyle.checks.coding.ReturnCountExtendedCheck.MSG_KEY_METHOD; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class ReturnCountExtendedCheckTest extends BaseCheckTestSupport { +public class ReturnCountExtendedCheckTest extends AbstractModuleTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(ReturnCountExtendedCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test - public void testMethodsMaxReturnLiteralsIsOne() throws Exception { + public void testNullOnIgnoreMethodsNames() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); + checkConfig.addAttribute("maxReturnCount", "99"); + checkConfig.addAttribute("ignoreMethodLinesCount", "99"); + checkConfig.addAttribute("minIgnoreReturnDepth", "99"); + checkConfig.addAttribute("ignoreEmptyReturns", "true"); + checkConfig.addAttribute("topLinesToIgnoreCount", "99"); + checkConfig.addAttribute("ignoreMethodsNames", null); + final String[] expected = {}; + + verify(checkConfig, getPath("InputReturnCountExtendedCheckMethods.java"), expected); + } + + @Test + public void testMethodsMaxReturnLiteralsIsOne() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "1"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -53,7 +74,8 @@ public void testMethodsMaxReturnLiteralsIsOne() throws Exception { @Test public void testMethodsMaxReturnLiteralsIsTwo() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "2"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -71,6 +93,8 @@ public void testMethodsMaxReturnLiteralsIsTwo() throws Exception { @Test public void testIgnoreEmptyReturns() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "2"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -87,7 +111,8 @@ public void testIgnoreEmptyReturns() throws Exception { @Test public void testConstructorsMaxReturnLiteralsIsOne() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "1"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -105,7 +130,8 @@ public void testConstructorsMaxReturnLiteralsIsOne() throws Exception { @Test public void testignoreMethodLinesCount() throws Exception { - + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "1"); checkConfig.addAttribute("ignoreMethodLinesCount", "10"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -123,6 +149,8 @@ public void testignoreMethodLinesCount() throws Exception { @Test public void testignoreMethodLinesCount2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "1"); checkConfig.addAttribute("ignoreMethodLinesCount", "20"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -139,6 +167,8 @@ public void testignoreMethodLinesCount2() throws Exception { @Test public void testminIgnoreReturnDepth() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "0"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "1"); @@ -157,6 +187,8 @@ public void testminIgnoreReturnDepth() throws Exception { @Test public void testIgnoreNonEmptyReturns() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "1"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -174,6 +206,8 @@ public void testIgnoreNonEmptyReturns() throws Exception { @Test public void testMethodsInMethods() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "1"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -190,6 +224,8 @@ public void testMethodsInMethods() throws Exception { @Test public void testIgnoreMethodsNamesProperty() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "1"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -208,6 +244,8 @@ public void testIgnoreMethodsNamesProperty() throws Exception { @Test public void testRegexIgnoreMethodsNamesProperty() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); checkConfig.addAttribute("maxReturnCount", "1"); checkConfig.addAttribute("ignoreMethodLinesCount", "0"); checkConfig.addAttribute("minIgnoreReturnDepth", "5"); @@ -223,4 +261,45 @@ public void testRegexIgnoreMethodsNamesProperty() throws Exception { verify(checkConfig, getPath("InputReturnCountExtendedCheckMethods.java"), expected); } + + @Test + public void testAnonymousClass() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); + checkConfig.addAttribute("maxReturnCount", "1"); + checkConfig.addAttribute("ignoreMethodLinesCount", "0"); + checkConfig.addAttribute("minIgnoreReturnDepth", "99"); + checkConfig.addAttribute("ignoreEmptyReturns", "false"); + checkConfig.addAttribute("topLinesToIgnoreCount", "0"); + + final String[] expected = { + "14:16: " + getCheckMessage(MSG_KEY_METHOD, "method2", 2, 1), + "16:24: " + getCheckMessage(MSG_KEY_METHOD, "method2", 2, 1), + }; + + verify(checkConfig, getPath("InputReturnCountExtendedCheckAnonymousClasses.java"), + expected); + } + + @Test + public void testLambda() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountExtendedCheck.class); + checkConfig.addAttribute("maxReturnCount", "1"); + checkConfig.addAttribute("ignoreMethodLinesCount", "0"); + checkConfig.addAttribute("minIgnoreReturnDepth", "99"); + checkConfig.addAttribute("ignoreEmptyReturns", "false"); + checkConfig.addAttribute("topLinesToIgnoreCount", "0"); + + final String[] expected = { + "12:55: " + getCheckMessage(MSG_KEY_LAMBDA, 2, 1), + "24:49: " + getCheckMessage(MSG_KEY_LAMBDA, 2, 1), + "31:42: " + getCheckMessage(MSG_KEY_LAMBDA, 3, 1), + "38:9: " + getCheckMessage(MSG_KEY_METHOD, "methodWithTwoReturnWithLambdas", 2, 1), + "46:57: " + getCheckMessage(MSG_KEY_LAMBDA, 2, 1), + }; + + verify(checkConfig, getPath("InputReturnCountExtendedCheckLambdas.java"), expected); + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnNullInsteadOfBooleanCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnNullInsteadOfBooleanCheckTest.java index 72526a47bb..74d1695a51 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnNullInsteadOfBooleanCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/ReturnNullInsteadOfBooleanCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,24 +20,66 @@ package com.github.sevntu.checkstyle.checks.coding; import static com.github.sevntu.checkstyle.checks.coding.ReturnNullInsteadOfBooleanCheck.MSG_KEY; +import static org.junit.Assert.fail; +import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; -public class ReturnNullInsteadOfBooleanCheckTest extends BaseCheckTestSupport { +public class ReturnNullInsteadOfBooleanCheckTest extends AbstractModuleTestSupport { private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ReturnNullInsteadOfBooleanCheck.class); + createModuleConfig(ReturnNullInsteadOfBooleanCheck.class); final String[] expected = { "11:9: " + warningMessage, "22:25: " + warningMessage, }; - verify(checkConfig, getPath("InputReturnNullInsteadOfBoolean.java"), expected); + verify(checkConfig, getPath("InputReturnNullInsteadOfBooleanCheck.java"), expected); + } + + @Test + public void testUnsupportedNodeVisit() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final ReturnNullInsteadOfBooleanCheck check = new ReturnNullInsteadOfBooleanCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } } + + @Test + public void testUnsupportedNodeLeave() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final ReturnNullInsteadOfBooleanCheck check = new ReturnNullInsteadOfBooleanCheck(); + check.leaveToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationCheckTest.java similarity index 50% rename from sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationTest.java rename to sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationCheckTest.java index c4a5d16ea4..360f4c4974 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -24,143 +24,161 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class SimpleAccessorNameNotationTest extends BaseCheckTestSupport { +public class SimpleAccessorNameNotationCheckTest extends AbstractModuleTestSupport { private final String warningGetterMessage = getCheckMessage(MSG_KEY_GETTER); private final String warningSetterMessage = getCheckMessage(MSG_KEY_SETTER); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void test() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); checkConfig.addAttribute("prefix", "m"); final String[] expected = { - "7: " + warningSetterMessage, - "10: " + warningGetterMessage, - "13: " + warningSetterMessage, - "16: " + warningGetterMessage, - "25: " + warningSetterMessage, - "28: " + warningGetterMessage, + "7:9: " + warningSetterMessage, + "10:9: " + warningGetterMessage, + "13:9: " + warningSetterMessage, + "16:9: " + warningGetterMessage, + "25:9: " + warningSetterMessage, + "28:9: " + warningGetterMessage, }; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck.java"), expected); } @Test public void correctWithoutPrefix() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); final String[] expected = { - "17: " + warningSetterMessage, - "22: " + warningGetterMessage, + "17:5: " + warningSetterMessage, + "22:5: " + warningGetterMessage, }; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation1.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck1.java"), expected); } @Test - public void correctWithtPrefix() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + public void correctWithPrefix() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); checkConfig.addAttribute("prefix", "m"); final String[] expected = { - "7: " + warningSetterMessage, - "12: " + warningGetterMessage, + "7:5: " + warningSetterMessage, + "12:5: " + warningGetterMessage, }; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation1.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck1.java"), expected); } @Test public void partlyWithoutPrefix() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); final String[] expected = { - "15: " + warningGetterMessage, - "20: " + warningSetterMessage, - "30: " + warningSetterMessage, - "35: " + warningGetterMessage, - "40: " + warningSetterMessage, - "45: " + warningGetterMessage, + "15:5: " + warningGetterMessage, + "20:5: " + warningSetterMessage, + "30:5: " + warningSetterMessage, + "35:5: " + warningGetterMessage, + "40:5: " + warningSetterMessage, + "45:5: " + warningGetterMessage, }; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation2.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck2.java"), expected); } @Test public void partlyWithPrefix() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); checkConfig.addAttribute("prefix", "m"); final String[] expected = { - "10: " + warningSetterMessage, - "15: " + warningGetterMessage, - "20: " + warningSetterMessage, - "25: " + warningGetterMessage, - "35: " + warningGetterMessage, - "40: " + warningSetterMessage, + "10:5: " + warningSetterMessage, + "15:5: " + warningGetterMessage, + "20:5: " + warningSetterMessage, + "25:5: " + warningGetterMessage, + "35:5: " + warningGetterMessage, + "40:5: " + warningSetterMessage, }; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation2.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck2.java"), expected); } @Test public void errorsWithoutPrefix() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); final String[] expected = { - "7: " + warningSetterMessage, - "12: " + warningGetterMessage, - "17: " + warningSetterMessage, - "22: " + warningGetterMessage, + "7:5: " + warningSetterMessage, + "12:5: " + warningGetterMessage, + "17:5: " + warningSetterMessage, + "22:5: " + warningGetterMessage, }; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation3.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck3.java"), expected); } @Test public void errorsWithPrefix() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); checkConfig.addAttribute("prefix", "m"); final String[] expected = { - "7: " + warningSetterMessage, - "12: " + warningGetterMessage, - "17: " + warningSetterMessage, - "22: " + warningGetterMessage, + "7:5: " + warningSetterMessage, + "12:5: " + warningGetterMessage, + "17:5: " + warningSetterMessage, + "22:5: " + warningGetterMessage, }; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation3.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck3.java"), expected); } @Test public void cleanWithoutPrefix() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation4.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck4.java"), expected); } @Test public void cleanWithPrefix() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); checkConfig.addAttribute("prefix", "m"); final String[] expected = {}; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation4.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck4.java"), expected); } @Test public void testBoolean() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); final String[] expected = { - "28: " + warningSetterMessage, - "33: " + warningGetterMessage, + "28:5: " + warningSetterMessage, + "33:5: " + warningGetterMessage, }; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation5.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck5.java"), expected); } @Test public void testAnonymousCases() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation6.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck6.java"), expected); } @Test public void testInterface() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SimpleAccessorNameNotationCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SimpleAccessorNameNotationCheck.class); final String[] expected = {}; - verify(checkConfig, getPath("InputSimpleAccessorNameNotation7.java"), expected); + verify(checkConfig, getPath("InputSimpleAccessorNameNotationCheck7.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SingleBreakOrContinueCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SingleBreakOrContinueCheckTest.java index ca73e80457..0d16084bb5 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SingleBreakOrContinueCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/SingleBreakOrContinueCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,36 +23,42 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; /** * @author Yasser Aziza */ -public class SingleBreakOrContinueCheckTest extends BaseCheckTestSupport { +public class SingleBreakOrContinueCheckTest extends AbstractModuleTestSupport { /** * An error message for current check. */ private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void testDefault() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(SingleBreakOrContinueCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(SingleBreakOrContinueCheck.class); final String[] expected = { - "8: " + warningMessage, - "26: " + warningMessage, - "44: " + warningMessage, - "88: " + warningMessage, - "106: " + warningMessage, - "124: " + warningMessage, - "168: " + warningMessage, - "187: " + warningMessage, - "206: " + warningMessage, - "346: " + warningMessage, - "367: " + warningMessage, - "389: " + warningMessage, + "8:9: " + warningMessage, + "26:9: " + warningMessage, + "44:9: " + warningMessage, + "88:9: " + warningMessage, + "106:9: " + warningMessage, + "124:9: " + warningMessage, + "168:9: " + warningMessage, + "187:9: " + warningMessage, + "206:9: " + warningMessage, + "346:13: " + warningMessage, + "367:13: " + warningMessage, + "389:13: " + warningMessage, }; verify(checkConfig, getPath("InputSingleBreakOrContinueCheck.java"), diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/TernaryPerExpressionCountCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/TernaryPerExpressionCountCheckTest.java index 7d08aec0d9..725190021c 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/TernaryPerExpressionCountCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/TernaryPerExpressionCountCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -24,38 +24,40 @@ import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; /** * @author Aleksey Nesterenko */ -public class TernaryPerExpressionCountCheckTest extends BaseCheckTestSupport { +public class TernaryPerExpressionCountCheckTest extends AbstractModuleTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(TernaryPerExpressionCountCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testWithDefaultTernaryPerExpressionCountValue() throws Exception { - final int maxTernaryOperatorsCount = 1; - final boolean ternaryInBraces = true; - final boolean oneLine = true; + final DefaultConfiguration checkConfig = + createModuleConfig(TernaryPerExpressionCountCheck.class); checkConfig.addAttribute("ignoreTernaryOperatorsInBraces", - Boolean.toString(ternaryInBraces)); + "true"); checkConfig.addAttribute("ignoreIsolatedTernaryOnLine", - Boolean.toString(oneLine)); + "true"); checkConfig.addAttribute("maxTernaryPerExpressionCount", - Integer.toString(maxTernaryOperatorsCount)); + "1"); final String[] expected = { - "14:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "18:32: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "20:33: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "21:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "25:56: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "26:50: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "30:47: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "47:36: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), + "14:26: " + getCheckMessage(MSG_KEY, 1), + "18:32: " + getCheckMessage(MSG_KEY, 1), + "20:33: " + getCheckMessage(MSG_KEY, 1), + "21:26: " + getCheckMessage(MSG_KEY, 1), + "25:56: " + getCheckMessage(MSG_KEY, 1), + "26:50: " + getCheckMessage(MSG_KEY, 1), + "30:47: " + getCheckMessage(MSG_KEY, 1), + "47:36: " + getCheckMessage(MSG_KEY, 1), }; verify(checkConfig, getPath("InputTernaryPerExpressionCountCheck.java"), expected); @@ -64,15 +66,14 @@ public void testWithDefaultTernaryPerExpressionCountValue() @Test public void testWithNegativeTernaryPerExpressionCountValue() throws Exception { - final int maxTernaryOperatorsCount = -1; - final boolean ternaryInBraces = true; - final boolean oneLine = false; + final DefaultConfiguration checkConfig = + createModuleConfig(TernaryPerExpressionCountCheck.class); checkConfig.addAttribute("ignoreTernaryOperatorsInBraces", - Boolean.toString(ternaryInBraces)); + "true"); checkConfig.addAttribute("ignoreIsolatedTernaryOnLine", - Boolean.toString(oneLine)); + "false"); checkConfig.addAttribute("maxTernaryPerExpressionCount", - Integer.toString(maxTernaryOperatorsCount)); + "-1"); final String[] expected = {}; try { @@ -83,55 +84,55 @@ public void testWithNegativeTernaryPerExpressionCountValue() } catch (CheckstyleException ex) { final String errorMsg = ex.getMessage(); - Assert.assertTrue(errorMsg - .contains("Cannot set property 'maxTernaryPerExpressionCount' to '-1' in module " - + "com.github.sevntu.checkstyle.checks.coding.TernaryPerExpressionCountCheck")); + final String expectedMessage = "Cannot set property 'maxTernaryPerExpressionCount' " + + "to '-1' in module com.github.sevntu.checkstyle.checks.coding." + + "TernaryPerExpressionCountCheck"; + Assert.assertTrue("Expected error message is missing: " + expectedMessage, + errorMsg.contains(expectedMessage)); } } @Test public void testWithDifferentTernaryPerExpressionCountValue() throws Exception { - final boolean ternaryInBraces = true; - final boolean oneLine = false; - final int maxTernaryOperatorsCount = 2; + final DefaultConfiguration checkConfig = + createModuleConfig(TernaryPerExpressionCountCheck.class); checkConfig.addAttribute("ignoreTernaryOperatorsInBraces", - Boolean.toString(ternaryInBraces)); + "true"); checkConfig.addAttribute("ignoreIsolatedTernaryOnLine", - Boolean.toString(oneLine)); + "false"); checkConfig.addAttribute("maxTernaryPerExpressionCount", - Integer.toString(maxTernaryOperatorsCount)); - final String[] expected = {"14:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount)}; + "2"); + final String[] expected = {"14:26: " + getCheckMessage(MSG_KEY, 2)}; verify(checkConfig, getPath("InputTernaryPerExpressionCountCheck.java"), expected); } @Test public void testWithZeroValue() throws Exception { - final boolean ternaryInBraces = false; - final boolean oneLine = true; - final int maxTernaryOperatorsCount = 0; + final DefaultConfiguration checkConfig = + createModuleConfig(TernaryPerExpressionCountCheck.class); checkConfig.addAttribute("ignoreTernaryOperatorsInBraces", - Boolean.toString(ternaryInBraces)); + "false"); checkConfig.addAttribute("ignoreIsolatedTernaryOnLine", - Boolean.toString(oneLine)); + "true"); checkConfig.addAttribute("maxTernaryPerExpressionCount", - Integer.toString(maxTernaryOperatorsCount)); + "0"); final String[] expected = { - "14:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "18:32: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "20:33: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "21:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "25:56: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "26:50: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "30:47: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "31:52: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "35:38: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "36:38: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "37:31: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "38:23: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "47:36: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "101:48: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), + "14:26: " + getCheckMessage(MSG_KEY, 0), + "18:32: " + getCheckMessage(MSG_KEY, 0), + "20:33: " + getCheckMessage(MSG_KEY, 0), + "21:26: " + getCheckMessage(MSG_KEY, 0), + "25:56: " + getCheckMessage(MSG_KEY, 0), + "26:50: " + getCheckMessage(MSG_KEY, 0), + "30:47: " + getCheckMessage(MSG_KEY, 0), + "31:52: " + getCheckMessage(MSG_KEY, 0), + "35:38: " + getCheckMessage(MSG_KEY, 0), + "36:38: " + getCheckMessage(MSG_KEY, 0), + "37:31: " + getCheckMessage(MSG_KEY, 0), + "38:23: " + getCheckMessage(MSG_KEY, 0), + "47:36: " + getCheckMessage(MSG_KEY, 0), + "101:48: " + getCheckMessage(MSG_KEY, 0), }; verify(checkConfig, getPath("InputTernaryPerExpressionCountCheck.java"), expected); @@ -139,28 +140,27 @@ public void testWithZeroValue() throws Exception { @Test public void testWithoutIgnoringExpressionInBraces() throws Exception { - final boolean ternaryInBraces = false; - final boolean oneLine = true; - final int maxTernaryOperatorsCount = 1; + final DefaultConfiguration checkConfig = + createModuleConfig(TernaryPerExpressionCountCheck.class); checkConfig.addAttribute("ignoreTernaryOperatorsInBraces", - Boolean.toString(ternaryInBraces)); + "false"); checkConfig.addAttribute("ignoreIsolatedTernaryOnLine", - Boolean.toString(oneLine)); + "true"); final String[] expected = { - "14:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "18:32: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "20:33: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "21:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "25:56: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "26:50: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "30:47: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "31:52: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "35:38: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "36:38: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "37:31: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "38:23: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "47:36: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "101:48: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), + "14:26: " + getCheckMessage(MSG_KEY, 1), + "18:32: " + getCheckMessage(MSG_KEY, 1), + "20:33: " + getCheckMessage(MSG_KEY, 1), + "21:26: " + getCheckMessage(MSG_KEY, 1), + "25:56: " + getCheckMessage(MSG_KEY, 1), + "26:50: " + getCheckMessage(MSG_KEY, 1), + "30:47: " + getCheckMessage(MSG_KEY, 1), + "31:52: " + getCheckMessage(MSG_KEY, 1), + "35:38: " + getCheckMessage(MSG_KEY, 1), + "36:38: " + getCheckMessage(MSG_KEY, 1), + "37:31: " + getCheckMessage(MSG_KEY, 1), + "38:23: " + getCheckMessage(MSG_KEY, 1), + "47:36: " + getCheckMessage(MSG_KEY, 1), + "101:48: " + getCheckMessage(MSG_KEY, 1), }; verify(checkConfig, getPath("InputTernaryPerExpressionCountCheck.java"), expected); @@ -168,35 +168,34 @@ public void testWithoutIgnoringExpressionInBraces() throws Exception { @Test public void testWithoutIgnoringSingleTernariesPerLine() throws Exception { - final boolean ternaryInBraces = false; - final boolean oneLine = false; - final int maxTernaryOperatorsCount = 1; + final DefaultConfiguration checkConfig = + createModuleConfig(TernaryPerExpressionCountCheck.class); checkConfig.addAttribute("ignoreTernaryOperatorsInBraces", - Boolean.toString(ternaryInBraces)); + "false"); checkConfig.addAttribute("ignoreIsolatedTernaryOnLine", - Boolean.toString(oneLine)); + "false"); final String[] expected = { - "14:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "18:32: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "20:33: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "21:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "25:56: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "26:50: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "30:47: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "31:52: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "35:38: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "36:38: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "37:31: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "38:23: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "47:36: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "49:47: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "57:41: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "67:39: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "79:41: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "91:29: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "94:29: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "99:29: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "101:48: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), + "14:26: " + getCheckMessage(MSG_KEY, 1), + "18:32: " + getCheckMessage(MSG_KEY, 1), + "20:33: " + getCheckMessage(MSG_KEY, 1), + "21:26: " + getCheckMessage(MSG_KEY, 1), + "25:56: " + getCheckMessage(MSG_KEY, 1), + "26:50: " + getCheckMessage(MSG_KEY, 1), + "30:47: " + getCheckMessage(MSG_KEY, 1), + "31:52: " + getCheckMessage(MSG_KEY, 1), + "35:38: " + getCheckMessage(MSG_KEY, 1), + "36:38: " + getCheckMessage(MSG_KEY, 1), + "37:31: " + getCheckMessage(MSG_KEY, 1), + "38:23: " + getCheckMessage(MSG_KEY, 1), + "47:36: " + getCheckMessage(MSG_KEY, 1), + "49:47: " + getCheckMessage(MSG_KEY, 1), + "57:41: " + getCheckMessage(MSG_KEY, 1), + "67:39: " + getCheckMessage(MSG_KEY, 1), + "79:41: " + getCheckMessage(MSG_KEY, 1), + "91:29: " + getCheckMessage(MSG_KEY, 1), + "94:29: " + getCheckMessage(MSG_KEY, 1), + "99:29: " + getCheckMessage(MSG_KEY, 1), + "101:48: " + getCheckMessage(MSG_KEY, 1), }; verify(checkConfig, getPath("InputTernaryPerExpressionCountCheck.java"), expected); @@ -204,30 +203,29 @@ public void testWithoutIgnoringSingleTernariesPerLine() throws Exception { @Test public void testWithIgnoringOneTernaryPerLine() throws Exception { - final boolean ternaryInBraces = false; - final boolean oneLine = true; - final int maxTernaryOperatorsCount = 0; + final DefaultConfiguration checkConfig = + createModuleConfig(TernaryPerExpressionCountCheck.class); checkConfig.addAttribute("ignoreTernaryOperatorsInBraces", - Boolean.toString(ternaryInBraces)); + "false"); checkConfig.addAttribute("ignoreIsolatedTernaryOnLine", - Boolean.toString(oneLine)); + "true"); checkConfig.addAttribute("maxTernaryPerExpressionCount", - Integer.toString(maxTernaryOperatorsCount)); + "0"); final String[] expected = { - "14:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "18:32: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "20:33: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "21:26: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "25:56: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "26:50: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "30:47: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "31:52: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "35:38: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "36:38: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "37:31: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "38:23: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "47:36: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), - "101:48: " + getCheckMessage(MSG_KEY, maxTernaryOperatorsCount), + "14:26: " + getCheckMessage(MSG_KEY, 0), + "18:32: " + getCheckMessage(MSG_KEY, 0), + "20:33: " + getCheckMessage(MSG_KEY, 0), + "21:26: " + getCheckMessage(MSG_KEY, 0), + "25:56: " + getCheckMessage(MSG_KEY, 0), + "26:50: " + getCheckMessage(MSG_KEY, 0), + "30:47: " + getCheckMessage(MSG_KEY, 0), + "31:52: " + getCheckMessage(MSG_KEY, 0), + "35:38: " + getCheckMessage(MSG_KEY, 0), + "36:38: " + getCheckMessage(MSG_KEY, 0), + "37:31: " + getCheckMessage(MSG_KEY, 0), + "38:23: " + getCheckMessage(MSG_KEY, 0), + "47:36: " + getCheckMessage(MSG_KEY, 0), + "101:48: " + getCheckMessage(MSG_KEY, 0), }; verify(checkConfig, getPath("InputTernaryPerExpressionCountCheck.java"), expected); diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UnnecessaryParenthesesExtendedCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UnnecessaryParenthesesExtendedCheckTest.java index 23ac7bf629..c21c510911 100755 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UnnecessaryParenthesesExtendedCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UnnecessaryParenthesesExtendedCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -28,7 +28,7 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; /** @@ -37,11 +37,17 @@ * @author Eric K. Roe * @author Antonenko Dmitriy */ -public class UnnecessaryParenthesesExtendedCheckTest extends BaseCheckTestSupport { +public class UnnecessaryParenthesesExtendedCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } + @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(UnnecessaryParenthesesExtendedCheck.class); + createModuleConfig(UnnecessaryParenthesesExtendedCheck.class); checkConfig.addAttribute("ignoreCalculationOfBooleanVariables", "false"); checkConfig.addAttribute("ignoreCalculationOfBooleanVariablesWithReturn", "false"); checkConfig.addAttribute("ignoreCalculationOfBooleanVariablesWithAssert", "false"); @@ -93,22 +99,24 @@ public void testDefault() throws Exception { "86:16: " + getCheckMessage(MSG_KEY_EXPR), }; - verify(checkConfig, getPath("InputUnnecessaryParentheses.java"), expected); + verify(checkConfig, getPath("InputUnnecessaryParenthesesExtendedCheck.java"), expected); } @Test public void test15Extensions() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(UnnecessaryParenthesesExtendedCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(UnnecessaryParenthesesExtendedCheck.class); final String[] expected = {}; checkConfig.addAttribute("ignoreCalculationOfBooleanVariables", "false"); checkConfig.addAttribute("ignoreCalculationOfBooleanVariablesWithReturn", "false"); checkConfig.addAttribute("ignoreCalculationOfBooleanVariablesWithAssert", "false"); - verify(checkConfig, getPath("Input15Extensions.java"), expected); + verify(checkConfig, getPath("InputUnnecessaryParenthesesExtendedCheck2.java"), expected); } @Test public void testUbv() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(UnnecessaryParenthesesExtendedCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(UnnecessaryParenthesesExtendedCheck.class); final String[] expected = { "5:22: " + getCheckMessage(MSG_KEY_ASSIGN), "5:29: " + getCheckMessage(MSG_KEY_EXPR), @@ -156,10 +164,12 @@ public void testUbv() throws Exception { "82:27: " + getCheckMessage(MSG_KEY_ASSIGN), "96:19: " + getCheckMessage(MSG_KEY_ASSIGN), "100:24: " + getCheckMessage(MSG_KEY_EXPR), + "123:27: " + getCheckMessage(MSG_KEY_IDENT, "i"), }; checkConfig.addAttribute("ignoreCalculationOfBooleanVariables", "true"); checkConfig.addAttribute("ignoreCalculationOfBooleanVariablesWithReturn", "true"); checkConfig.addAttribute("ignoreCalculationOfBooleanVariablesWithAssert", "true"); - verify(checkConfig, getPath("InputUnnecessaryParenthesesUbv.java"), expected); + verify(checkConfig, getPath("InputUnnecessaryParenthesesExtendedCheckUbv.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UselessSingleCatchCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UselessSingleCatchCheckTest.java index 453e96c84d..edcd328c0f 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UselessSingleCatchCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UselessSingleCatchCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,16 +23,21 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class UselessSingleCatchCheckTest extends BaseCheckTestSupport { +public class UselessSingleCatchCheckTest extends AbstractModuleTestSupport { + private final String warningMessage = getCheckMessage(MSG_KEY); - private final DefaultConfiguration config = createCheckConfig(UselessSingleCatchCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testMultiCatch() throws Exception { + final DefaultConfiguration config = createModuleConfig(UselessSingleCatchCheck.class); final String[] expected = {}; verify(config, getPath("InputUselessSingleCatchCheck1.java"), expected); @@ -40,6 +45,7 @@ public void testMultiCatch() throws Exception { @Test public void testWrappingCatch() throws Exception { + final DefaultConfiguration config = createModuleConfig(UselessSingleCatchCheck.class); final String[] expected = {}; verify(config, getPath("InputUselessSingleCatchCheck2.java"), expected); @@ -47,6 +53,7 @@ public void testWrappingCatch() throws Exception { @Test public void testLoggingCatch() throws Exception { + final DefaultConfiguration config = createModuleConfig(UselessSingleCatchCheck.class); final String[] expected = {}; verify(config, getPath("InputUselessSingleCatchCheck3.java"), expected); @@ -54,6 +61,7 @@ public void testLoggingCatch() throws Exception { @Test public void testThrowsAnotherException() throws Exception { + final DefaultConfiguration config = createModuleConfig(UselessSingleCatchCheck.class); final String[] expected = {}; verify(config, getPath("InputUselessSingleCatchCheck4.java"), expected); @@ -61,10 +69,12 @@ public void testThrowsAnotherException() throws Exception { @Test public void testUselessCatch() throws Exception { + final DefaultConfiguration config = createModuleConfig(UselessSingleCatchCheck.class); final String[] expected = { "15:9: " + warningMessage, }; verify(config, getPath("InputUselessSingleCatchCheck5.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UselessSuperCtorCallCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UselessSuperCtorCallCheckTest.java index c6940dc34a..b399666292 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UselessSuperCtorCallCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/UselessSuperCtorCallCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -24,82 +24,99 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class UselessSuperCtorCallCheckTest extends BaseCheckTestSupport { - private final DefaultConfiguration mDefaultConfig = createCheckConfig(UselessSuperCtorCallCheck.class); +public class UselessSuperCtorCallCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testSingleCtorWithSuperWithinNotDerivedClass() throws Exception { + final DefaultConfiguration mDefaultConfig = + createModuleConfig(UselessSuperCtorCallCheck.class); final String[] expected = { - "7:9: " + getCheckMessage(MSG_IN_NOT_DERIVED_CLASS, "InputUselessSuperCtorCall1"), + "7:9: " + getCheckMessage(MSG_IN_NOT_DERIVED_CLASS, "InputUselessSuperCtorCallCheck1"), }; - verify(mDefaultConfig, getPath("InputUselessSuperCtorCall1.java"), expected); + verify(mDefaultConfig, getPath("InputUselessSuperCtorCallCheck1.java"), expected); } @Test public void testSingleCtorWithSuperWithinDerivedClass() throws Exception { + final DefaultConfiguration mDefaultConfig = + createModuleConfig(UselessSuperCtorCallCheck.class); final String[] expected = { - "7:9: " + getCheckMessage(MSG_WITHOUT_ARGS, "InputUselessSuperCtorCall2"), + "7:9: " + getCheckMessage(MSG_WITHOUT_ARGS, "InputUselessSuperCtorCallCheck2"), }; - verify(mDefaultConfig, getPath("InputUselessSuperCtorCall2.java"), expected); + verify(mDefaultConfig, getPath("InputUselessSuperCtorCallCheck2.java"), expected); } @Test public void testMultipleCtorsWithSuperWithinNotDerivedClass() throws Exception { + final DefaultConfiguration mDefaultConfig = + createModuleConfig(UselessSuperCtorCallCheck.class); final String[] expected = { - "7:9: " + getCheckMessage(MSG_IN_NOT_DERIVED_CLASS, "InputUselessSuperCtorCall3"), - "12:9: " + getCheckMessage(MSG_IN_NOT_DERIVED_CLASS, "InputUselessSuperCtorCall3"), + "7:9: " + getCheckMessage(MSG_IN_NOT_DERIVED_CLASS, "InputUselessSuperCtorCallCheck3"), + "12:9: " + getCheckMessage(MSG_IN_NOT_DERIVED_CLASS, "InputUselessSuperCtorCallCheck3"), }; - verify(mDefaultConfig, getPath("InputUselessSuperCtorCall3.java"), expected); + verify(mDefaultConfig, getPath("InputUselessSuperCtorCallCheck3.java"), expected); } @Test public void testInnerClassWithCtorWithSuper() throws Exception { + final DefaultConfiguration mDefaultConfig = + createModuleConfig(UselessSuperCtorCallCheck.class); final String[] expected = { "9:13: " + getCheckMessage(MSG_IN_NOT_DERIVED_CLASS, "Inner"), }; - verify(mDefaultConfig, getPath("InputUselessSuperCtorCall4.java"), expected); + verify(mDefaultConfig, getPath("InputUselessSuperCtorCallCheck4.java"), expected); } @Test public void testClassWithSuperCtorWithArgs() throws Exception { + final DefaultConfiguration mDefaultConfig = + createModuleConfig(UselessSuperCtorCallCheck.class); final String[] expected = {}; - verify(mDefaultConfig, getPath("InputUselessSuperCtorCall5.java"), expected); + verify(mDefaultConfig, getPath("InputUselessSuperCtorCallCheck5.java"), expected); } @Test public void testOptionAllowCallToNoArgsSuperCtor() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(UselessSuperCtorCallCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(UselessSuperCtorCallCheck.class); checkConfig.addAttribute("allowCallToNoArgsSuperCtor", "true"); final String[] expected = {}; - verify(checkConfig, getPath("InputUselessSuperCtorCall6.java"), expected); + verify(checkConfig, getPath("InputUselessSuperCtorCallCheck6.java"), expected); } @Test public void testOptionAllowCallToNoArgsSuperCtorIfMultiplePublicCtor() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(UselessSuperCtorCallCheck.class); + final DefaultConfiguration checkConfig = + createModuleConfig(UselessSuperCtorCallCheck.class); checkConfig.addAttribute("allowCallToNoArgsSuperCtorIfMultiplePublicCtor", "true"); final String[] expected = { "26:13: " + getCheckMessage(MSG_WITHOUT_ARGS, "DerivedTwo"), }; - verify(checkConfig, getPath("InputUselessSuperCtorCall7.java"), expected); + verify(checkConfig, getPath("InputUselessSuperCtorCallCheck7.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/WhitespaceBeforeArrayInitializerCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/WhitespaceBeforeArrayInitializerCheckTest.java index 78ed4932ed..6da9e912ef 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/WhitespaceBeforeArrayInitializerCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/coding/WhitespaceBeforeArrayInitializerCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,14 +23,20 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class WhitespaceBeforeArrayInitializerCheckTest extends BaseCheckTestSupport { - private final DefaultConfiguration mDefaultConfig = createCheckConfig(WhitespaceBeforeArrayInitializerCheck.class); +public class WhitespaceBeforeArrayInitializerCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/coding"; + } @Test public void testWhitespaceBeforeArrayInitializer() throws Exception { + final DefaultConfiguration mDefaultConfig = + createModuleConfig(WhitespaceBeforeArrayInitializerCheck.class); final String[] expected = { "5:28: " + getCheckMessage(MSG_KEY), "13:32: " + getCheckMessage(MSG_KEY), @@ -38,6 +44,8 @@ public void testWhitespaceBeforeArrayInitializer() throws Exception { "17:21: " + getCheckMessage(MSG_KEY), "24:56: " + getCheckMessage(MSG_KEY), }; - verify(mDefaultConfig, getPath("InputWhitespaceBeforeArrayIntializer.java"), expected); + verify(mDefaultConfig, getPath("InputWhitespaceBeforeArrayInitializerCheck.java"), + expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionCheckTest.java new file mode 100644 index 0000000000..ad57f628bd --- /dev/null +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionCheckTest.java @@ -0,0 +1,103 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.design; + +import static com.github.sevntu.checkstyle.checks.design.AvoidConditionInversionCheck.MSG_KEY; +import static org.junit.Assert.fail; + +import org.junit.Assert; +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; + +/** + * + * @author Aleksey Nesterenko + * + */ +public class AvoidConditionInversionCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } + + @Test + public void defaultTest() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidConditionInversionCheck.class); + final String[] expected = { + "7:24: " + getCheckMessage(MSG_KEY), + "11:24: " + getCheckMessage(MSG_KEY), + "15:24: " + getCheckMessage(MSG_KEY), + "19:21: " + getCheckMessage(MSG_KEY), + "23:24: " + getCheckMessage(MSG_KEY), + "29:27: " + getCheckMessage(MSG_KEY), + "31:34: " + getCheckMessage(MSG_KEY), + "39:24: " + getCheckMessage(MSG_KEY), + "102:21: " + getCheckMessage(MSG_KEY), + "107:21: " + getCheckMessage(MSG_KEY), + }; + + verify(checkConfig, getPath("InputAvoidConditionInversionCheck.java"), + expected); + } + + @Test + public void avoidOnlyRelationalOperandsInCondition() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(AvoidConditionInversionCheck.class); + checkConfig.addAttribute("applyOnlyToRelationalOperands", + "true"); + + final String[] expected = { + "7:24: " + getCheckMessage(MSG_KEY), + "11:24: " + getCheckMessage(MSG_KEY), + "15:24: " + getCheckMessage(MSG_KEY), + "19:21: " + getCheckMessage(MSG_KEY), + "23:24: " + getCheckMessage(MSG_KEY), + "29:27: " + getCheckMessage(MSG_KEY), + "31:34: " + getCheckMessage(MSG_KEY), + }; + + verify(checkConfig, getPath("InputAvoidConditionInversionCheck.java"), + expected); + } + + @Test + public void testUnsupportedNode() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final AvoidConditionInversionCheck check = new AvoidConditionInversionCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } + } + +} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionTest.java deleted file mode 100644 index 2a97f44aa8..0000000000 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/AvoidConditionInversionTest.java +++ /dev/null @@ -1,79 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.github.sevntu.checkstyle.checks.design; - -import static com.github.sevntu.checkstyle.checks.design.AvoidConditionInversionCheck.MSG_KEY; - -import org.junit.Test; - -import com.github.sevntu.checkstyle.BaseCheckTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; - -/** - * - * @author Aleksey Nesterenko - * - */ -public class AvoidConditionInversionTest extends BaseCheckTestSupport { - private final DefaultConfiguration checkConfig = - createCheckConfig(AvoidConditionInversionCheck.class); - - @Test - public void defaultTest() throws Exception { - - final String[] expected = { - "7: " + getCheckMessage(MSG_KEY), - "11: " + getCheckMessage(MSG_KEY), - "15: " + getCheckMessage(MSG_KEY), - "19: " + getCheckMessage(MSG_KEY), - "23: " + getCheckMessage(MSG_KEY), - "29: " + getCheckMessage(MSG_KEY), - "31: " + getCheckMessage(MSG_KEY), - "39: " + getCheckMessage(MSG_KEY), - "102: " + getCheckMessage(MSG_KEY), - "107: " + getCheckMessage(MSG_KEY), - }; - - verify(checkConfig, getPath("InputAvoidConditionInversion.java"), - expected); - } - - @Test - public void avoidOnlyRelationalOperandsInCondition() throws Exception { - - final boolean applyOnlyToMathematicalOperands = true; - checkConfig.addAttribute("applyOnlyToRelationalOperands", - Boolean.toString(applyOnlyToMathematicalOperands)); - - final String[] expected = { - "7: " + getCheckMessage(MSG_KEY), - "11: " + getCheckMessage(MSG_KEY), - "15: " + getCheckMessage(MSG_KEY), - "19: " + getCheckMessage(MSG_KEY), - "23: " + getCheckMessage(MSG_KEY), - "29: " + getCheckMessage(MSG_KEY), - "31: " + getCheckMessage(MSG_KEY), - }; - - verify(checkConfig, getPath("InputAvoidConditionInversion.java"), - expected); - } - -} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/CauseParameterInExceptionCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/CauseParameterInExceptionCheckTest.java index 8c46bf313f..76c60b6c75 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/CauseParameterInExceptionCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/CauseParameterInExceptionCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,74 +20,92 @@ package com.github.sevntu.checkstyle.checks.design; import static com.github.sevntu.checkstyle.checks.design.CauseParameterInExceptionCheck.MSG_KEY; +import static org.junit.Assert.fail; +import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * @author Daniil * Yaroslavtsev */ -public class CauseParameterInExceptionCheckTest extends BaseCheckTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(CauseParameterInExceptionCheck.class); +public class CauseParameterInExceptionCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } @Test public void testNormalWork() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CauseParameterInExceptionCheck.class); checkConfig.addAttribute("classNamesRegexp", ".+Exception"); checkConfig.addAttribute("ignoredClassNamesRegexp", null); checkConfig.addAttribute("allowedCauseTypes", "Throwable, Exception"); final String[] expected = { - "3:1: " + getCheckMessage(MSG_KEY, "InputCauseParameterInException"), + "5:5: " + getCheckMessage(MSG_KEY, "TestException"), }; - verify(checkConfig, getPath("InputCauseParameterInException.java"), expected); + verify(checkConfig, getPath("InputCauseParameterInExceptionCheck.java"), expected); } @Test public void testNormalWork2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CauseParameterInExceptionCheck.class); checkConfig.addAttribute("classNamesRegexp", ".+Exception2"); checkConfig.addAttribute("ignoredClassNamesRegexp", null); checkConfig.addAttribute("allowedCauseTypes", "Throwable, Exception"); final String[] expected = { - "3:1: " + getCheckMessage(MSG_KEY, "InputCauseParameterInException2"), + "5:5: " + getCheckMessage(MSG_KEY, "TestException2"), "16:5: " + getCheckMessage(MSG_KEY, "MyException2"), }; - verify(checkConfig, getPath("InputCauseParameterInException2.java"), expected); + verify(checkConfig, getPath("InputCauseParameterInExceptionCheck2.java"), expected); } @Test public void testIgnorePattern() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CauseParameterInExceptionCheck.class); checkConfig.addAttribute("classNamesRegexp", ".+Exception2"); - checkConfig.addAttribute("ignoredClassNamesRegexp", "Input.+"); + checkConfig.addAttribute("ignoredClassNamesRegexp", "Test.+"); checkConfig.addAttribute("allowedCauseTypes", "Throwable, Exception"); final String[] expected = { "16:5: " + getCheckMessage(MSG_KEY, "MyException2"), }; - verify(checkConfig, getPath("InputCauseParameterInException2.java"), expected); + verify(checkConfig, getPath("InputCauseParameterInExceptionCheck2.java"), expected); } @Test public void testIgnorePattern2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CauseParameterInExceptionCheck.class); checkConfig.addAttribute("classNamesRegexp", ".+Exception2"); checkConfig.addAttribute("ignoredClassNamesRegexp", "My.+"); checkConfig.addAttribute("allowedCauseTypes", "Throwable, Exception"); final String[] expected = { - "3:1: " + getCheckMessage(MSG_KEY, "InputCauseParameterInException2"), + "5:5: " + getCheckMessage(MSG_KEY, "TestException2"), }; - verify(checkConfig, getPath("InputCauseParameterInException2.java"), expected); + verify(checkConfig, getPath("InputCauseParameterInExceptionCheck2.java"), expected); } @Test public void testStrangeSituation() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CauseParameterInExceptionCheck.class); checkConfig.addAttribute("classNamesRegexp", ".+Exception"); checkConfig.addAttribute("ignoredClassNamesRegexp", ""); checkConfig.addAttribute("allowedCauseTypes", "Throwable, Exception"); @@ -95,11 +113,13 @@ public void testStrangeSituation() throws Exception { final String[] expected = { }; - verify(checkConfig, getPath("InputCauseParameterInException3.java"), expected); + verify(checkConfig, getPath("InputCauseParameterInExceptionCheck3.java"), expected); } @Test public void testStrangeSituation2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CauseParameterInExceptionCheck.class); checkConfig.addAttribute("classNamesRegexp", null); checkConfig.addAttribute("ignoredClassNamesRegexp", null); checkConfig.addAttribute("allowedCauseTypes", "Throwable, Exception"); @@ -107,11 +127,13 @@ public void testStrangeSituation2() throws Exception { final String[] expected = { }; - verify(checkConfig, getPath("InputCauseParameterInException3.java"), expected); + verify(checkConfig, getPath("InputCauseParameterInExceptionCheck3.java"), expected); } @Test public void testStrangeSituation3() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CauseParameterInExceptionCheck.class); checkConfig.addAttribute("classNamesRegexp", null); checkConfig.addAttribute("ignoredClassNamesRegexp", null); checkConfig.addAttribute("allowedCauseTypes", "Throwable, Exception"); @@ -119,11 +141,13 @@ public void testStrangeSituation3() throws Exception { final String[] expected = { }; - verify(checkConfig, getPath("InputCauseParameterInException4.java"), expected); + verify(checkConfig, getPath("InputCauseParameterInExceptionCheck4.java"), expected); } @Test public void testStrangeSituation4() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CauseParameterInExceptionCheck.class); checkConfig.addAttribute("classNamesRegexp", null); checkConfig.addAttribute("ignoredClassNamesRegexp", null); checkConfig.addAttribute("allowedCauseTypes", "Throwable, Exception"); @@ -131,6 +155,23 @@ public void testStrangeSituation4() throws Exception { final String[] expected = { }; - verify(checkConfig, getPath("InputCauseParameterInException5.java"), expected); + verify(checkConfig, getPath("InputCauseParameterInExceptionCheck5.java"), expected); + } + + @Test + public void testUnsupportedNode() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final CauseParameterInExceptionCheck check = new CauseParameterInExceptionCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/CheckstyleTestMakeupCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/CheckstyleTestMakeupCheckTest.java new file mode 100644 index 0000000000..c80fed1843 --- /dev/null +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/CheckstyleTestMakeupCheckTest.java @@ -0,0 +1,129 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.checks.design; + +import static com.github.sevntu.checkstyle.checks.design.CheckstyleTestMakeupCheck.MSG_KEY_CONFIG_NOT_ASSIGNED; +import static com.github.sevntu.checkstyle.checks.design.CheckstyleTestMakeupCheck.MSG_KEY_CONFIG_NOT_ASSIGNED_PROPERLY; +import static com.github.sevntu.checkstyle.checks.design.CheckstyleTestMakeupCheck.MSG_KEY_CONFIG_NOT_ASSIGNED_WITH; +import static com.github.sevntu.checkstyle.checks.design.CheckstyleTestMakeupCheck.MSG_KEY_CONFIG_NOT_FOUND; +import static com.github.sevntu.checkstyle.checks.design.CheckstyleTestMakeupCheck.MSG_KEY_UNKNOWN_PROPERTY; +import static org.junit.Assert.fail; + +import org.junit.Assert; +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; + +public class CheckstyleTestMakeupCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } + + @Test + public void testMiscFile() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CheckstyleTestMakeupCheck.class); + + final String[] expected = {}; + + verify(checkConfig, getPath("InputCheckstyleTestMakeupCheck.java"), expected); + } + + @Test + public void testValidFile() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CheckstyleTestMakeupCheck.class); + + final String[] expected = {}; + + verify(checkConfig, getPath("InputCheckstyleTestMakeupCheckValid.java"), expected); + } + + @Test + public void testInvalidFile() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CheckstyleTestMakeupCheck.class); + + final String[] expected = { + "8:5: " + getCheckMessage(MSG_KEY_CONFIG_NOT_FOUND), + "15:9: " + getCheckMessage(MSG_KEY_CONFIG_NOT_ASSIGNED), + "21:37: " + getCheckMessage(MSG_KEY_CONFIG_NOT_ASSIGNED_WITH), + "27:9: " + getCheckMessage(MSG_KEY_CONFIG_NOT_ASSIGNED_PROPERLY), + "36:45: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + "37:53: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + "38:44: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + "39:50: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + "40:48: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + "41:55: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + "42:33: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + "43:36: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + "44:35: " + getCheckMessage(MSG_KEY_UNKNOWN_PROPERTY), + }; + + verify(checkConfig, getPath("InputCheckstyleTestMakeupCheckInvalid.java"), expected); + } + + @Test + public void testInvalidFileIgnoreVerifies() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CheckstyleTestMakeupCheck.class); + checkConfig.addAttribute("verifyMethodRegexp", "BAD"); + + final String[] expected = {}; + + verify(checkConfig, getPath("InputCheckstyleTestMakeupCheckInvalid.java"), expected); + } + + @Test + public void testInvalidFileIgnoreCreates() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CheckstyleTestMakeupCheck.class); + checkConfig.addAttribute("createMethodRegexp", "BAD"); + + final String[] expected = { + "16:36: " + getCheckMessage(MSG_KEY_CONFIG_NOT_ASSIGNED_WITH), + "22:43: " + getCheckMessage(MSG_KEY_CONFIG_NOT_ASSIGNED_WITH), + "28:36: " + getCheckMessage(MSG_KEY_CONFIG_NOT_ASSIGNED_WITH), + }; + + verify(checkConfig, getPath("InputCheckstyleTestMakeupCheckValid.java"), expected); + } + + @Test + public void testInvalidToken() { + final DetailAST parent = new DetailAST(); + parent.setType(TokenTypes.OBJBLOCK); + + final CheckstyleTestMakeupCheck check = new CheckstyleTestMakeupCheck(); + try { + check.visitToken(parent); + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: OBJBLOCK", ex.getMessage()); + } + } + +} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthCheckTest.java similarity index 81% rename from sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthTest.java rename to sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthCheckTest.java index f3d4158a6c..56a04c0f47 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ChildBlockLengthCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,18 +23,23 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; /** * @author Daniil * Yaroslavtsev */ -public class ChildBlockLengthTest extends BaseCheckTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(ChildBlockLengthCheck.class); +public class ChildBlockLengthCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } @Test public void testNpeOnAllBlockTypes() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ChildBlockLengthCheck.class); checkConfig.addAttribute("maxChildBlockPercentage", "100"); checkConfig.addAttribute("blockTypes", "LITERAL_IF, LITERAL_SWITCH, LITERAL_FOR, " + "LITERAL_DO, LITERAL_WHILE, LITERAL_TRY, LITERAL_ELSE, LITERAL_CATCH"); @@ -47,6 +52,7 @@ public void testNpeOnAllBlockTypes() throws Exception { @Test public void testNestedConditions() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ChildBlockLengthCheck.class); checkConfig.addAttribute("maxChildBlockPercentage", "100"); checkConfig.addAttribute("blockTypes", "LITERAL_IF, LITERAL_SWITCH, LITERAL_FOR, " + "LITERAL_DO, LITERAL_WHILE, LITERAL_TRY, LITERAL_ELSE, LITERAL_CATCH"); @@ -59,6 +65,7 @@ public void testNestedConditions() throws Exception { @Test public void testManyBadChildBlocks() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ChildBlockLengthCheck.class); checkConfig.addAttribute("maxChildBlockPercentage", "20"); checkConfig.addAttribute("blockTypes", "LITERAL_IF, LITERAL_SWITCH, LITERAL_FOR, " + "LITERAL_DO, LITERAL_WHILE, LITERAL_TRY, LITERAL_ELSE, LITERAL_CATCH"); @@ -68,11 +75,13 @@ public void testManyBadChildBlocks() throws Exception { "15:15: " + getCheckMessage(MSG_KEY, 13, 5), }; - verify(checkConfig, getPath("InputChildBlockLengthCheckManyBlocksOnOneScope.java"), expected); + verify(checkConfig, getPath("InputChildBlockLengthCheckManyBlocksOnOneScope.java"), + expected); } @Test public void testManyBadChildBlocks2() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ChildBlockLengthCheck.class); checkConfig.addAttribute("maxChildBlockPercentage", "19"); checkConfig.addAttribute("blockTypes", "LITERAL_IF, LITERAL_SWITCH, LITERAL_FOR, " + "LITERAL_DO, LITERAL_WHILE, LITERAL_TRY, LITERAL_ELSE, LITERAL_CATCH"); @@ -83,11 +92,13 @@ public void testManyBadChildBlocks2() throws Exception { "31:15: " + getCheckMessage(MSG_KEY, 5, 4), }; - verify(checkConfig, getPath("InputChildBlockLengthCheckManyBlocksOnOneScope.java"), expected); + verify(checkConfig, getPath("InputChildBlockLengthCheckManyBlocksOnOneScope.java"), + expected); } @Test public void testNestedBadChildBlocks() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ChildBlockLengthCheck.class); checkConfig.addAttribute("maxChildBlockPercentage", "70"); checkConfig.addAttribute("blockTypes", "LITERAL_IF, LITERAL_SWITCH, LITERAL_FOR, " + "LITERAL_DO, LITERAL_WHILE, LITERAL_TRY, LITERAL_ELSE, LITERAL_CATCH"); @@ -103,6 +114,7 @@ public void testNestedBadChildBlocks() throws Exception { @Test public void testIgnoreBlockLinesCountOption() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ChildBlockLengthCheck.class); checkConfig.addAttribute("maxChildBlockPercentage", "19"); checkConfig.addAttribute("blockTypes", "LITERAL_IF, LITERAL_SWITCH, LITERAL_FOR, " + "LITERAL_DO, LITERAL_WHILE, LITERAL_TRY, LITERAL_ELSE, LITERAL_CATCH"); @@ -111,11 +123,13 @@ public void testIgnoreBlockLinesCountOption() throws Exception { final String[] expected = { }; - verify(checkConfig, getPath("InputChildBlockLengthCheckManyBlocksOnOneScope.java"), expected); + verify(checkConfig, getPath("InputChildBlockLengthCheckManyBlocksOnOneScope.java"), + expected); } @Test public void testBadChildBlocksThatAreDoubleNested2() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ChildBlockLengthCheck.class); checkConfig.addAttribute("maxChildBlockPercentage", "70"); checkConfig.addAttribute("blockTypes", "LITERAL_IF, LITERAL_SWITCH, LITERAL_FOR, " + "LITERAL_DO, LITERAL_WHILE, LITERAL_TRY, LITERAL_ELSE, LITERAL_CATCH"); @@ -128,6 +142,7 @@ public void testBadChildBlocksThatAreDoubleNested2() throws Exception { @Test public void testNestedClass() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ChildBlockLengthCheck.class); checkConfig.addAttribute("maxChildBlockPercentage", "19"); checkConfig.addAttribute("blockTypes", "LITERAL_IF"); checkConfig.addAttribute("ignoreBlockLinesCount", "0"); @@ -138,4 +153,5 @@ public void testNestedClass() throws Exception { verify(checkConfig, getPath("InputChildBlockLengthCheckNestedClass.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ConstructorWithoutParamsCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ConstructorWithoutParamsCheckTest.java index a18a70371d..bccf77538b 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ConstructorWithoutParamsCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ConstructorWithoutParamsCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,38 +20,44 @@ package com.github.sevntu.checkstyle.checks.design; import static com.github.sevntu.checkstyle.checks.design.ConstructorWithoutParamsCheck.MSG_KEY; +import static org.junit.Assert.assertArrayEquals; -import org.junit.Before; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.TokenTypes; -public class ConstructorWithoutParamsCheckTest extends BaseCheckTestSupport { +public class ConstructorWithoutParamsCheckTest extends AbstractModuleTestSupport { - private DefaultConfiguration defaultConfig; - - @Before - public void getDefaultConfiguration() { - defaultConfig = createCheckConfig(ConstructorWithoutParamsCheck.class); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; } @Test public void testDefaultConfigProhibitsExceptionsWithoutParams() throws Exception { - final String[] expectedViolationMsg = {"30:37: " + getCheckMessage(MSG_KEY, "RuntimeException")}; - verify(defaultConfig, getPath("InputConstructorWithoutParamsCheck.java"), expectedViolationMsg); + final DefaultConfiguration defaultConfig = + createModuleConfig(ConstructorWithoutParamsCheck.class); + final String[] expectedViolationMsg = { + "35:37: " + getCheckMessage(MSG_KEY, "RuntimeException"), + }; + verify(defaultConfig, getPath("InputConstructorWithoutParamsCheck.java"), + expectedViolationMsg); } @Test public void testUserDefinedConfigProhibitsCustomClasses() throws Exception { + final DefaultConfiguration defaultConfig = + createModuleConfig(ConstructorWithoutParamsCheck.class); defaultConfig.addAttribute("classNameFormat", "Clazz[1-9]"); defaultConfig.addAttribute("ignoredClassNameFormat", "Clazz4"); final String[] expectedViolationMsg = { - "64:27: " + getCheckMessage(MSG_KEY, "Clazz1"), - "67:27: " + getCheckMessage(MSG_KEY, "Clazz2"), + "69:27: " + getCheckMessage(MSG_KEY, "Clazz1"), + "72:27: " + getCheckMessage(MSG_KEY, "Clazz2"), }; - verify(defaultConfig, getPath("InputConstructorWithoutParamsCheck.java"), expectedViolationMsg); + verify(defaultConfig, getPath("InputConstructorWithoutParamsCheck.java"), + expectedViolationMsg); } /* diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ForbidWildcardAsReturnTypeCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ForbidWildcardAsReturnTypeCheckTest.java index f8a430b83c..6323c9f955 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ForbidWildcardAsReturnTypeCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/ForbidWildcardAsReturnTypeCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -27,14 +27,16 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; /** * Test class for ForbidWildcardInReturnTypeCheck. * @author Baratali Izmailov */ -public class ForbidWildcardAsReturnTypeCheckTest extends BaseCheckTestSupport { +public class ForbidWildcardAsReturnTypeCheckTest extends AbstractModuleTestSupport { + /** * Line numbers with methods which have wildcard in return type. */ @@ -93,10 +95,6 @@ public class ForbidWildcardAsReturnTypeCheckTest extends BaseCheckTestSupport { */ private static final SortedSet LINES_WITH_IGNORE_CLASS_NAMES = newSetOfLines(new Integer[] {214, 218, 221, }); - /** - * Ignore list for class names. Regexp. - */ - private static final String IGNORE_LIST_PATTERN = "(Compar.+)|Collection"; /** * Message for this check. */ @@ -112,6 +110,11 @@ public ForbidWildcardAsReturnTypeCheckTest() { LINES.addAll(LINES_WITH_PUBLIC_METHODS); } + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } + /** * Main test. * @throws Exception @@ -121,7 +124,7 @@ public ForbidWildcardAsReturnTypeCheckTest() { public final void testDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "true"); checkConfig.addAttribute("checkPrivateMethods", "true"); checkConfig.addAttribute("checkProtectedMethods", "true"); @@ -134,7 +137,7 @@ public final void testDefault() final String[] expected = createExpectedMessages(LINES); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -147,7 +150,7 @@ public final void testDefault() public final void testOnlyPublicMethods() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "true"); checkConfig.addAttribute("checkPrivateMethods", "false"); checkConfig.addAttribute("checkProtectedMethods", "false"); @@ -161,7 +164,7 @@ public final void testOnlyPublicMethods() createExpectedMessages(LINES_WITH_PUBLIC_METHODS); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -174,7 +177,7 @@ public final void testOnlyPublicMethods() public final void testOnlyPrivateMethods() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "false"); checkConfig.addAttribute("checkPrivateMethods", "true"); checkConfig.addAttribute("checkProtectedMethods", "false"); @@ -188,7 +191,7 @@ public final void testOnlyPrivateMethods() createExpectedMessages(LINES_WITH_PRIVATE_METHODS); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -201,7 +204,7 @@ public final void testOnlyPrivateMethods() public final void testOnlyProtectedMethods() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "false"); checkConfig.addAttribute("checkPrivateMethods", "false"); checkConfig.addAttribute("checkProtectedMethods", "true"); @@ -215,7 +218,7 @@ public final void testOnlyProtectedMethods() createExpectedMessages(LINES_WITH_PROTECTED_METHODS); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -228,7 +231,7 @@ public final void testOnlyProtectedMethods() public final void testOnlyPackageMethods() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "false"); checkConfig.addAttribute("checkPrivateMethods", "false"); checkConfig.addAttribute("checkProtectedMethods", "false"); @@ -242,7 +245,7 @@ public final void testOnlyPackageMethods() createExpectedMessages(LINES_WITH_PACKAGE_METHODS); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -255,7 +258,7 @@ public final void testOnlyPackageMethods() public final void testAllowSuper() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "true"); checkConfig.addAttribute("checkPrivateMethods", "true"); checkConfig.addAttribute("checkProtectedMethods", "true"); @@ -271,7 +274,7 @@ public final void testAllowSuper() final String[] expected = createExpectedMessages(exceptSuper); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -284,7 +287,7 @@ public final void testAllowSuper() public final void testAllowExtends() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "true"); checkConfig.addAttribute("checkPrivateMethods", "true"); checkConfig.addAttribute("checkProtectedMethods", "true"); @@ -300,7 +303,7 @@ public final void testAllowExtends() final String[] expected = createExpectedMessages(exceptExtends); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -313,7 +316,7 @@ public final void testAllowExtends() public final void testAllowExtendsAndSuper() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "true"); checkConfig.addAttribute("checkPrivateMethods", "true"); checkConfig.addAttribute("checkProtectedMethods", "true"); @@ -330,7 +333,7 @@ public final void testAllowExtendsAndSuper() final String[] expected = createExpectedMessages(exceptSuperAndExtends); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -343,7 +346,7 @@ public final void testAllowExtendsAndSuper() public final void testWithIgnoreList() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "true"); checkConfig.addAttribute("checkPrivateMethods", "true"); checkConfig.addAttribute("checkProtectedMethods", "true"); @@ -353,14 +356,14 @@ public final void testWithIgnoreList() checkConfig.addAttribute("allowReturnWildcardWithExtends", "false"); checkConfig.addAttribute("allowReturnWildcardWithSuper", "false"); checkConfig.addAttribute("returnTypeClassNamesIgnoreRegex", - IGNORE_LIST_PATTERN); + "(Compar.+)|Collection"); final SortedSet exceptSuperAndExtends = new TreeSet<>(LINES); exceptSuperAndExtends.removeAll(LINES_WITH_IGNORE_CLASS_NAMES); final String[] expected = createExpectedMessages(exceptSuperAndExtends); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -373,7 +376,7 @@ public final void testWithIgnoreList() public final void testAllExceptOverrideMethods() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "true"); checkConfig.addAttribute("checkPrivateMethods", "true"); checkConfig.addAttribute("checkProtectedMethods", "true"); @@ -389,7 +392,7 @@ public final void testAllExceptOverrideMethods() final String[] expected = createExpectedMessages(exceptOverride); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } @@ -402,7 +405,7 @@ public final void testAllExceptOverrideMethods() public final void testAllExceptDeprecatedMethods() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(ForbidWildcardAsReturnTypeCheck.class); + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); checkConfig.addAttribute("checkPublicMethods", "true"); checkConfig.addAttribute("checkPrivateMethods", "true"); checkConfig.addAttribute("checkProtectedMethods", "true"); @@ -418,10 +421,21 @@ public final void testAllExceptDeprecatedMethods() final String[] expected = createExpectedMessages(exceptOverride); verify(checkConfig, - getPath("InputForbidWildcardAsReturnType.java"), + getPath("InputForbidWildcardAsReturnTypeCheck.java"), expected); } + @Test + public final void testFullyQualifiedAnnotation() + throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ForbidWildcardAsReturnTypeCheck.class); + + verify(checkConfig, + getPath("InputForbidWildcardAsReturnTypeCheckQualifiedAnnotation.java"), + CommonUtils.EMPTY_STRING_ARRAY); + } + /** * Create new set of line numbers. * @param aLines @@ -429,7 +443,7 @@ public final void testAllExceptDeprecatedMethods() * @return sorted set of line numbers. */ private static SortedSet newSetOfLines(Integer[] aLines) { - return new TreeSet(Arrays.asList(aLines)); + return new TreeSet<>(Arrays.asList(aLines)); } /** @@ -441,9 +455,26 @@ private String[] createExpectedMessages(SortedSet aLines) { final String[] expected = new String[aLines.size()]; int index = 0; for (Integer element : aLines) { - expected[index] = element + ": " + warningMessage; + expected[index] = element + ":" + getColumnNumber(element) + ": " + warningMessage; index++; } return expected; } + + private static int getColumnNumber(int lineNumber) { + final int result; + + if (lineNumber >= 264 && lineNumber < 280) { + result = 13; + } + else if (lineNumber < 228 || lineNumber >= 280 && lineNumber < 290 || lineNumber >= 304) { + result = 5; + } + else { + result = 9; + } + + return result; + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/HideUtilityClassConstructorCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/HideUtilityClassConstructorCheckTest.java index b893d03721..5a9a0a0c6f 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/HideUtilityClassConstructorCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/HideUtilityClassConstructorCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,75 +23,80 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class HideUtilityClassConstructorCheckTest - extends BaseCheckTestSupport { +public class HideUtilityClassConstructorCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } + /** Only static methods and no constructor - default ctor is visible */ @Test public void testUtilClass() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(HideUtilityClassConstructorCheck.class); + createModuleConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { "11:1: " + getCheckMessage(MSG_KEY), }; - verify(checkConfig, getPath("InputArrayTypeStyle.java"), expected); + verify(checkConfig, getPath("InputHideUtilityClassConstructorCheck.java"), expected); } /** Non static methods - always OK */ @Test public void testNonUtilClass() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(HideUtilityClassConstructorCheck.class); + createModuleConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; - verify(checkConfig, getPath("InputDesignForExtension.java"), expected); + verify(checkConfig, getPath("InputHideUtilityClassConstructorCheck4.java"), expected); } @Test public void testDerivedNonUtilClass() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(HideUtilityClassConstructorCheck.class); + createModuleConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; - verify(checkConfig, getPath("InputNonUtilityClass.java"), expected); + verify(checkConfig, getPath("InputHideUtilityClassConstructorCheck5.java"), expected); } @Test public void testOnlyNonstaticFieldNonUtilClass() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(HideUtilityClassConstructorCheck.class); + createModuleConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; - verify(checkConfig, getPath("InputRegression.java"), expected); + verify(checkConfig, getPath("InputHideUtilityClassConstructorCheck6.java"), expected); } @Test public void testEmptyAbstractClass() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(HideUtilityClassConstructorCheck.class); + createModuleConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; - verify(checkConfig, getPath("InputHideUtilityClassContructor1.java"), expected); + verify(checkConfig, getPath("InputHideUtilityClassConstructorCheck1.java"), expected); } @Test public void testEmptyClassWithOnlyPrivateFields() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(HideUtilityClassConstructorCheck.class); + createModuleConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; - verify(checkConfig, getPath("InputHideUtilityClassContructor2.java"), expected); + verify(checkConfig, getPath("InputHideUtilityClassConstructorCheck2.java"), expected); } @Test public void testClassWithStaticInnerClass() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(HideUtilityClassConstructorCheck.class); + createModuleConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; - verify(checkConfig, getPath("InputHideUtilityClassContructor3.java"), expected); + verify(checkConfig, getPath("InputHideUtilityClassConstructorCheck3.java"), expected); } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/InnerClassCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/InnerClassCheckTest.java index 23b6f34084..08ed1b0e00 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/InnerClassCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/InnerClassCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,17 +23,22 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class InnerClassCheckTest extends BaseCheckTestSupport { +public class InnerClassCheckTest extends AbstractModuleTestSupport { private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } + @Test public void testMembersBeforeInner() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(InnerClassCheck.class); + createModuleConfig(InnerClassCheck.class); final String[] expected = { "15:17: " + warningMessage, "25:17: " + warningMessage, @@ -49,4 +54,5 @@ public void testMembersBeforeInner() throws Exception { }; verify(checkConfig, getPath("InputInnerClassCheck.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/NestedSwitchCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/NestedSwitchCheckTest.java index 1b665610d8..4820a1cb06 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/NestedSwitchCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/NestedSwitchCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,17 +23,23 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; /** * @author Damian Szczepanik (damianszczepanik@github) */ -public class NestedSwitchCheckTest extends BaseCheckTestSupport { - private final DefaultConfiguration checkConfig = createCheckConfig(NestedSwitchCheck.class); +public class NestedSwitchCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } @Test public void testSimple() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(NestedSwitchCheck.class); final String[] expected = { "11:13: " + getCheckMessage(MSG_KEY), "23:13: " + getCheckMessage(MSG_KEY), @@ -49,4 +55,15 @@ public void testSimple() throws Exception { verify(checkConfig, getPath("InputNestedSwitchCheck.java"), expected); } + + @Test + public void testMax() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(NestedSwitchCheck.class); + checkConfig.addAttribute("max", "99"); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + + verify(checkConfig, getPath("InputNestedSwitchCheck.java"), + expected); + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/NoMainMethodInAbstractClassCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/NoMainMethodInAbstractClassCheckTest.java index 0478a8f297..bd972d15fd 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/NoMainMethodInAbstractClassCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/NoMainMethodInAbstractClassCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -23,14 +23,15 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; /** * Test class for NoMainMethodInAbstractClass check. * @author Baratali Izmailov */ -public class NoMainMethodInAbstractClassCheckTest extends BaseCheckTestSupport { +public class NoMainMethodInAbstractClassCheckTest extends AbstractModuleTestSupport { + /** * Name of file with messages. */ @@ -40,6 +41,11 @@ public class NoMainMethodInAbstractClassCheckTest extends BaseCheckTestSupport { */ private final String warningMessage = getCheckMessage(MSG_KEY); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } + /** * Main test. * @throws Exception @@ -49,35 +55,36 @@ public class NoMainMethodInAbstractClassCheckTest extends BaseCheckTestSupport { public final void testDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(NoMainMethodInAbstractClassCheck.class); + createModuleConfig(NoMainMethodInAbstractClassCheck.class); final String[] expected = { - "23: " + warningMessage, - "26: " + warningMessage, - "34: " + warningMessage, - "37: " + warningMessage, - "51: " + warningMessage, - "53: " + warningMessage, - "57: " + warningMessage, - "59: " + warningMessage, - "100: " + warningMessage, - "103: " + warningMessage, - "106: " + warningMessage, - "109: " + warningMessage, - "116: " + warningMessage, - "119: " + warningMessage, - "122: " + warningMessage, - "125: " + warningMessage, - "130: " + warningMessage, - "136: " + warningMessage, - "151: " + warningMessage, - "155: " + warningMessage, - "166: " + warningMessage, - "175: " + warningMessage, - "185: " + warningMessage, + "23:5: " + warningMessage, + "26:5: " + warningMessage, + "34:9: " + warningMessage, + "37:9: " + warningMessage, + "51:5: " + warningMessage, + "53:9: " + warningMessage, + "57:5: " + warningMessage, + "59:9: " + warningMessage, + "100:5: " + warningMessage, + "103:5: " + warningMessage, + "106:5: " + warningMessage, + "109:5: " + warningMessage, + "116:5: " + warningMessage, + "119:5: " + warningMessage, + "122:5: " + warningMessage, + "125:5: " + warningMessage, + "130:5: " + warningMessage, + "136:5: " + warningMessage, + "151:8: " + warningMessage, + "155:4: " + warningMessage, + "166:9: " + warningMessage, + "175:9: " + warningMessage, + "185:9: " + warningMessage, }; verify(checkConfig, getPath("InputNoMainMethodInAbstractClassCheck.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/PublicReferenceToPrivateTypeCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/PublicReferenceToPrivateTypeCheckTest.java index 2b1b7045d9..e864b57fc4 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/PublicReferenceToPrivateTypeCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/PublicReferenceToPrivateTypeCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,17 +20,26 @@ package com.github.sevntu.checkstyle.checks.design; import static com.github.sevntu.checkstyle.checks.design.PublicReferenceToPrivateTypeCheck.MSG_KEY; +import static org.junit.Assert.fail; +import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * @author Aleksey Nesterenko */ -public class PublicReferenceToPrivateTypeCheckTest extends - BaseCheckTestSupport { +public class PublicReferenceToPrivateTypeCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } + /** * Test file without method return instance of private class. * @throws Exception @@ -40,7 +49,7 @@ public class PublicReferenceToPrivateTypeCheckTest extends public void noReturnProblemsTest() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = {}; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck1.java"), @@ -57,8 +66,8 @@ public void returnPrivateTest() throws Exception { final String typeName = "PrivateInner"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); - final String[] expected = {"13: " + getCheckMessage(MSG_KEY, typeName), }; + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); + final String[] expected = {"13:12: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck2.java"), expected); @@ -71,10 +80,10 @@ public void returnPrivateTest() * exceptions while verify() */ @Test - public void returnPrivateThatImplimentTest() + public void returnPrivateThatImplementTest() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = {}; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck4.java"), @@ -91,7 +100,7 @@ public void returnPrivateThatImplimentTest() public void returnPrivateThatExtendsTest() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = {}; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck3.java"), @@ -108,8 +117,8 @@ public void returnPrivateArrayTest() throws Exception { final String typeName = "PrivateInner"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); - final String[] expected = {"13: " + getCheckMessage(MSG_KEY, typeName), }; + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); + final String[] expected = {"13:12: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck5.java"), expected); @@ -125,8 +134,8 @@ public void returnPrivateInShell() throws Exception { final String typeName = "PrivateInner"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); - final String[] expected = {"14: " + getCheckMessage(MSG_KEY, typeName), }; + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); + final String[] expected = {"14:16: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck6.java"), expected); @@ -143,8 +152,8 @@ public void returnPrivateInCollectionInCollection() throws Exception { final String typeName = "PrivateInner"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); - final String[] expected = {"14: " + getCheckMessage(MSG_KEY, typeName), }; + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); + final String[] expected = {"14:24: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck7.java"), expected); @@ -161,8 +170,8 @@ public void returnPrivateInMapInCollectionInCollection() throws Exception { final String typeName = "PrivateInner"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); - final String[] expected = {"14: " + getCheckMessage(MSG_KEY, typeName), }; + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); + final String[] expected = {"14:40: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck9.java"), expected); @@ -180,10 +189,10 @@ public void complexTest() final String typeName = "PrivateInner"; final String typeName1 = "OutClass"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "25: " + getCheckMessage(MSG_KEY, typeName), - "28: " + getCheckMessage(MSG_KEY, typeName1), + "25:40: " + getCheckMessage(MSG_KEY, typeName), + "28:12: " + getCheckMessage(MSG_KEY, typeName1), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck8.java"), @@ -201,11 +210,11 @@ public void methodModifiersTest() throws Exception { final String typeName = "PrivateInner"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "14: " + getCheckMessage(MSG_KEY, typeName), - "20: " + getCheckMessage(MSG_KEY, typeName), - "23: " + getCheckMessage(MSG_KEY, typeName), + "14:40: " + getCheckMessage(MSG_KEY, typeName), + "20:43: " + getCheckMessage(MSG_KEY, typeName), + "23:33: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck10.java"), @@ -222,11 +231,11 @@ public void wildcardsTest() throws Exception { final String typeName = "PrivateInner"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "14: " + getCheckMessage(MSG_KEY, typeName), - "20: " + getCheckMessage(MSG_KEY, typeName), - "23: " + getCheckMessage(MSG_KEY, typeName), + "14:24: " + getCheckMessage(MSG_KEY, typeName), + "20:29: " + getCheckMessage(MSG_KEY, typeName), + "23:33: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck11.java"), @@ -238,10 +247,10 @@ public void interfacesTest() throws Exception { final String typeName = "PrivateInner"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "13: " + getCheckMessage(MSG_KEY, typeName), - "19: " + getCheckMessage(MSG_KEY, typeName), + "13:24: " + getCheckMessage(MSG_KEY, typeName), + "19:16: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck12.java"), @@ -253,10 +262,10 @@ public void enumsTest() throws Exception { final String typeName = "First"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "8: " + getCheckMessage(MSG_KEY, typeName), - "10: " + getCheckMessage(MSG_KEY, typeName), + "8:5: " + getCheckMessage(MSG_KEY, typeName), + "10:15: " + getCheckMessage(MSG_KEY, typeName), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck13.java"), @@ -270,13 +279,13 @@ public void testClassEnumInterface() final String typeName1 = "PrivateInner1"; final String typeName2 = "First"; final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "15: " + getCheckMessage(MSG_KEY, typeName), - "25: " + getCheckMessage(MSG_KEY, typeName1), - "31: " + getCheckMessage(MSG_KEY, typeName1), - "35: " + getCheckMessage(MSG_KEY, typeName2), - "37: " + getCheckMessage(MSG_KEY, typeName2), + "15:12: " + getCheckMessage(MSG_KEY, typeName), + "25:24: " + getCheckMessage(MSG_KEY, typeName1), + "31:16: " + getCheckMessage(MSG_KEY, typeName1), + "35:5: " + getCheckMessage(MSG_KEY, typeName2), + "37:15: " + getCheckMessage(MSG_KEY, typeName2), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck14.java"), @@ -287,14 +296,14 @@ public void testClassEnumInterface() public void returnFromInnerTypeTest() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "4: " + getCheckMessage(MSG_KEY, "Inner"), - "4: " + getCheckMessage(MSG_KEY, "Inner1"), - "9: " + getCheckMessage(MSG_KEY, "Inner"), - "9: " + getCheckMessage(MSG_KEY, "Inner2"), - "9: " + getCheckMessage(MSG_KEY, "Inner3"), - "14: " + getCheckMessage(MSG_KEY, "Inner"), + "4:12: " + getCheckMessage(MSG_KEY, "Inner"), + "4:18: " + getCheckMessage(MSG_KEY, "Inner1"), + "9:12: " + getCheckMessage(MSG_KEY, "Inner"), + "9:18: " + getCheckMessage(MSG_KEY, "Inner2"), + "9:25: " + getCheckMessage(MSG_KEY, "Inner3"), + "14:12: " + getCheckMessage(MSG_KEY, "Inner"), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck15.java"), @@ -305,11 +314,11 @@ public void returnFromInnerTypeTest() public void returnFromInnerAnonymousClassTest() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "4: " + getCheckMessage(MSG_KEY, "Inner"), - "4: " + getCheckMessage(MSG_KEY, "Inner2"), - "4: " + getCheckMessage(MSG_KEY, "Inner3"), + "4:12: " + getCheckMessage(MSG_KEY, "Inner"), + "4:18: " + getCheckMessage(MSG_KEY, "Inner2"), + "4:25: " + getCheckMessage(MSG_KEY, "Inner3"), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck16.java"), @@ -320,10 +329,10 @@ public void returnFromInnerAnonymousClassTest() public void returnFromPublicFieldTest() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "4: " + getCheckMessage(MSG_KEY, "Inner"), - "9: " + getCheckMessage(MSG_KEY, "Inner1"), + "4:12: " + getCheckMessage(MSG_KEY, "Inner"), + "9:12: " + getCheckMessage(MSG_KEY, "Inner1"), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck17.java"), @@ -334,9 +343,9 @@ public void returnFromPublicFieldTest() public void implementingOrExtendingPrivateTypeTest() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "17: " + getCheckMessage(MSG_KEY, "InnerClass"), + "17:12: " + getCheckMessage(MSG_KEY, "InnerClass"), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck18.java"), @@ -347,15 +356,44 @@ public void implementingOrExtendingPrivateTypeTest() public void usingPrivateTypeAsMethodParameterTest() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(PublicReferenceToPrivateTypeCheck.class); + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); final String[] expected = { - "4: " + getCheckMessage(MSG_KEY, "C1"), - "6: " + getCheckMessage(MSG_KEY, "C1"), - "8: " + getCheckMessage(MSG_KEY, "C1"), + "4:31: " + getCheckMessage(MSG_KEY, "C1"), + "6:23: " + getCheckMessage(MSG_KEY, "C1"), + "8:43: " + getCheckMessage(MSG_KEY, "C1"), }; verify(checkConfig, getPath("InputPublicReferenceToPrivateTypeCheck19.java"), expected); } + @Test + public void testNestedInnerClass() + throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(PublicReferenceToPrivateTypeCheck.class); + final String[] expected = { + "7:18: " + getCheckMessage(MSG_KEY, "ConcurrentWeakInternSet"), + }; + verify(checkConfig, + getPath("InputPublicReferenceToPrivateTypeCheck20.java"), + expected); + } + + @Test + public void testUnsupportedNode() { + final DetailAST sync = new DetailAST(); + sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); + + try { + final PublicReferenceToPrivateTypeCheck check = new PublicReferenceToPrivateTypeCheck(); + check.visitToken(sync); + + fail(); + } + catch (IllegalArgumentException ex) { + Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); + } + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/StaticMethodCandidateCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/StaticMethodCandidateCheckTest.java index 07b387fb3b..cea4552fe4 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/StaticMethodCandidateCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/design/StaticMethodCandidateCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,44 +20,51 @@ package com.github.sevntu.checkstyle.checks.design; import static com.github.sevntu.checkstyle.checks.design.StaticMethodCandidateCheck.MSG_KEY; +import static org.junit.Assert.assertArrayEquals; import java.io.File; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.TokenTypes; -public class StaticMethodCandidateCheckTest extends BaseCheckTestSupport { +public class StaticMethodCandidateCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/design"; + } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(StaticMethodCandidateCheck.class); + createModuleConfig(StaticMethodCandidateCheck.class); final String[] expected = { - "37: " + getCheckMessage(MSG_KEY, "foo11"), - "56: " + getCheckMessage(MSG_KEY, "nestedFoo1"), - "86: " + getCheckMessage(MSG_KEY, "doSomething"), - "123: " + getCheckMessage(MSG_KEY, "main"), - "176: " + getCheckMessage(MSG_KEY, "bar"), - "184: " + getCheckMessage(MSG_KEY, "fooBar"), - "186: " + getCheckMessage(MSG_KEY, "barFoo"), - "188: " + getCheckMessage(MSG_KEY, "fooo"), - "190: " + getCheckMessage(MSG_KEY, "baar"), - "192: " + getCheckMessage(MSG_KEY, "fOo"), - "194: " + getCheckMessage(MSG_KEY, "foO"), + "37:5: " + getCheckMessage(MSG_KEY, "foo11"), + "56:9: " + getCheckMessage(MSG_KEY, "nestedFoo1"), + "86:9: " + getCheckMessage(MSG_KEY, "doSomething"), + "123:5: " + getCheckMessage(MSG_KEY, "main"), + "176:5: " + getCheckMessage(MSG_KEY, "bar"), + "184:5: " + getCheckMessage(MSG_KEY, "fooBar"), + "186:5: " + getCheckMessage(MSG_KEY, "barFoo"), + "188:5: " + getCheckMessage(MSG_KEY, "fooo"), + "190:5: " + getCheckMessage(MSG_KEY, "baar"), + "192:5: " + getCheckMessage(MSG_KEY, "fOo"), + "194:5: " + getCheckMessage(MSG_KEY, "foO"), }; - verify(checkConfig, getPath("InputStaticMethodCandidate.java"), expected); + verify(checkConfig, getPath("InputStaticMethodCandidateCheck.java"), expected); } @Test public void testSkippedMethods() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(StaticMethodCandidateCheck.class); + createModuleConfig(StaticMethodCandidateCheck.class); checkConfig.addAttribute("skippedMethods", "foo, bar,foobar"); final String[] expected = {}; - verify(checkConfig, getPath("InputStaticMethodCandidateSkippedMethods.java"), expected); + verify(checkConfig, getPath("InputStaticMethodCandidateCheckSkippedMethods.java"), + expected); } @Test @@ -125,22 +132,23 @@ public void testGetRequiredTokens() { @Test public void testLambda() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(StaticMethodCandidateCheck.class); + createModuleConfig(StaticMethodCandidateCheck.class); final String[] expected = { }; verify(checkConfig, "src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/" - + "design/InputStaticMethodCandidateLambda.java", expected); + + "design/InputStaticMethodCandidateCheckLambda.java", expected); } @Test public void testInterface() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(StaticMethodCandidateCheck.class); + createModuleConfig(StaticMethodCandidateCheck.class); final String[] expected = { - "16: " + getCheckMessage(MSG_KEY, "bar"), + "16:5: " + getCheckMessage(MSG_KEY, "bar"), }; verify(checkConfig, new File("src/test/resources-noncompilable/com/github/" - + "sevntu/checkstyle/checks/design/InputStaticMethodCandidateInterfaceMethod.java") + + "sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckInterfaceMethod.java") .getCanonicalPath(), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/EnumValueNameCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/EnumValueNameCheckTest.java index 6cb8c847df..aa374858ad 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/EnumValueNameCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/EnumValueNameCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,192 +19,53 @@ package com.github.sevntu.checkstyle.checks.naming; -import java.text.MessageFormat; +import static com.github.sevntu.checkstyle.checks.naming.EnumValueNameCheck.DEFAULT_PATTERN; +import static com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck.MSG_INVALID_PATTERN; -import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -/** - * Test unit for - * {@link EnumValueNameCheck}. - * @author Pavel Baranchikov - */ -public class EnumValueNameCheckTest extends BaseCheckTestSupport { - private final String msgObj = getCheckMessage(EnumValueNameCheck.MSG_OBJ); - private final String msgConst = getCheckMessage(EnumValueNameCheck.MSG_CONST); - private final String inputFile; +public class EnumValueNameCheckTest extends AbstractModuleTestSupport { - public EnumValueNameCheckTest() { - inputFile = getPath("InputEnumValueNameCheck.java"); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/naming"; } - /** - * Tests for a default naming pattern. - * - * @throws Exception - * on some errors during verification. - */ @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(EnumValueNameCheck.class); - final MessageContext constContext = new MessageContext(false, - EnumValueNameCheck.DEFAULT_CONST_PATTERN); - final MessageContext objContext = new MessageContext(true, - EnumValueNameCheck.DEFAULT_OBJ_PATTERN); + createModuleConfig(EnumValueNameCheck.class); final String[] expected = { - buildMessage(35, 9, "FirstSimple", constContext), - buildMessage(43, 26, "SECOND_COMPLEX", objContext), - buildMessage(66, 19, "MoSecond", constContext), - buildMessage(76, 9, "FO_FIRST", objContext), + "35:9: " + getCheckMessage(MSG_INVALID_PATTERN, "FirstSimple", DEFAULT_PATTERN), + "43:9: " + getCheckMessage(MSG_INVALID_PATTERN, "FirstComplex", DEFAULT_PATTERN), + "66:19: " + getCheckMessage(MSG_INVALID_PATTERN, "MoSecond", DEFAULT_PATTERN), + "76:19: " + getCheckMessage(MSG_INVALID_PATTERN, "FoSecond", DEFAULT_PATTERN), }; - verify(checkConfig, inputFile, expected); + verify(checkConfig, getPath("InputEnumValueNameCheck.java"), expected); } - /** - * Tests for a default naming pattern with exclusion of "some*" member - * names. - * - * @throws Exception - * on some errors during verification. - */ @Test - public void testExcludes() + public void testCustomFormat() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(EnumValueNameCheck.class); - final MessageContext constContext = new MessageContext(false, - EnumValueNameCheck.DEFAULT_CONST_PATTERN); - final MessageContext objContext = new MessageContext(true, - EnumValueNameCheck.DEFAULT_OBJ_PATTERN); - checkConfig.addAttribute("excludes", "some*"); - final String[] expected = { - buildMessage(35, 9, "FirstSimple", constContext), - buildMessage(43, 26, "SECOND_COMPLEX", objContext), - buildMessage(66, 9, "MO_FIRST", objContext), - buildMessage(76, 19, "FoSecond", constContext), - }; - verify(checkConfig, inputFile, expected); - } - - /** - * Tests for wrong formatter string. - * - * @throws Exception - * on some errors during verification. - */ - @Test - public void testInvalidFormat() - throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(EnumValueNameCheck.class); - checkConfig.addAttribute("constFormat", "\\"); - final String[] expected = {}; - try { - verify(checkConfig, inputFile, expected); - fail(); - } - catch (CheckstyleException ex) { - Assert.assertTrue(ex.getMessage().startsWith("cannot initialize module " - + "com.puppycrawl.tools.checkstyle.TreeWalker - " - + "Cannot set property 'constFormat' to '\\' in module ")); - } - } - - /** - * Tests for upset naming - Values Enumeration in camel notation while Class - * Enumeration - in upper-case notation. - * - * @throws Exception - * on some errors during verification. - */ - @Test - public void testUpset() - throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(EnumValueNameCheck.class); - final MessageContext constContext = new MessageContext(false, - EnumValueNameCheck.DEFAULT_OBJ_PATTERN); - final MessageContext objContext = new MessageContext(true, - EnumValueNameCheck.DEFAULT_CONST_PATTERN); - - checkConfig.addAttribute("constFormat", constContext.getPattern()); - checkConfig.addAttribute("objFormat", objContext.getPattern()); - - final String[] expected = { - buildMessage(35, 22, "SECOND_SIMPLE", constContext), - buildMessage(43, 9, "FirstComplex", objContext), - buildMessage(66, 9, "MO_FIRST", constContext), - buildMessage(76, 19, "FoSecond", objContext), - }; - verify(checkConfig, inputFile, expected); - } + createModuleConfig(EnumValueNameCheck.class); - /** - * Tests equal values for constants and static final object references. - * - * @throws Exception - * on some errors during verification. - */ - @Test - public void testEqualRegexps() - throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(EnumValueNameCheck.class); - final MessageContext constContext = new MessageContext(false, - EnumValueNameCheck.DEFAULT_CONST_PATTERN); - final MessageContext objContext = new MessageContext(true, - EnumValueNameCheck.DEFAULT_CONST_PATTERN); - checkConfig.addAttribute("constFormat", constContext.getPattern()); - checkConfig.addAttribute("objFormat", objContext.getPattern()); + checkConfig.addAttribute("format", "[a-z]+"); final String[] expected = { - buildMessage(35, 9, "FirstSimple", constContext), - buildMessage(43, 9, "FirstComplex", objContext), - buildMessage(66, 19, "MoSecond", constContext), - buildMessage(76, 19, "FoSecond", objContext), + "35:22: " + getCheckMessage(MSG_INVALID_PATTERN, "SECOND_SIMPLE", "[a-z]+"), + "35:37: " + getCheckMessage(MSG_INVALID_PATTERN, "DB2", "[a-z]+"), + "35:42: " + getCheckMessage(MSG_INVALID_PATTERN, "V1", "[a-z]+"), + "43:26: " + getCheckMessage(MSG_INVALID_PATTERN, "SECOND_COMPLEX", "[a-z]+"), + "43:45: " + getCheckMessage(MSG_INVALID_PATTERN, "V2", "[a-z]+"), + "66:9: " + getCheckMessage(MSG_INVALID_PATTERN, "MO_FIRST", "[a-z]+"), + "76:9: " + getCheckMessage(MSG_INVALID_PATTERN, "FO_FIRST", "[a-z]+"), }; - verify(checkConfig, inputFile, expected); - } - - private String buildMessage(int lineNumber, int colNumber, - String constName, MessageContext context) { - final String msg; - if (context.isEnumObj()) { - msg = msgObj; - } - else { - msg = msgConst; - } - return lineNumber + ":" + colNumber + ": " - + MessageFormat.format(msg, constName, context.getPattern()); - } - - /** - * Class containing pattern and is-object flag. - */ - private static final class MessageContext { - private final boolean enumObj; - private final String pattern; - - private MessageContext(boolean enumIsObj, String pattern) { - this.enumObj = enumIsObj; - this.pattern = pattern; - } - - public boolean isEnumObj() { - return enumObj; - } - - public String getPattern() { - return pattern; - } - + verify(checkConfig, getPath("InputEnumValueNameCheck.java"), expected); } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/TypeParameterNameTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/InterfaceTypeParameterNameCheckTest.java similarity index 76% rename from sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/TypeParameterNameTest.java rename to sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/InterfaceTypeParameterNameCheckTest.java index 0533db1c66..05e75f2c81 100755 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/TypeParameterNameTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/InterfaceTypeParameterNameCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -21,41 +21,47 @@ import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -public class TypeParameterNameTest - extends BaseCheckTestSupport { +public class InterfaceTypeParameterNameCheckTest extends AbstractModuleTestSupport { + /** Warning message key. */ private static final String MSG_KEY = "name.invalidPattern"; + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/naming"; + } + @Test public void testInterfaceDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(InterfaceTypeParameterNameCheck.class); + createModuleConfig(InterfaceTypeParameterNameCheck.class); final String[] expected = { - "5:51: " + getCheckMessage(MSG_KEY, "it", "^[A-Z]$"), + "5:56: " + getCheckMessage(MSG_KEY, "it", "^[A-Z]$"), "9:27: " + getCheckMessage(MSG_KEY, "foo", "^[A-Z]$"), "18:34: " + getCheckMessage(MSG_KEY, "Taa", "^[A-Z]$"), "18:52: " + getCheckMessage(MSG_KEY, "Vaa", "^[A-Z]$"), }; - verify(checkConfig, getPath("InputInterfaceTypeParameterName.java"), expected); + verify(checkConfig, getPath("InputInterfaceTypeParameterNameCheck.java"), expected); } @Test public void testInterfaceFooName() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(InterfaceTypeParameterNameCheck.class); + createModuleConfig(InterfaceTypeParameterNameCheck.class); checkConfig.addAttribute("format", "^foo$"); final String[] expected = { - "5:51: " + getCheckMessage(MSG_KEY, "it", "^foo$"), + "5:56: " + getCheckMessage(MSG_KEY, "it", "^foo$"), "13:27: " + getCheckMessage(MSG_KEY, "A", "^foo$"), "18:34: " + getCheckMessage(MSG_KEY, "Taa", "^foo$"), "18:52: " + getCheckMessage(MSG_KEY, "Vaa", "^foo$"), }; - verify(checkConfig, getPath("InputInterfaceTypeParameterName.java"), expected); + verify(checkConfig, getPath("InputInterfaceTypeParameterNameCheck.java"), expected); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/UniformEnumConstantNameCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/UniformEnumConstantNameCheckTest.java index 3ac421e3a6..ab56dad649 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/UniformEnumConstantNameCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/naming/UniformEnumConstantNameCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,12 +19,14 @@ package com.github.sevntu.checkstyle.checks.naming; +import static org.junit.Assert.fail; + import java.util.Arrays; import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; @@ -33,11 +35,11 @@ * * @author Pavel Baranchikov */ -public class UniformEnumConstantNameCheckTest extends BaseCheckTestSupport { - private final String inputFile; +public class UniformEnumConstantNameCheckTest extends AbstractModuleTestSupport { - public UniformEnumConstantNameCheckTest() { - inputFile = getPath("InputUniformEnumConstantNameCheck.java"); + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/naming"; } /** @@ -50,7 +52,7 @@ public UniformEnumConstantNameCheckTest() { public void testDefault() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(UniformEnumConstantNameCheck.class); + createModuleConfig(UniformEnumConstantNameCheck.class); final String[] expected = { buildMessage(37, 9, "SECOND_SIMPLE", UniformEnumConstantNameCheck.CAMEL_PATTERN), @@ -59,7 +61,7 @@ public void testDefault() buildMessage(90, 9, "WF_First", UniformEnumConstantNameCheck.DEFAULT_PATTERN), }; - verify(checkConfig, inputFile, expected); + verify(checkConfig, getPath("InputUniformEnumConstantNameCheck.java"), expected); } /** @@ -72,20 +74,20 @@ public void testDefault() public void testUpperCase() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(UniformEnumConstantNameCheck.class); + createModuleConfig(UniformEnumConstantNameCheck.class); checkConfig.addAttribute("formats", - UniformEnumConstantNameCheck.UPPERCASE_PATTERN); + "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"); final String[] expected = { buildMessage(35, 9, "FirstSimple", - UniformEnumConstantNameCheck.UPPERCASE_PATTERN), + "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"), buildMessage(48, 9, "SecondComplex", - UniformEnumConstantNameCheck.UPPERCASE_PATTERN), + "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"), buildMessage(82, 9, "CcFirst", - UniformEnumConstantNameCheck.UPPERCASE_PATTERN), + "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"), buildMessage(90, 9, "WF_First", - UniformEnumConstantNameCheck.UPPERCASE_PATTERN), + "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"), }; - verify(checkConfig, inputFile, expected); + verify(checkConfig, getPath("InputUniformEnumConstantNameCheck.java"), expected); } /** @@ -98,11 +100,11 @@ public void testUpperCase() public void testAllAfterUpper() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(UniformEnumConstantNameCheck.class); + createModuleConfig(UniformEnumConstantNameCheck.class); checkConfig.addAttribute("formats", - UniformEnumConstantNameCheck.UPPERCASE_PATTERN + ",.*"); + "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$" + ",.*"); final String[] expected = {}; - verify(checkConfig, inputFile, expected); + verify(checkConfig, getPath("InputUniformEnumConstantNameCheck.java"), expected); } /** @@ -115,17 +117,19 @@ public void testAllAfterUpper() public void testInvalidFormat() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(UniformEnumConstantNameCheck.class); + createModuleConfig(UniformEnumConstantNameCheck.class); checkConfig.addAttribute("formats", "\\"); final String[] expected = {}; try { - verify(checkConfig, inputFile, expected); + verify(checkConfig, getPath("InputUniformEnumConstantNameCheck.java"), expected); fail(); } catch (CheckstyleException ex) { - Assert.assertTrue(ex.getMessage().startsWith("cannot initialize module " - + "com.puppycrawl.tools.checkstyle.TreeWalker - " - + "Cannot set property 'formats' to '\\' in module ")); + final String messagePrefix = "cannot initialize module " + + "com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'formats' to '\\' in module "; + Assert.assertTrue("Exception's message does not start with: " + messagePrefix, + ex.getMessage().startsWith(messagePrefix)); } } @@ -139,18 +143,20 @@ public void testInvalidFormat() public void testWrongToken() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(UniformEnumConstantNameCheck.class); + createModuleConfig(UniformEnumConstantNameCheck.class); checkConfig.addAttribute("tokens", "INTERFACE_DEF"); final String[] expected = {}; try { - verify(checkConfig, inputFile, expected); + verify(checkConfig, getPath("InputUniformEnumConstantNameCheck.java"), expected); fail(); } catch (CheckstyleException ex) { - Assert.assertTrue(ex.getMessage().startsWith("cannot initialize module " - + "com.puppycrawl.tools.checkstyle.TreeWalker - " - + "Token \"INTERFACE_DEF\" was not found in " - + "Acceptable tokens list in check ")); + final String messagePrefix = "cannot initialize module " + + "com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Token \"INTERFACE_DEF\" was not found in " + + "Acceptable tokens list in check "; + Assert.assertTrue("Exception's message does not start with: " + messagePrefix, + ex.getMessage().startsWith(messagePrefix)); } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthCheckTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthExtendedCheckTest.java similarity index 65% rename from sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthCheckTest.java rename to sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthExtendedCheckTest.java index 4d4d8b3ae7..f771cce1ef 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthCheckTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/checks/sizes/LineLengthExtendedCheckTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,32 +20,41 @@ package com.github.sevntu.checkstyle.checks.sizes; import static com.github.sevntu.checkstyle.checks.sizes.LineLengthExtendedCheck.MSG_KEY; +import static org.junit.Assert.fail; +import org.junit.Assert; import org.junit.Test; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; + +public class LineLengthExtendedCheckTest extends AbstractModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/github/sevntu/checkstyle/checks/sizes"; + } -public class LineLengthCheckTest extends BaseCheckTestSupport { @Test public void testSimple() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(LineLengthExtendedCheck.class); + createModuleConfig(LineLengthExtendedCheck.class); checkConfig.addAttribute("max", "80"); checkConfig.addAttribute("ignorePattern", "^.*is OK.*regexp.*$"); final String[] expected = { "18: " + getCheckMessage(MSG_KEY, 80, 81), "145: " + getCheckMessage(MSG_KEY, 80, 83), }; - verify(checkConfig, getPath("InputSimple.java"), expected); + verify(checkConfig, getPath("InputLineLengthExtendedCheck.java"), expected); } @Test public void testSimpleIgnore() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(LineLengthExtendedCheck.class); + createModuleConfig(LineLengthExtendedCheck.class); checkConfig.addAttribute("max", "40"); checkConfig.addAttribute("ignorePattern", "^.*is OK.*regexp.*$"); final String[] expected = { @@ -70,6 +79,29 @@ public void testSimpleIgnore() checkConfig.addAttribute("ignoreConstructor", "true"); checkConfig.addAttribute("ignoreField", "true"); checkConfig.addAttribute("ignoreMethod", "true"); - verify(checkConfig, getPath("InputSimple.java"), expected); + verify(checkConfig, getPath("InputLineLengthExtendedCheck.java"), expected); } + + @Test + public void testProperty() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(LineLengthExtendedCheck.class); + + checkConfig.addAttribute("ignorePattern", "["); + + final String[] expected = {}; + + try { + verify(checkConfig, getPath("InputLineLengthExtendedCheck.java"), expected); + fail(); + } + catch (CheckstyleException ex) { + final String messagePrefix = "cannot initialize module " + + "com.puppycrawl.tools.checkstyle.TreeWalker - " + + "Cannot set property 'ignorePattern' to '[' in module "; + Assert.assertTrue("Exception's message does not start with: " + messagePrefix, + ex.getMessage().startsWith(messagePrefix)); + } + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/AllChecksTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/AllChecksTest.java index c3282532d2..ba44737299 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/AllChecksTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/AllChecksTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,14 +19,88 @@ package com.github.sevntu.checkstyle.internal; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; import java.util.Set; +import java.util.TreeMap; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Test; +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; + public class AllChecksTest { + + @Test + public void testDefaultTokensAreSubsetOfAcceptableTokens() throws Exception { + for (Class check : CheckUtil.getCheckstyleChecks()) { + if (AbstractCheck.class.isAssignableFrom(check)) { + final AbstractCheck testedCheck = (AbstractCheck) check.getDeclaredConstructor() + .newInstance(); + final int[] defaultTokens = testedCheck.getDefaultTokens(); + final int[] acceptableTokens = testedCheck.getAcceptableTokens(); + + if (!isSubset(defaultTokens, acceptableTokens)) { + final String errorMessage = String.format(Locale.ROOT, + "%s's default tokens must be a subset" + + " of acceptable tokens.", check.getName()); + Assert.fail(errorMessage); + } + } + } + } + + @Test + public void testRequiredTokensAreSubsetOfAcceptableTokens() throws Exception { + for (Class check : CheckUtil.getCheckstyleChecks()) { + if (AbstractCheck.class.isAssignableFrom(check)) { + final AbstractCheck testedCheck = (AbstractCheck) check.getDeclaredConstructor() + .newInstance(); + final int[] requiredTokens = testedCheck.getRequiredTokens(); + final int[] acceptableTokens = testedCheck.getAcceptableTokens(); + + if (!isSubset(requiredTokens, acceptableTokens)) { + final String errorMessage = String.format(Locale.ROOT, + "%s's required tokens must be a subset" + + " of acceptable tokens.", check.getName()); + Assert.fail(errorMessage); + } + } + } + } + + @Test + public void testRequiredTokensAreSubsetOfDefaultTokens() throws Exception { + for (Class check : CheckUtil.getCheckstyleChecks()) { + if (AbstractCheck.class.isAssignableFrom(check)) { + final AbstractCheck testedCheck = (AbstractCheck) check.getDeclaredConstructor() + .newInstance(); + final int[] defaultTokens = testedCheck.getDefaultTokens(); + final int[] requiredTokens = testedCheck.getRequiredTokens(); + + if (!isSubset(requiredTokens, defaultTokens)) { + final String errorMessage = String.format(Locale.ROOT, + "%s's required tokens must be a subset" + + " of default tokens.", check.getName()); + Assert.fail(errorMessage); + } + } + } + } + @Test public void testAllChecksAreReferencedInConfigFile() throws Exception { final Set checksReferencedInConfig = CheckUtil.getConfigCheckStyleChecks(); @@ -40,13 +114,220 @@ public void testAllChecksAreReferencedInConfigFile() throws Exception { }); } + @Test + public void testAllCheckstyleModulesHaveTest() throws Exception { + for (Class module : CheckUtil.getCheckstyleChecks()) { + final String path = "src/test/java/" + + module.getName().replace('.', File.separatorChar) + "Test.java"; + final File file = new File(path); + + Assert.assertTrue("Test must exist for " + module.getName() + " and be located at " + + path, file.exists()); + } + } + + @Test + public void testAllCheckstyleModulesHaveMessage() throws Exception { + for (Class module : CheckUtil.getCheckstyleChecks()) { + Assert.assertFalse(module.getSimpleName() + + " should have atleast one 'MSG_*' field for error messages", CheckUtil + .getCheckMessages(module).isEmpty()); + } + } + + @Test + public void testAllCheckstyleMessages() throws Exception { + final Map> usedMessages = new TreeMap<>(); + + // test validity of messages from checks + for (Class module : CheckUtil.getCheckstyleModules()) { + for (Field message : CheckUtil.getCheckMessages(module)) { + Assert.assertEquals(module.getSimpleName() + "." + message.getName() + + " should be 'public static final'", Modifier.PUBLIC | Modifier.STATIC + | Modifier.FINAL, message.getModifiers()); + + // below is required for package/private classes + if (!message.isAccessible()) { + message.setAccessible(true); + } + + verifyCheckstyleMessage(usedMessages, module, message); + } + } + + // test properties for messages not used by checks + for (Entry> entry : usedMessages.entrySet()) { + final Properties pr = new Properties(); + pr.load(AllChecksTest.class.getResourceAsStream( + "/" + entry.getKey().replace('.', '/') + "/messages.properties")); + + for (Object key : pr.keySet()) { + Assert.assertTrue("property '" + key + "' isn't used by any check in package '" + + entry.getKey() + "'", entry.getValue().contains(key.toString())); + } + } + } + + @Test + public void testAllInputsHaveTest() throws Exception { + final Map> allTests = new HashMap<>(); + + Files.walk(Paths.get("src/test/java/com/github/sevntu/checkstyle")) + .forEach(filePath -> { + grabAllTests(allTests, filePath.toFile()); + }); + Files.walk(Paths.get("src/test/resources/com/github/sevntu/checkstyle")) + .forEach(filePath -> { + verifyInputFile(allTests, filePath.toFile()); + }); + Files.walk(Paths.get("src/test/resources-noncompilable/com/github/sevntu/checkstyle")) + .forEach(filePath -> { + verifyInputFile(allTests, filePath.toFile()); + }); + } + + private static void verifyCheckstyleMessage(Map> usedMessages, + Class module, Field message) throws Exception { + final String messageString = message.get(null).toString(); + final String packageName = module.getPackage().getName(); + List packageMessages = usedMessages.get(packageName); + + if (packageMessages == null) { + packageMessages = new ArrayList<>(); + usedMessages.put(packageName, packageMessages); + } + + packageMessages.add(messageString); + + String result = null; + + try { + result = CheckUtil.getCheckMessage(module, messageString); + } + catch (IllegalArgumentException ex) { + Assert.fail(module.getSimpleName() + " with the message '" + messageString + + "' failed with: " + + ex.getClass().getSimpleName() + " - " + ex.getMessage()); + } + + Assert.assertNotNull( + module.getSimpleName() + " should have text for the message '" + + messageString + "'", + result); + Assert.assertFalse( + module.getSimpleName() + " should have non-empty text for the message '" + + messageString + "'", + result.trim().isEmpty()); + Assert.assertFalse( + module.getSimpleName() + " should have non-TODO text for the message '" + + messageString + "'", + result.trim().startsWith("TODO")); + } + + private static void grabAllTests(Map> allTests, File file) { + if (file.isFile() && file.getName().endsWith("Test.java")) { + String path = null; + + try { + path = getSimplePath(file.getCanonicalPath()).replace("Test.java", ""); + } + catch (IOException ex) { + throw new IllegalStateException(ex); + } + + final int slash = path.lastIndexOf(File.separatorChar); + final String pkg = path.substring(0, slash); + + List classes = allTests.get(pkg); + + if (classes == null) { + classes = new ArrayList<>(); + + allTests.put(pkg, classes); + } + + classes.add(path.substring(slash + 1)); + } + } + + private static void verifyInputFile(Map> allTests, File file) { + if (file.isFile()) { + String fileName = file.getName().toString(); + String path = null; + + try { + path = getSimplePath(file.getCanonicalPath()); + } + catch (IOException ex) { + throw new IllegalStateException(ex); + } + + Assert.assertTrue("Resource must start with 'Input': " + path, + fileName.startsWith("Input")); + + final int period = fileName.lastIndexOf("."); + + Assert.assertTrue("Resource must have an extension: " + path, period > 0); + + fileName = fileName.substring(5, period); + + final int slash = path.lastIndexOf(File.separatorChar); + final String pkg = path.substring(0, slash); + final List classes = allTests.get(pkg); + + if (classes != null || !pkg.endsWith("external")) { + Assert.assertNotNull("Resource must be in a package that has tests: " + path, + classes); + + boolean found = false; + + for (String clss : classes) { + if (fileName.startsWith(clss)) { + found = true; + break; + } + } + + Assert.assertTrue("Resource must be named after a Test like 'InputMyCheck.java' " + + "and be in the same package as the test: " + path, found); + } + } + } + /** * Removes 'Check' suffix from each class name in the set. * @param checks class instances. * @return a set of simple names. */ private static Set getFullNames(Set> checks) { - return checks.stream().map(check -> check.getName().replace("Check", "")) + return checks.stream().map(check -> check.getName()) .collect(Collectors.toSet()); } + + private static String getSimplePath(String path) { + return path.substring(path.lastIndexOf("com" + File.separator + "github")); + } + + /** + * Checks that an array is a subset of other array. + * @param array to check whether it is a subset. + * @param arrayToCheckIn array to check in. + */ + private static boolean isSubset(int[] array, int... arrayToCheckIn) { + boolean result = true; + if (arrayToCheckIn == null) { + result = array == null || array.length == 0; + } + else { + Arrays.sort(arrayToCheckIn); + for (final int element : array) { + if (Arrays.binarySearch(arrayToCheckIn, element) < 0) { + result = false; + break; + } + } + } + return result; + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CheckUtil.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CheckUtil.java index c0e53bf0e8..f5e527c43a 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CheckUtil.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CheckUtil.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -22,8 +22,9 @@ import java.io.File; import java.io.IOException; import java.lang.reflect.Field; -import java.lang.reflect.Modifier; +import java.text.MessageFormat; import java.util.HashSet; +import java.util.Properties; import java.util.Set; import javax.xml.parsers.DocumentBuilder; @@ -34,14 +35,11 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import com.google.common.collect.ImmutableSet; -import com.google.common.reflect.ClassPath; -import com.puppycrawl.tools.checkstyle.api.AbstractCheck; -import com.puppycrawl.tools.checkstyle.api.AutomaticBean; -import com.puppycrawl.tools.checkstyle.api.BeforeExecutionFileFilter; -import com.puppycrawl.tools.checkstyle.api.Filter; +import com.puppycrawl.tools.checkstyle.PackageNamesLoader; +import com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtils; public final class CheckUtil { + private CheckUtil() { } @@ -56,7 +54,7 @@ public static Set getConfigCheckStyleChecks() { * file path of checkstyle_checks.xml. * @return names of checkstyle's checks which are referenced in checkstyle_checks.xml. */ - private static Set getCheckStyleChecksReferencedInConfig(String configFilePath) { + public static Set getCheckStyleChecksReferencedInConfig(String configFilePath) { try { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -103,23 +101,19 @@ private static Set getCheckStyleChecksReferencedInConfig(String configFi /** * Gets the checkstyle's non abstract checks. * @return the set of checkstyle's non abstract check classes. - * @throws IOException if the attempt to read class path resources failed. + * @throws Exception if the attempt to read class path resources failed. */ - public static Set> getCheckstyleChecks() throws IOException { + public static Set> getCheckstyleChecks() throws Exception { final Set> checkstyleChecks = new HashSet<>(); final ClassLoader loader = Thread.currentThread() .getContextClassLoader(); - final ClassPath classpath = ClassPath.from(loader); - final String packageName = "com.github.sevntu.checkstyle"; - final ImmutableSet checkstyleClasses = classpath - .getTopLevelClassesRecursive(packageName); - - for (ClassPath.ClassInfo clazz : checkstyleClasses) { - final String className = clazz.getSimpleName(); - final Class loadedClass = clazz.load(); - if (isCheckstyleNonAbstractCheck(loadedClass, className)) { - checkstyleChecks.add(loadedClass); + final Set> checkstyleModules = ModuleReflectionUtils.getCheckstyleModules( + PackageNamesLoader.getPackageNames(loader), loader); + + for (Class clazz : checkstyleModules) { + if (ModuleReflectionUtils.isCheckstyleTreeWalkerCheck(clazz)) { + checkstyleChecks.add(clazz); } } return checkstyleChecks; @@ -136,11 +130,11 @@ public static Set getPackages(Set> modules) { return result; } - public static Set> getModulesInPackage(Set> modules, String packge) { + public static Set> getModulesInPackage(Set> modules, String pkg) { final Set> result = new HashSet<>(); for (Class module : modules) { - if (module.getPackage().getName().endsWith(packge)) { + if (module.getPackage().getName().endsWith(pkg)) { result.add(module); } } @@ -155,24 +149,12 @@ public static Set> getModulesInPackage(Set> modules, String pa * checkstyle's filters and SuppressWarningsHolder class. * * @return a set of checkstyle's modules names. - * @throws IOException if the attempt to read class path resources failed. + * @throws Exception if the attempt to read class path resources failed. */ - public static Set> getCheckstyleModules() throws IOException { - final Set> checkstyleModules = new HashSet<>(); - + public static Set> getCheckstyleModules() throws Exception { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); - final ClassPath classpath = ClassPath.from(loader); - final String packageName = "com.github.sevntu.checkstyle.checks"; - final ImmutableSet checkstyleClasses = classpath - .getTopLevelClassesRecursive(packageName); - - for (ClassPath.ClassInfo clazz : checkstyleClasses) { - final Class loadedClass = clazz.load(); - if (isCheckstyleModule(loadedClass)) { - checkstyleModules.add(loadedClass); - } - } - return checkstyleModules; + return ModuleReflectionUtils.getCheckstyleModules( + PackageNamesLoader.getPackageNames(loader), loader); } /** @@ -204,68 +186,27 @@ public static Set getCheckMessages(Class module) throws ClassNotFoundE } /** - * Checks whether a class may be considered as the checkstyle module. - * Checkstyle's modules are nonabstract classes which names end with - * 'Check', do not contain the word 'Input' (are not input files for UTs), - * checkstyle's filters, checkstyle's file filters and - * SuppressWarningsHolder class. - * - * @param loadedClass class to check. - * @return true if the class may be considered as the checkstyle module. - */ - private static boolean isCheckstyleModule(Class loadedClass) { - final String className = loadedClass.getSimpleName(); - return isCheckstyleNonAbstractCheck(loadedClass, className) - || isFilterModule(loadedClass, className) - || isFileFilterModule(loadedClass, className) - || "SuppressWarningsHolder".equals(className) - || "FileContentsHolder".equals(className); - } - - /** - * Checks whether a class may be considered as the checkstyle check. - * Checkstyle's checks are nonabstract classes which names end with 'Check', - * do not contain the word 'Input' (are not input files for UTs), and extend - * Check. - * - * @param loadedClass class to check. - * @param className class name to check. - * @return true if a class may be considered as the checkstyle check. - */ - private static boolean isCheckstyleNonAbstractCheck(Class loadedClass, String className) { - return !Modifier.isAbstract(loadedClass.getModifiers()) && className.endsWith("Check") - && !className.contains("Input") - && AbstractCheck.class.isAssignableFrom(loadedClass); - } - - /** - * Checks whether a class may be considered as the checkstyle filter. - * Checkstyle's filters are classes which are subclasses of AutomaticBean, - * implement 'Filter' interface, and which names end with 'Filter'. + * Gets the check message 'as is' from appropriate 'messages.properties' + * file. * - * @param loadedClass class to check. - * @param className class name to check. - * @return true if a class may be considered as the checkstyle filter. + * @param locale the locale to get the message for. + * @param messageKey the key of message in 'messages*.properties' file. + * @param arguments the arguments of message in 'messages*.properties' file. + * @return the check's formatted message. */ - private static boolean isFilterModule(Class loadedClass, String className) { - return Filter.class.isAssignableFrom(loadedClass) - && AutomaticBean.class.isAssignableFrom(loadedClass) - && className.endsWith("Filter"); + public static String getCheckMessage(Class module, String messageKey, + Object... arguments) { + String result; + final Properties pr = new Properties(); + try { + pr.load(module.getResourceAsStream("messages.properties")); + final MessageFormat formatter = new MessageFormat(pr.getProperty(messageKey)); + result = formatter.format(arguments); + } + catch (IOException ex) { + result = null; + } + return result; } - /** - * Checks whether a class may be considered as the checkstyle file filter. - * Checkstyle's file filters are classes which are subclasses of - * AutomaticBean, implement 'BeforeExecutionFileFilter' interface, and which - * names end with 'FileFilter'. - * - * @param loadedClass class to check. - * @param className class name to check. - * @return true if a class may be considered as the checkstyle file filter. - */ - private static boolean isFileFilterModule(Class loadedClass, String className) { - return BeforeExecutionFileFilter.class.isAssignableFrom(loadedClass) - && AutomaticBean.class.isAssignableFrom(loadedClass) - && className.endsWith("FileFilter"); - } } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/ChecksTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/ChecksTest.java index 3ed4d5ab10..8e3b1a007c 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/ChecksTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/ChecksTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -44,10 +44,13 @@ import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck; +import com.puppycrawl.tools.checkstyle.internal.utils.XmlUtil; public final class ChecksTest { + private static final Set CHECK_PROPERTIES = getProperties(AbstractCheck.class); - private static final Set JAVADOC_CHECK_PROPERTIES = getProperties(AbstractJavadocCheck.class); + private static final Set JAVADOC_CHECK_PROPERTIES = + getProperties(AbstractJavadocCheck.class); private static final Set FILESET_PROPERTIES = getProperties(AbstractFileSetCheck.class); @Test @@ -77,14 +80,14 @@ public void verifyTestConfigurationFiles() throws Exception { Assert.assertTrue("folder " + p + " must exist in eclipsecs", new File( getEclipseCsPath(p)).exists()); - final Set> packgeModules = CheckUtil.getModulesInPackage(modules, p); + final Set> pkgModules = CheckUtil.getModulesInPackage(modules, p); validateEclipseCsMetaXmlFile( new File(getEclipseCsPath(p + "/checkstyle-metadata.xml")), p, new HashSet<>( - packgeModules)); + pkgModules)); validateEclipseCsMetaPropFile(new File(getEclipseCsPath(p - + "/checkstyle-metadata.properties")), p, new HashSet<>(packgeModules)); + + "/checkstyle-metadata.properties")), p, new HashSet<>(pkgModules)); } } @@ -95,7 +98,7 @@ private static void validateSonarFile(Document document, Set> modules) final Node rule = rules.item(position); final Set children = XmlUtil.getChildrenElements(rule); - final String key = XmlUtil.findElementByTag(children, "key").getTextContent(); + final String key = SevntuXmlUtil.findElementByTag(children, "key").getTextContent(); final Class module = findModule(modules, key); modules.remove(module); @@ -103,13 +106,13 @@ private static void validateSonarFile(Document document, Set> modules) Assert.assertNotNull("Unknown class found in sonar: " + key, module); final String moduleName = module.getName(); - final Node name = XmlUtil.findElementByTag(children, "name"); + final Node name = SevntuXmlUtil.findElementByTag(children, "name"); Assert.assertNotNull(moduleName + " requires a name in sonar", name); Assert.assertFalse(moduleName + " requires a name in sonar", name.getTextContent() .isEmpty()); - final Node categoryNode = XmlUtil.findElementByTag(children, "category"); + final Node categoryNode = SevntuXmlUtil.findElementByTag(children, "category"); String expectedCategory = module.getCanonicalName(); final int lastIndex = expectedCategory.lastIndexOf('.'); @@ -125,18 +128,18 @@ private static void validateSonarFile(Document document, Set> modules) Assert.assertEquals(moduleName + " requires a valid category in sonar", expectedCategory, categoryAttribute.getTextContent()); - final Node description = XmlUtil.findElementByTag(children, "description"); + final Node description = SevntuXmlUtil.findElementByTag(children, "description"); Assert.assertNotNull(moduleName + " requires a description in sonar", description); - final Node configKey = XmlUtil.findElementByTag(children, "configKey"); + final Node configKey = SevntuXmlUtil.findElementByTag(children, "configKey"); final String expectedConfigKey = "Checker/TreeWalker/" + key; Assert.assertNotNull(moduleName + " requires a configKey in sonar", configKey); Assert.assertEquals(moduleName + " requires a valid configKey in sonar", expectedConfigKey, configKey.getTextContent()); - validateSonarProperties(module, XmlUtil.findElementsByTag(children, "param")); + validateSonarProperties(module, SevntuXmlUtil.findElementsByTag(children, "param")); } for (Class module : modules) { @@ -170,9 +173,9 @@ private static void validateSonarProperties(Class module, Set parameter } } - private static void validateEclipseCsMetaXmlFile(File file, String packge, - Set> packgeModules) throws Exception { - Assert.assertTrue("'checkstyle-metadata.xml' must exist in eclipsecs in inside " + packge, + private static void validateEclipseCsMetaXmlFile(File file, String pkg, + Set> pkgModules) throws Exception { + Assert.assertTrue("'checkstyle-metadata.xml' must exist in eclipsecs in inside " + pkg, file.exists()); final String input = new String(Files.readAllBytes(file.toPath()), UTF_8); @@ -180,62 +183,62 @@ private static void validateEclipseCsMetaXmlFile(File file, String packge, final NodeList ruleGroups = document.getElementsByTagName("rule-group-metadata"); - Assert.assertTrue(packge + " checkstyle-metadata.xml must contain only one rule group", + Assert.assertTrue(pkg + " checkstyle-metadata.xml must contain only one rule group", ruleGroups.getLength() == 1); for (int position = 0; position < ruleGroups.getLength(); position++) { final Node ruleGroup = ruleGroups.item(position); final Set children = XmlUtil.getChildrenElements(ruleGroup); - validateEclipseCsMetaXmlFileRules(packge, packgeModules, children); + validateEclipseCsMetaXmlFileRules(pkg, pkgModules, children); } - for (Class module : packgeModules) { - Assert.fail("Module not found in " + packge + " checkstyle-metadata.xml: " + for (Class module : pkgModules) { + Assert.fail("Module not found in " + pkg + " checkstyle-metadata.xml: " + module.getCanonicalName()); } } - private static void validateEclipseCsMetaXmlFileRules(String packge, - Set> packgeModules, Set rules) throws Exception { + private static void validateEclipseCsMetaXmlFileRules(String pkg, + Set> pkgModules, Set rules) throws Exception { for (Node rule : rules) { final NamedNodeMap attributes = rule.getAttributes(); final Node internalNameNode = attributes.getNamedItem("internal-name"); - Assert.assertNotNull(packge + " checkstyle-metadata.xml must contain an internal name", + Assert.assertNotNull(pkg + " checkstyle-metadata.xml must contain an internal name", internalNameNode); final String internalName = internalNameNode.getTextContent(); - final String classpath = "com.github.sevntu.checkstyle.checks." + packge + "." + final String classpath = "com.github.sevntu.checkstyle.checks." + pkg + "." + internalName; - final Class module = findModule(packgeModules, classpath); - packgeModules.remove(module); + final Class module = findModule(pkgModules, classpath); + pkgModules.remove(module); - Assert.assertNotNull("Unknown class found in " + packge + " checkstyle-metadata.xml: " + Assert.assertNotNull("Unknown class found in " + pkg + " checkstyle-metadata.xml: " + internalName, module); final Node nameAttribute = attributes.getNamedItem("name"); - Assert.assertNotNull(packge + " checkstyle-metadata.xml requires a name for " + Assert.assertNotNull(pkg + " checkstyle-metadata.xml requires a name for " + internalName, nameAttribute); - Assert.assertEquals(packge + " checkstyle-metadata.xml requires a valid name for " + Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid name for " + internalName, "%" + internalName + ".name", nameAttribute.getTextContent()); final Node parentAttribute = attributes.getNamedItem("parent"); - Assert.assertNotNull(packge + " checkstyle-metadata.xml requires a parent for " + Assert.assertNotNull(pkg + " checkstyle-metadata.xml requires a parent for " + internalName, parentAttribute); - Assert.assertEquals(packge + " checkstyle-metadata.xml requires a valid parent for " + Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid parent for " + internalName, "TreeWalker", parentAttribute.getTextContent()); final Set children = XmlUtil.getChildrenElements(rule); - validateEclipseCsMetaXmlFileRule(packge, module, children); + validateEclipseCsMetaXmlFileRule(pkg, module, children); } } - private static void validateEclipseCsMetaXmlFileRule(String packge, Class module, + private static void validateEclipseCsMetaXmlFileRule(String pkg, Class module, Set children) throws Exception { final String moduleName = module.getSimpleName(); final Set properties = getFinalProperties(module); @@ -258,95 +261,100 @@ private static void validateEclipseCsMetaXmlFileRule(String packge, Class mod case "alternative-name": final Node internalNameNode = attributes.getNamedItem("internal-name"); - Assert.assertNotNull(packge + Assert.assertNotNull(pkg + " checkstyle-metadata.xml must contain an internal name for " + moduleName, internalNameNode); final String internalName = internalNameNode.getTextContent(); - Assert.assertEquals(packge + Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid internal-name for " + moduleName, module.getName(), internalName); break; case "description": Assert.assertEquals( - packge + " checkstyle-metadata.xml requires a valid description for " - + moduleName, "%" + moduleName + ".desc", child.getTextContent()); + pkg + " checkstyle-metadata.xml requires a valid description for " + + moduleName, "%" + moduleName + ".desc", + child.getTextContent()); break; case "property-metadata": final String propertyName = attributes.getNamedItem("name").getTextContent(); - Assert.assertTrue(packge + " checkstyle-metadata.xml has an unknown parameter for " + Assert.assertTrue(pkg + + " checkstyle-metadata.xml has an unknown parameter for " + moduleName + ": " + propertyName, properties.remove(propertyName)); final Node firstChild = child.getFirstChild().getNextSibling(); - Assert.assertNotNull(packge - + " checkstyle-metadata.xml requires atleast one child for " + moduleName - + ", " + propertyName, firstChild); + Assert.assertNotNull(pkg + + " checkstyle-metadata.xml requires atleast one child for " + + moduleName + ", " + propertyName, firstChild); Assert.assertEquals( - packge - + " checkstyle-metadata.xml should have a description for the first child of " + pkg + + " checkstyle-metadata.xml should have a description for the " + + "first child of " + moduleName + ", " + propertyName, "description", firstChild.getNodeName()); - Assert.assertEquals(packge - + " checkstyle-metadata.xml requires a valid description for " + moduleName - + ", " + propertyName, "%" + moduleName + "." + propertyName, + Assert.assertEquals(pkg + + " checkstyle-metadata.xml requires a valid description for " + + moduleName + ", " + propertyName, "%" + moduleName + "." + + propertyName, firstChild.getTextContent()); break; case "message-key": final String key = attributes.getNamedItem("key").getTextContent(); - Assert.assertTrue(packge + " checkstyle-metadata.xml has an unknown message for " + Assert.assertTrue(pkg + + " checkstyle-metadata.xml has an unknown message for " + moduleName + ": " + key, messages.remove(key)); break; default: - Assert.fail(packge + " checkstyle-metadata.xml unknown node for " + moduleName + Assert.fail(pkg + " checkstyle-metadata.xml unknown node for " + moduleName + ": " + child.getNodeName()); break; } } for (String property : properties) { - Assert.fail(packge + " checkstyle-metadata.xml missing parameter for " + moduleName + Assert.fail(pkg + " checkstyle-metadata.xml missing parameter for " + moduleName + ": " + property); } for (String message : messages) { - Assert.fail(packge + " checkstyle-metadata.xml missing message for " + moduleName + Assert.fail(pkg + " checkstyle-metadata.xml missing message for " + moduleName + ": " + message); } } - private static void validateEclipseCsMetaPropFile(File file, String packge, - Set> packgeModules) throws Exception { + private static void validateEclipseCsMetaPropFile(File file, String pkg, + Set> pkgModules) throws Exception { Assert.assertTrue("'checkstyle-metadata.properties' must exist in eclipsecs in inside " - + packge, file.exists()); + + pkg, file.exists()); final Properties prop = new Properties(); prop.load(new FileInputStream(file)); final Set properties = new HashSet<>(Collections.list(prop.keys())); - for (Class module : packgeModules) { + for (Class module : pkgModules) { final String moduleName = module.getSimpleName(); - Assert.assertTrue(moduleName + " requires a name in eclipsecs properties " + packge, + Assert.assertTrue(moduleName + " requires a name in eclipsecs properties " + pkg, properties.remove(moduleName + ".name")); - Assert.assertTrue(moduleName + " requires a desc in eclipsecs properties " + packge, + Assert.assertTrue(moduleName + " requires a desc in eclipsecs properties " + pkg, properties.remove(moduleName + ".desc")); final Set moduleProperties = getFinalProperties(module); for (String moduleProperty : moduleProperties) { Assert.assertTrue(moduleName + " requires the property " + moduleProperty - + " in eclipsecs properties " + packge, + + " in eclipsecs properties " + pkg, properties.remove(moduleName + "." + moduleProperty)); } } for (Object property : properties) { - Assert.fail("Unknown property found in eclipsecs properties " + packge + ": " + Assert.fail("Unknown property found in eclipsecs properties " + pkg + ": " + property); } } @@ -420,4 +428,5 @@ private static String getSonarPath(String filename) throws IOException { "../sevntu-checkstyle-sonar-plugin/src/main/resources/com/github/sevntu/" + "checkstyle/sonar/" + filename).getCanonicalPath(); } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CheckstyleRegressionTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CheckstyleRegressionTest.java new file mode 100644 index 0000000000..f4d25eeef8 --- /dev/null +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CheckstyleRegressionTest.java @@ -0,0 +1,180 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2018 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.sevntu.checkstyle.internal; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import org.junit.Test; + +public class CheckstyleRegressionTest { + + /** List of checks to suppress if we dynamically add it to the configuration. */ + private static final List ADD_CHECK_SUPPRESSIONS = Arrays + .asList("ReturnCountExtendedCheck"); + + // -@cs[CyclomaticComplexity] Can't split + @Test + public void setupFiles() throws Exception { + final String regressionPath = System.getProperty("regression-path"); + + if (regressionPath != null) { + final File path = new File(regressionPath); + + if (!path.exists()) { + throw new IllegalStateException("Invalid path: " + path.getAbsolutePath()); + } + + System.out.println("Working Path: " + path.getCanonicalPath()); + + final File project = new File(path, "checkstyle"); + + if (!project.exists() || !project.isDirectory()) { + throw new IllegalStateException("Can't find project: " + project.getAbsolutePath()); + } + + final File config = new File(project, "config/checkstyle_sevntu_checks.xml"); + + if (!config.exists() || !config.isFile() || !config.canRead() || !config.canWrite()) { + throw new IllegalStateException("Can't read config: " + config.getAbsolutePath()); + } + + System.out.println("Config Path: " + config.getCanonicalPath()); + + final File suppression = new File(project, "config/sevntu_suppressions.xml"); + + if (!suppression.exists() || !suppression.isFile() || !suppression.canRead() + || !suppression.canWrite()) { + throw new IllegalStateException("Can't read suppression: " + + suppression.getAbsolutePath()); + } + + System.out.println("Suppression Path: " + suppression.getCanonicalPath()); + + work(config, suppression); + + System.out.println("Done"); + } + } + + private static void work(File config, File suppression) throws Exception { + final Set configChecks = CheckUtil.getCheckStyleChecksReferencedInConfig(config + .getAbsolutePath()); + final List> sevntuChecks = new ArrayList<>(CheckUtil.getCheckstyleModules()); + + trimSevntuChecksNotReferenced(configChecks, sevntuChecks); + + if (sevntuChecks.size() > 0) { + System.out.println("Adding " + sevntuChecks.size() + " missing check(s)"); + + String configAdditions = ""; + String suppressionAdditions = ""; + + for (Class sevntuCheck : sevntuChecks) { + final String name = sevntuCheck.getName(); + final String simpleName = sevntuCheck.getSimpleName(); + + System.out.println("-- Adding Check: " + name); + + configAdditions += "\r\n"; + + if (ADD_CHECK_SUPPRESSIONS.contains(simpleName)) { + System.out.println("-- Adding Suppression: " + simpleName); + + suppressionAdditions += "\r\n"; + } + } + + String configContents = new String(Files.readAllBytes(config.toPath()), UTF_8); + + int treeWalkerPosition = configContents.lastIndexOf(""); + treeWalkerPosition = configContents.indexOf('\n', treeWalkerPosition) + 1; + + configContents = configContents.substring(0, treeWalkerPosition) + configAdditions + + configContents.substring(treeWalkerPosition); + + Files.write(config.toPath(), configContents.getBytes(UTF_8), StandardOpenOption.CREATE); + + if (!suppressionAdditions.isEmpty()) { + String suppressionContents = new String(Files.readAllBytes(suppression.toPath()), + UTF_8); + final int position = suppressionContents.lastIndexOf(" configChecks, + List> sevntuChecks) { + for (String configCheck : configChecks) { + final int position = findCheck(sevntuChecks, configCheck); + + if (position == -1) { + System.err.println("Found module not in sevntu: " + configCheck); + } + else { + sevntuChecks.remove(position); + } + } + } + + // -@cs[ReturnCount] Not simple to reduce returns + private static int findCheck(Collection> checks, String findCheck) { + int position = 0; + + for (Class check : checks) { + final String simpleName = check.getSimpleName(); + + if (findCheck.endsWith("Check")) { + if (simpleName.equals(findCheck) || check.getName().equals(findCheck)) { + return position; + } + } + else { + if (simpleName.replaceAll("Check$", "").equals(findCheck) + || check.getName().replaceAll("Check$", "").equals(findCheck)) { + return position; + } + } + + position++; + } + + return -1; + } + +} diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CommitValidationTest.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CommitValidationTest.java index 2b5a859a59..786f98911a 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CommitValidationTest.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/CommitValidationTest.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -134,11 +134,11 @@ public void testCommitMessage() { @Test public void testCommitMessageHasProperStructure() { for (RevCommit commit : filterValidCommits(lastCommits)) { - final String commitId = commit.getId().getName(); final String commitMessage = commit.getFullMessage(); final int error = validateCommitMessage(commitMessage); if (error != 0) { + final String commitId = commit.getId().getName(); fail(getInvalidCommitMessageFormattingError(commitId, commitMessage) + error); } } @@ -290,11 +290,14 @@ private static String getInvalidCommitMessageFormattingError(String commitId, } private enum CommitsResolutionMode { + BY_COUNTER, BY_LAST_COMMIT_AUTHOR, + } private static class RevCommitsPair { + private final Iterator first; private final Iterator second; @@ -315,6 +318,7 @@ public Iterator getFirst() { public Iterator getSecond() { return second; } + } private static class OmitMergeCommitsIterator implements Iterator { @@ -343,5 +347,7 @@ public RevCommit next() { public void remove() { throw new UnsupportedOperationException("remove"); } + } + } diff --git a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/XmlUtil.java b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/SevntuXmlUtil.java similarity index 52% rename from sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/XmlUtil.java rename to sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/SevntuXmlUtil.java index f6d7615eb8..251dc9ca7e 100644 --- a/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/XmlUtil.java +++ b/sevntu-checks/src/test/java/com/github/sevntu/checkstyle/internal/SevntuXmlUtil.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,55 +19,14 @@ package com.github.sevntu.checkstyle.internal; -import java.io.IOException; -import java.io.StringReader; import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.Set; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.junit.Assert; -import org.w3c.dom.Document; import org.w3c.dom.Node; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public final class XmlUtil { - private XmlUtil() { - } - - public static Document getRawXml(String fileName, String code, String unserializedSource) - throws ParserConfigurationException { - try { - final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setValidating(false); - factory.setNamespaceAware(true); - - final DocumentBuilder builder = factory.newDocumentBuilder(); - - return builder.parse(new InputSource(new StringReader(code))); - } - catch (IOException | SAXException ex) { - Assert.fail(fileName + " has invalid xml (" + ex.getMessage() + "): " - + unserializedSource); - } - return null; - } - - public static Set getChildrenElements(Node node) { - final Set result = new LinkedHashSet<>(); - - for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { - if (child.getNodeType() != Node.TEXT_NODE) { - result.add(child); - } - } +public final class SevntuXmlUtil { - return result; + private SevntuXmlUtil() { } public static Node findElementByTag(Set nodes, String tag) { @@ -94,4 +53,5 @@ public static Set findElementsByTag(Set nodes, String tag) { return result; } + } diff --git a/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck3.java b/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck3.java similarity index 95% rename from sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck3.java rename to sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck3.java index b13b6979f0..0fa875a8a9 100644 --- a/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck3.java +++ b/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck3.java @@ -2,7 +2,7 @@ import java.util.function.Function; -public class InputNumericLiteralNeedUnderscoreCheck3 { +public class InputNumericLiteralNeedsUnderscoreCheck3 { private static final float G = 6.6740831E-11f; private static final double H = 6.626070040E-34d; diff --git a/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnTestNPE.java b/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckTestNPE.java similarity index 89% rename from sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnTestNPE.java rename to sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckTestNPE.java index d4bf6f2d4b..a92e677657 100644 --- a/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnTestNPE.java +++ b/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckTestNPE.java @@ -11,7 +11,7 @@ import javax.sql.DataSource; -public class InputRedundantReturnTestNPE +public class InputRedundantReturnCheckTestNPE { public void init() { @@ -51,14 +51,14 @@ public static void outputDocument(String targetProvider, String uri, String requ return; } - long ifModofiedSince = Integer.parseInt(request); + long ifModifiedSince = Integer.parseInt(request); boolean gzip = Boolean.getBoolean(request); String output = new String(response + gzip); try { - if (ifModofiedSince > 0) { - if (!targetProvider.equals(uri + ifModofiedSince + output)) { + if (ifModifiedSince > 0) { + if (!targetProvider.equals(uri + ifModifiedSince + output)) { response.concat(""); return; } diff --git a/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateInterfaceMethod.java b/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckInterfaceMethod.java similarity index 81% rename from sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateInterfaceMethod.java rename to sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckInterfaceMethod.java index cc18ad876a..2a476fa51a 100644 --- a/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateInterfaceMethod.java +++ b/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckInterfaceMethod.java @@ -3,7 +3,7 @@ /** * Compilable with Java 8. */ -public class InputStaticMethodCandidateInterfaceMethod { +public class InputStaticMethodCandidateCheckInterfaceMethod { interface InnerIterface { default void foo() { diff --git a/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateLambda.java b/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckLambda.java similarity index 85% rename from sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateLambda.java rename to sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckLambda.java index 8cd75971fd..de2b32b89a 100644 --- a/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateLambda.java +++ b/sevntu-checks/src/test/resources-noncompilable/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckLambda.java @@ -5,7 +5,7 @@ /** * Compilable with Java 8. */ -public class InputStaticMethodCandidateLambda { +public class InputStaticMethodCandidateCheckLambda { public void getEntityCallbackWithLambdas() { JButton testButton = new JButton("Test Button"); testButton.addActionListener((e) -> System.out.println("")); diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotation2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotation2.java deleted file mode 100644 index 69e4c7a66f..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotation2.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.github.sevntu.checkstyle.checks.annotation; -import java.awt.Component; - -public class InputForbidAnnotation2 extends Component { - private static final long serialVersionUID = 1L; - -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotation.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotationCheck.java similarity index 96% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotation.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotationCheck.java index 5138fbd006..245a7e4320 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotation.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotationCheck.java @@ -4,10 +4,10 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Test -public class InputForbidAnnotation { +public class InputForbidAnnotationCheck { @ctor @ctor2 - InputForbidAnnotation(){ + InputForbidAnnotationCheck(){ } @Edible(true) diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotationCheck2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotationCheck2.java new file mode 100644 index 0000000000..ab5dc1769e --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/annotation/InputForbidAnnotationCheck2.java @@ -0,0 +1,7 @@ +package com.github.sevntu.checkstyle.checks.annotation; + +public class InputForbidAnnotationCheck2 { + @org.junit.Test + public void method() { + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidConstantAsFirstOperandInConditionCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidConstantAsFirstOperandInConditionCheck.java index 73356e1a1d..5b251f9491 100755 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidConstantAsFirstOperandInConditionCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidConstantAsFirstOperandInConditionCheck.java @@ -112,4 +112,23 @@ public void forCyclesCheck() { for (someVariable = null; null == someVariable; someVariable = null) {} //!! } + public void expressionsWithInnerConstant() { + int a = 0, b = 0; + + if (1 == (1 & (a >> b))) {} + if (1 != someMethod(1)) {} + if (1 != a * 2) {} + if (null != System.getProperty("test.src", null)) {} + } + + public int someMethod(int i) { return i; } + + public void otherConditions() { + int a = 0; + + if (1 < a) {} + if (1 <= a) {} + if (1 > a) {} + if (1 >= a) {} + } } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck1.java similarity index 89% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses1.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck1.java index 4e8fb3af93..8829c477b5 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses1.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck1.java @@ -2,12 +2,12 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -public class InputAvoidDefaultSerializableInInnerClasses1 implements Serializable +public class InputAvoidDefaultSerializableInInnerClassesCheck1 implements Serializable { private int field1; private String field2 = new String(); - InputAvoidDefaultSerializableInInnerClasses1(int a, int b, String s) + InputAvoidDefaultSerializableInInnerClassesCheck1(int a, int b, String s) { this.field1 = a; this.field2 = s; @@ -156,7 +156,7 @@ public void readObject(ObjectInputStream s) } } - private class NoErrorForPartlial1 implements Serializable + private class NoErrorForPartial1 implements Serializable { private void readObject(ObjectInputStream s) { @@ -168,7 +168,7 @@ public int writeObject(ObjectOutputStream s) } } - private class ErrorForPartlial implements Serializable //error + private class ErrorForPartial implements Serializable //error { private final int readObject(ObjectInputStream s) { @@ -191,4 +191,4 @@ private void writeObject(ObjectOutputStream s, long l) } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck2.java similarity index 93% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck2.java index 243dffb981..0b29cd92cd 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck2.java @@ -5,7 +5,7 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -public class InputAvoidDefaultSerializableInInnerClasses2 +public class InputAvoidDefaultSerializableInInnerClassesCheck2 { public class Foo implements Serializable { @@ -25,4 +25,4 @@ private Foo readObject(String str) throws ParseException { return result; } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck3.java similarity index 95% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses3.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck3.java index 242ac6c97d..b77b1c6fc6 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClasses3.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidDefaultSerializableInInnerClassesCheck3.java @@ -5,7 +5,7 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -public class InputAvoidDefaultSerializableInInnerClasses3 { +public class InputAvoidDefaultSerializableInInnerClassesCheck3 { public class Foo implements java.io.Serializable { private static final long serialVersionUID = 1L; public Date date; @@ -35,4 +35,4 @@ private void writeObject(ObjectOutputStream aOutputStream) aOutputStream.writeObject(date); } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidHidingCauseExceptionCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidHidingCauseExceptionCheck.java index 2b072f4ecf..51bc063a75 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidHidingCauseExceptionCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidHidingCauseExceptionCheck.java @@ -20,12 +20,12 @@ public void Simple() catch (IllegalStateException e) { //your code - throw new RuntimeException("Runtime Ecxeption!"); // ! + throw new RuntimeException("Runtime Exception!"); // ! } catch (java.lang.ArithmeticException e) { //your code - throw new RuntimeException("Runtime Ecxeption!", e); + throw new RuntimeException("Runtime Exception!", e); } catch (RuntimeException e) { @@ -62,14 +62,14 @@ public void Stronger() x = !!!!!!!!false & !!!!!!!!true; double kkk = Math.pow(5, 25555555); int ee = (int) kkk; - throw new RuntimeException("Runtime Ecxeption!"); // ! + throw new RuntimeException("Runtime Exception!"); // ! } } catch (java.lang.ArithmeticException e) { int []err = new int [50]; if (err[51]==0) { err[999]++; } - throw new RuntimeException("Runtime Ecxeption!", e); + throw new RuntimeException("Runtime Exception!", e); } catch (RuntimeException e) { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidHidingCauseExceptionCheckWrapping.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidHidingCauseExceptionCheckWrapping.java new file mode 100644 index 0000000000..e318eea8ae --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidHidingCauseExceptionCheckWrapping.java @@ -0,0 +1,17 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputAvoidHidingCauseExceptionCheckWrapping { + private Exception field; + + public void executeLocal() { + try { + } + catch (final Exception e) { + this.field = InputAvoidHidingCauseExceptionCheckWrapping.method(new Exception(e)); + } + } + + private static Exception method(Exception exception) { + return exception; + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidModifiersForTypesCheck2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidModifiersForTypesCheck2.java index ea915cdc35..e482020f02 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidModifiersForTypesCheck2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidModifiersForTypesCheck2.java @@ -1,24 +1,22 @@ package com.github.sevntu.checkstyle.checks.coding; -import com.github.sevntu.checkstyle.BaseCheckTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; -public class InputAvoidModifiersForTypesCheck2 extends BaseCheckTestSupport +public class InputAvoidModifiersForTypesCheck2 extends BaseClass { @Test public void testSimple() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(LineLengthCheck.class); + createModuleConfig(LineLengthCheck.class); checkConfig.addAttribute("max", "80"); checkConfig.addAttribute("ignorePattern", "^.*is OK.*regexp.*$"); final String[] expected = { "18: Line is longer than 80 characters.", "145: Line is longer than 80 characters.", }; - verify(checkConfig, getPath("InputSimple.java"), expected); + verify(checkConfig, getPath("InputSomeFile.java"), expected); } @Test @@ -26,7 +24,7 @@ public void testSimpleIgnore() throws Exception { final DefaultConfiguration checkConfig = - createCheckConfig(LineLengthCheck.class); + createModuleConfig(LineLengthCheck.class); checkConfig.addAttribute("max", "40"); checkConfig.addAttribute("ignorePattern", "^.*is OK.*regexp.*$"); final String[] expected = { @@ -52,11 +50,26 @@ public void testSimpleIgnore() checkConfig.addAttribute("ignoreField", "true"); checkConfig.addAttribute("ignoreMethod", "true"); //System.setProperty("testinputs.dir", "/home/romani/Practice/New_workspace/sevntu.checkstyle/src/testinputs/com/puppycrawl/tools/checkstyle/sizes"); - verify(checkConfig, getPath("InputSimple.java"), expected); + verify(checkConfig, getPath("InputSomeFile.java"), expected); } - + class LineLengthCheck { } -} \ No newline at end of file +} +class DefaultConfiguration { + public void addAttribute(String name, String value) {} +} +abstract class BaseClass { + protected String getPath(String fileName) { + return null; + } + + protected DefaultConfiguration createModuleConfig(Class clss) { + return new DefaultConfiguration(); + } + + protected void verify(DefaultConfiguration checkConfig, String path, String[] expected) { + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheck.java index 48e7e5fec4..cd6017978b 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheck.java @@ -160,4 +160,19 @@ class MyConstructor { boolean x = InputAvoidNotShortCircuitOperatorsForBooleanCheck.x | InputAvoidNotShortCircuitOperatorsForBooleanCheck.x; } + + public void test() { + new Runnable() { + @Override + public void run() { + } + public boolean test() { + try { + } catch (IllegalArgumentException | NullPointerException e) { + return false; + } + return true; + } + }; + } } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheckLambdaWithMultiCatch.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheckLambdaWithMultiCatch.java new file mode 100644 index 0000000000..56fd64e447 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheckLambdaWithMultiCatch.java @@ -0,0 +1,16 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import java.awt.EventQueue; + +public class InputAvoidNotShortCircuitOperatorsForBooleanCheckLambdaWithMultiCatch { + public void method() { + EventQueue.invokeLater(() -> { + if (true) { + try { + } + catch (NullPointerException | IndexOutOfBoundsException ex) { + } + } + }); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheckNonClasses.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheckNonClasses.java new file mode 100644 index 0000000000..9fd48f60da --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputAvoidNotShortCircuitOperatorsForBooleanCheckNonClasses.java @@ -0,0 +1,13 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public interface InputAvoidNotShortCircuitOperatorsForBooleanCheckNonClasses { + int field = 4 << 16 | 0; +} +enum TestEnum { + ; + + int field = 4 << 16 | 0; +} +@interface TestAnnotation { + int field = 4 << 16 | 0; +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputConfusingConditionCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputConfusingConditionCheck.java index a584a6ad0e..4e316e801d 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputConfusingConditionCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputConfusingConditionCheck.java @@ -242,7 +242,24 @@ else if (!a) {} } else { a = true; - } + } + + if (!a) { + // + } + else if (!b) { + a = true; + } + else { + // + } + + if (!a) + ; + else if (!b) + ; + else + ; } } \ No newline at end of file diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputConfusingConditionCheck2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputConfusingConditionCheck2.java new file mode 100644 index 0000000000..e23cfcef60 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputConfusingConditionCheck2.java @@ -0,0 +1,17 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputConfusingConditionCheck2 { + class InnerEmptyBlocks { + void foo() { + } + } + + InnerEmptyBlocks anon = new InnerEmptyBlocks() { + boolean flag = true; + + void foo() { + if(flag); + else; + } + }; +} \ No newline at end of file diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputCustomDeclarationOrder.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputCustomDeclarationOrderCheck.java similarity index 93% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputCustomDeclarationOrder.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputCustomDeclarationOrderCheck.java index f4c5589bce..c46b3524be 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputCustomDeclarationOrder.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputCustomDeclarationOrderCheck.java @@ -2,7 +2,7 @@ import java.util.ArrayList; -public class InputCustomDeclarationOrder { +public class InputCustomDeclarationOrderCheck { public static final int TEST = 0; public final int test = 1; @@ -30,7 +30,7 @@ public String test() { } }; - private InputCustomDeclarationOrder() { + private InputCustomDeclarationOrderCheck() { //constructor } @@ -42,7 +42,7 @@ protected String test() { return "test"; } - InputCustomDeclarationOrder(int aTest) { + InputCustomDeclarationOrderCheck(int aTest) { //constructor } @@ -53,7 +53,7 @@ public static void editTest() { } public abstract class AbstractTest extends - InputCustomDeclarationOrder + InputCustomDeclarationOrderCheck { private static final long INNER_T1 = 1L; @@ -77,7 +77,7 @@ private void innerTest1() { private static class Test { private abstract static class AbstractTest1 { } - public abstract class AbstractrTest2 { + public abstract class AbstractTest2 { } } @@ -188,4 +188,4 @@ public abstract class privatea { private class publicabstract { } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass1.java deleted file mode 100644 index b55a2b1d8d..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass1.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputEmptyPublicCtorInClass1 -{ - public InputEmptyPublicCtorInClass1() { - - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass2.java deleted file mode 100644 index 20e6d3ec96..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass2.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputEmptyPublicCtorInClass2 -{ - private InputEmptyPublicCtorInClass2() { - - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass3.java deleted file mode 100644 index b610bc9978..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass3.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputEmptyPublicCtorInClass3 -{ - public InputEmptyPublicCtorInClass3() { - - } - - public InputEmptyPublicCtorInClass3(int i) { - - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass6.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass6.java deleted file mode 100644 index f6a36ed384..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass6.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputEmptyPublicCtorInClass6 -{ - protected InputEmptyPublicCtorInClass6() { - - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck1.java new file mode 100644 index 0000000000..70c0457f6d --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck1.java @@ -0,0 +1,8 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputEmptyPublicCtorInClassCheck1 +{ + public InputEmptyPublicCtorInClassCheck1() { + + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass10.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck10.java similarity index 87% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass10.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck10.java index 408735ee2a..a7a0a64c31 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass10.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck10.java @@ -5,7 +5,7 @@ import org.junit.runners.*; -public class InputEmptyPublicCtorInClass10 +public class InputEmptyPublicCtorInClassCheck10 { @RunWith(Parameterized.class) class Inner1 { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck2.java new file mode 100644 index 0000000000..a9595f0151 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck2.java @@ -0,0 +1,8 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputEmptyPublicCtorInClassCheck2 +{ + private InputEmptyPublicCtorInClassCheck2() { + + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck3.java new file mode 100644 index 0000000000..e64ea8a06f --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck3.java @@ -0,0 +1,12 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputEmptyPublicCtorInClassCheck3 +{ + public InputEmptyPublicCtorInClassCheck3() { + + } + + public InputEmptyPublicCtorInClassCheck3(int i) { + + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass4.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck4.java similarity index 54% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass4.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck4.java index 942d3e3cbc..fb3b67adce 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass4.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck4.java @@ -1,10 +1,10 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputEmptyPublicCtorInClass4 +public class InputEmptyPublicCtorInClassCheck4 { private int field; - public InputEmptyPublicCtorInClass4() { + public InputEmptyPublicCtorInClassCheck4() { field =4; } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass5.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck5.java similarity index 76% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass5.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck5.java index 440b41fe2a..924f4bd3f9 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass5.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck5.java @@ -1,8 +1,8 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputEmptyPublicCtorInClass5 +public class InputEmptyPublicCtorInClassCheck5 { - public InputEmptyPublicCtorInClass5() + public InputEmptyPublicCtorInClassCheck5() { } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck6.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck6.java new file mode 100644 index 0000000000..4152cdee60 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck6.java @@ -0,0 +1,8 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputEmptyPublicCtorInClassCheck6 +{ + protected InputEmptyPublicCtorInClassCheck6() { + + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass7.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck7.java similarity index 56% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass7.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck7.java index f822f4b9af..5392650940 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass7.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck7.java @@ -1,9 +1,9 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputEmptyPublicCtorInClass7 +public class InputEmptyPublicCtorInClassCheck7 { @AnnotationName - public InputEmptyPublicCtorInClass7() { + public InputEmptyPublicCtorInClassCheck7() { } } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass8.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck8.java similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass8.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck8.java index 7e97789b1f..76c35559fa 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass8.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck8.java @@ -6,7 +6,7 @@ import org.junit.runners.Parameterized.Parameters; -public class InputEmptyPublicCtorInClass8 +public class InputEmptyPublicCtorInClassCheck8 { //RunWith is imported with single type import. @RunWith(Parameterized.class) @@ -40,7 +40,7 @@ public Inner4() { } } - @InputEmptyPublicCtorInClass9.InnerAnnotation + @InputEmptyPublicCtorInClassCheck9.InnerAnnotation class Inner5 { public Inner5() { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass9.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck9.java similarity index 66% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass9.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck9.java index ce9ddad021..1a8acafdf8 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClass9.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputEmptyPublicCtorInClassCheck9.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputEmptyPublicCtorInClass9 +public class InputEmptyPublicCtorInClassCheck9 { @interface InnerAnnotation { } } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputFinalizeImplementationCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputFinalizeImplementationCheck.java index 4dc4dbe06d..a9e98391cf 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputFinalizeImplementationCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputFinalizeImplementationCheck.java @@ -81,4 +81,24 @@ protected void finalize() throws Throwable } } +} + +class TestNoFinal { + public static void doStuff() + { + } + protected void finalize() throws Throwable + { + try { + doStuff(); + } + catch(Exception e) { + } + } +} + +interface TestNotFinalize { + int finalize() throws Throwable; + void finalize(int n) throws Throwable; + void someOtherMethod(); } \ No newline at end of file diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputFinalizeImplementationCheckSpecial.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputFinalizeImplementationCheckSpecial.java new file mode 100644 index 0000000000..ededf30c16 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputFinalizeImplementationCheckSpecial.java @@ -0,0 +1,25 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputFinalizeImplementationCheckSpecial { + private boolean condition; + @Override + protected void finalize() throws Throwable { + if (condition) { + method(); + } + method(); + super.finalize(); + } + + private void method() { + } +} +class InputFinalizeImplementationCheckSpecial2 { + @Override + protected void finalize() throws Throwable { + this.method(); + } + + private void method() { + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck.java similarity index 68% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck.java index 8998c77b3d..5fa5b65b69 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; - public class InputForbidCCommentsInMethods + public class InputForbidCCommentsInMethodsCheck { /* * first comment, that hasn't error @@ -69,3 +69,26 @@ private void anyMethod() } } } +class InnerInputForbidCCommentsInMethods3 { + /* Comment before field. */ + private int field; + + /* Comment on same line as method. */ void method1() {} + void method2() {} /* Comment on same line as method. */ + void method3() { /* Comment on same line as method but inside. */ } + + void method4() { + new innerClass() { + /* Comment inside anonymous class. */ + public void innerMethod() {} + }; + } + + private static void /* Comment insside definition. */ method5() {} + /* Comment before native method. */ + public native void method6(); + + private abstract class innerClass { + public abstract void innerMethod(); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck2.java similarity index 80% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck2.java index daab709fe3..620e96e216 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck2.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputForbidCCommentsInMethods2 +public class InputForbidCCommentsInMethodsCheck2 { public String getAdditionalTables() { return null; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck3.java similarity index 73% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods3.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck3.java index 6abe43bda7..34b1a5cbb9 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethods3.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCCommentsInMethodsCheck3.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public interface InputForbidCCommentsInMethods3 +public interface InputForbidCCommentsInMethodsCheck3 { /* * first comment, that hasn't error diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidsCertainImports.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheck.java similarity index 72% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidsCertainImports.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheck.java index e5b85f4154..c595c0c907 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidsCertainImports.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheck.java @@ -12,13 +12,18 @@ * @author Daniil * Yaroslavtsev */ -public class InputForbidsCertainImports extends Check +public class InputForbidCertainImportsCheck extends Check { public int a() { - AutomaticBean smth = new com.puppycrawl.tools.checkstyle.api.AutomaticBean(); // forbidden! + AutomaticBean smth = new com.puppycrawl.tools.checkstyle.api.AutomaticBean() { // forbidden! + @Override + protected void finishLocalSetup() { + } + }; + Number test = new Integer(0); return 5; } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsDefaultPackageWithoutImports.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheckDefaultPackageWithoutImports.java similarity index 87% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsDefaultPackageWithoutImports.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheckDefaultPackageWithoutImports.java index da4ebea06a..a65cb757c4 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsDefaultPackageWithoutImports.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheckDefaultPackageWithoutImports.java @@ -13,7 +13,7 @@ * @author Daniil * Yaroslavtsev */ -public class InputForbidCertainImportsDefaultPackageWithoutImports extends Check +public class InputForbidCertainImportsCheckDefaultPackageWithoutImports extends Check { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheckSinglePackage.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheckSinglePackage.java new file mode 100644 index 0000000000..caeb22e30c --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainImportsCheckSinglePackage.java @@ -0,0 +1,17 @@ +package sevntu; + +import com.puppycrawl.tools.checkstyle.api.AutomaticBean; // forbidden + +public class InputForbidCertainImportsCheckSinglePackage +{ + public int a() + { + + AutomaticBean smth = new com.puppycrawl.tools.checkstyle.api.AutomaticBean() { // forbidden! + @Override + protected void finishLocalSetup() { + } + }; + return 5; + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainMethodCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainMethodCheck.java new file mode 100644 index 0000000000..cc5c8809f4 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidCertainMethodCheck.java @@ -0,0 +1,57 @@ +//////////////////////////////////////////////////////////////////////////////// +// Test case file for checkstyle. +// Created: 2017 +//////////////////////////////////////////////////////////////////////////////// +package com.github.sevntu.checkstyle.checks.coding; + +import org.junit.Assert; + +import java.io.File; +import java.util.Arrays; + +/** + * Test case for detecting usage of forbidden method. + * @author Raghav Kumar Gautam + **/ +class InputForbidCertainMethodCheck +{ + /** + * no param constructor + */ + InputForbidCertainMethodCheck() { + System.exit(1); + } + + /** + * non final param method + */ + void method(String s) { + Assert.assertTrue(1 != 2); + Assert.assertTrue("Good assert with some reason.", true); + ForbiddenMethod.exit2(); + ForbiddenMethod.INSTANCE.exit2(); + //method call that does not need "." in it + method(""); + // new usage that does not invoke constructor + String[] strs = new String[4]; + Arrays.stream(strs).map(File::new).count(); + } + + private static class ForbiddenMethod { + static final ForbiddenMethod INSTANCE = new ForbiddenMethod(); + static void exit2() { + Arrays.asList(1); + Arrays.asList(1, 2); + Arrays.asList(1, 2, 3); + Arrays.asList(1, 2, 3, 4); + Arrays.asList(1, 2, 3, 4, 5); + Arrays.asList(1, 2, 3, 4, 5, 6); + Arrays.asList(1, 2, 3, 4, 5, 6, 7); + Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); + Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); + Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); + Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); + } + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidInstantiationCheckWithoutDots.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidInstantiationCheckWithoutDots.java index 5aaaf99a28..32a9492920 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidInstantiationCheckWithoutDots.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidInstantiationCheckWithoutDots.java @@ -9,7 +9,7 @@ public void method() { int []x = new int[10]; new InputForbidInstantiationCheck(); NullPointerException ex2 = new java.lang.NullPointerException("message"); // ! - com.github.sevntu.checkstyle.checks.test.utils.File File = new com.github.sevntu.checkstyle.checks.test.utils.File(""); // ! + com.github.sevntu.checkstyle.checks.coding.InputForbidInstantiationCheck File = new com.github.sevntu.checkstyle.checks.coding.InputForbidInstantiationCheck(); // ! File File1 = new java.io.File(""); // 2 ! String a = new String(); // 2 ! InputForbidInstantiationCheck c = new InputForbidInstantiationCheck(); diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck.java similarity index 91% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck.java index 05de44f3c8..b1817c0d4e 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputForbidThrowAnonymousExceptions { +public class InputForbidThrowAnonymousExceptionsCheck { public void anonymousEx() { try { //some code @@ -30,4 +30,4 @@ public void notAnonEx3() { } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck2.java similarity index 94% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck2.java index a6fb81ab7a..761e6bb2a6 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck2.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputForbidThrowAnonymousExceptions2 { +public class InputForbidThrowAnonymousExceptionsCheck2 { public void anonymousEx() { try { //some code @@ -41,4 +41,4 @@ public void notAnonEx3() { } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck3.java similarity index 98% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions3.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck3.java index a2cd555a4e..107b4cfcec 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptions3.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheck3.java @@ -2,7 +2,7 @@ import java.util.Comparator; -public class InputForbidThrowAnonymousExceptions3 { +public class InputForbidThrowAnonymousExceptionsCheck3 { protected RuntimeException exception = new RuntimeException() {}; public void anonymousEx() { try { @@ -129,4 +129,4 @@ public int compare(String o1, String o2) private static final long serialVersionUID = 1L; -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsAnotherClassName.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheckAnotherClassName.java similarity index 85% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsAnotherClassName.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheckAnotherClassName.java index 4ee7254b53..f580daa63b 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsAnotherClassName.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputForbidThrowAnonymousExceptionsCheckAnotherClassName.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputForbidThrowAnonymousExceptionsAnotherClassName { +public class InputForbidThrowAnonymousExceptionsCheckAnotherClassName { ExceptionBlablabla someException = new ExceptionBlablabla() {}; @@ -17,4 +17,4 @@ private void anonException() throws ExceptionBlablabla { private class ExceptionBlablabla extends Exception { } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchCheck.java deleted file mode 100755 index 9403d5f1ce..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchCheck.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputIllegalCatchCheck { - public void foo() { - try { - } catch (RuntimeException e) { - } catch (Exception e) { - } catch (Throwable e) { - } - } - - public void bar() { - try { - } catch (java.lang.RuntimeException e) { - } catch (java.lang.Exception e) { - } catch (java.lang.Throwable e) { - } - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchCheckNew.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchExtendedCheckNew.java similarity index 94% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchCheckNew.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchExtendedCheckNew.java index 1fe733fd02..8194337fb3 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchCheckNew.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputIllegalCatchExtendedCheckNew.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputIllegalCatchCheckNew +public class InputIllegalCatchExtendedCheckNew { public void foo() { @@ -44,4 +44,4 @@ public void bar() } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputLogicConditionsNeedOptimizationCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputLogicConditionNeedOptimizationCheck.java similarity index 67% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputLogicConditionsNeedOptimizationCheck.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputLogicConditionNeedOptimizationCheck.java index f0717fca01..4c076bd784 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputLogicConditionsNeedOptimizationCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputLogicConditionNeedOptimizationCheck.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputLogicConditionsNeedOptimizationCheck +public class InputLogicConditionNeedOptimizationCheck { private boolean field1; @@ -93,4 +93,29 @@ private void methodInParentheses(){ found = (lst.remove(elem)) || found; found = found || (lst.remove(elem)); } + + private void instanceOf() { + String s = ""; + Object o = null; + if (("Test".equals(s)) && (o instanceof String)) {} + if ((o instanceof String)) {} + if (o==null && (o instanceof String)) {} + if ((o instanceof String) && o==null ) {} // violation + if (o==null && (o instanceof String) && o!=null) {} // violation + if (o==null && ((o instanceof String) && o!=null)) {} // violation + if (o==null && ((o instanceof String) || o!=null)) {} // violation + if (o==null && (o!=null && (o instanceof String))) {} + if (o instanceof InputLogicConditionNeedOptimizationCheck + && ((InputLogicConditionNeedOptimizationCheck) o).field1 == true) {} + if (o instanceof String && o != null && ((String) o).length() > 0) {} // violation + if (o != null && o instanceof String && ((String) o).length() > 0) {} + } + + private void complexConditions() { + String s = System.getProperty("s"); + int i = 0; + if (((s.equals("1") && (i != 1))) || + ((s.equals("2") && (i != 2)))) {} + if ("true".equals(s) || ((s.contains("test")))) {} + } } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoop.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheck.java similarity index 99% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoop.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheck.java index 07061eb5af..f3dd0a4859 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoop.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheck.java @@ -7,7 +7,7 @@ import java.util.Set; import java.util.Map.Entry; -public class InputMapIterationInForEachLoop { +public class InputMapIterationInForEachLoopCheck { Map mMap = new HashMap(); public static void main(String[] args) { Map map = new HashMap(); @@ -140,4 +140,4 @@ private static void someMethod(){ System.out.println(string); } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckExtendingMap.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckExtendingMap.java new file mode 100644 index 0000000000..b3724c1bdf --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckExtendingMap.java @@ -0,0 +1,16 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import java.util.HashMap; + +public class InputMapIterationInForEachLoopCheckExtendingMap { + public static class TestMap extends HashMap { + public void test() { + for (Entry entry : this.entrySet()) { + } + } + public void test2() { + for (Entry entry : entrySet()) { + } + } + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopImport.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckImport.java similarity index 59% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopImport.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckImport.java index 997b0f52ad..0ea17a893a 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopImport.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckImport.java @@ -1,20 +1,20 @@ package com.github.sevntu.checkstyle.checks.coding; -import com.github.sevntu.checkstyle.checks.coding.MyMap; +import com.github.sevntu.checkstyle.checks.coding.external.InputMyMap; import java.util.*; -public class InputMapIterationInForEachLoopImport +public class InputMapIterationInForEachLoopCheckImport { public static void main(String[] args) { Map map = new HashMap(); - MyMap myMap = new MyMap(); + InputMyMap myMap = new InputMyMap(); for (String key : map.keySet()) { System.out.println(key + " --> " + map.get(key)); } - for (MyMap.Entry entry : myMap.entrySet()) + for (InputMyMap.Entry entry : myMap.entrySet()) { System.out.println(entry.getValue() + " --> "); } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopSkipIf.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckSkipIf.java similarity index 84% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopSkipIf.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckSkipIf.java index f273f11c26..ce4497fbe2 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopSkipIf.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMapIterationInForEachLoopCheckSkipIf.java @@ -1,14 +1,14 @@ package com.github.sevntu.checkstyle.checks.coding; -import com.github.sevntu.checkstyle.checks.coding.MyMap; +import com.github.sevntu.checkstyle.checks.coding.external.InputMyMap; import java.util.*; import java.util.Map.Entry; -public class InputMapIterationInForEachLoopSkipIf +public class InputMapIterationInForEachLoopCheckSkipIf { public static void main(String[] args) { Map map = new HashMap(); - MyMap myMap = new MyMap(); + InputMyMap myMap = new InputMyMap(); int counter = 0; for (String key : map.keySet()) @@ -41,7 +41,7 @@ public static void main(String[] args) } } - for (MyMap.Entry entry : myMap.entrySet()) + for (InputMyMap.Entry entry : myMap.entrySet()) { System.out.println(entry.getKey()); if (entry.getValue() != "value") { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckFalsePositives.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckFalsePositives.java new file mode 100644 index 0000000000..6db2a845bb --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckFalsePositives.java @@ -0,0 +1,45 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import java.util.List; + +public class InputMoveVariableInsideIfCheckFalsePositives { + private List field; + + public void method1(List list) { + final String variable = list.remove(0); + final String next = list.get(0); + + if (next.equals("test")) { + list.add(variable); + } + } + + public void method2(List list) { + final String variable = list.remove(0); + + if (true) { + test(list.get(0)); + } + + if (true) { + list.add(variable); + } + } + + public void method3(List list) { + final String variable = field.get(0); + + modifyField(); + + if (true) { + field.add(variable); + } + } + + private void test(String string) { + } + + private void modifyField() { + test(field.remove(0)); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckNoViolations.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckNoViolations.java new file mode 100644 index 0000000000..592e8ecfc5 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckNoViolations.java @@ -0,0 +1,119 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import java.io.BufferedReader; +import java.io.FileReader; + +public class InputMoveVariableInsideIfCheckNoViolations { + String field = ""; + + public void method1() { + } + + public void method2() { + String nothing = ""; + } + + public void method3() { + for (int i = 0; i < 5; i++) { + method1(); + + if (true) { + i++; + } + } + + try (BufferedReader in = new BufferedReader(new FileReader("foo.in"))) { + method1(); + + if (true) { + in.readLine(); + } + } + catch (Exception e) { + method1(); + + if (true) { + e.getCause(); + } + } + } + + public void method4() { + String variable = ""; + + variable = variable.substring(0); + } + + public void method5() { + String variable = ""; + + variable = variable.substring(0); + + if (true) { + variable = variable.substring(0); + } + } + + public void method6() { + String variable = ""; + + if (variable.contains("a")) { + method1(); + } + } + + public void method7() { + String variable = ""; + + if (true) { + variable = variable.substring(0); + } + else { + variable = variable.substring(0); + } + } + + public void method8() { + String variable = ""; + + if (true) { + method1(); + } + else if (true) { + variable = variable.substring(0); + } + else { + variable = variable.substring(0); + } + } + + public void method9() { + String variable = ""; + + if (true) { + variable = variable.substring(0); + } + + if (true) { + variable = variable.substring(0); + } + } + + public void method10() { + String variable = ""; + + for (int i = 0; i < 10; i++) { + variable = variable.substring(0); + } + } + + public void method11() { + String variable = ""; + + for (int i = 0; i < 10; i++) { + if (true) { + variable = variable.substring(0); + } + } + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckViolations.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckViolations.java new file mode 100644 index 0000000000..e909e5f0d5 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMoveVariableInsideIfCheckViolations.java @@ -0,0 +1,51 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputMoveVariableInsideIfCheckViolations { + public void method1() { + String variable = ""; + + if (true) { + variable = variable.substring(0); + } + } + + public void method2() { + String variable = ""; + + if (true) { + variable = variable.substring(0); + } + else { + method1(); + } + } + + public void method3() { + String variable = ""; + + if (true) + variable = variable.substring(0); + else + method1(); + } + + public void method4() { + String variable = ""; + + if (true) { + method1(); + } + else { + variable = variable.substring(0); + } + } + + public void method5() { + String variable = ""; + + if (true) + method1(); + else + variable = variable.substring(0); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleStringLiterals.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleStringLiteralsExtendedCheck.java old mode 100755 new mode 100644 similarity index 93% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleStringLiterals.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleStringLiteralsExtendedCheck.java index 5ff3917a47..31f281024e --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleStringLiterals.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleStringLiteralsExtendedCheck.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputMultipleStringLiterals +public class InputMultipleStringLiteralsExtendedCheck { String m = "StringContents"; String m1 = "SingleString"; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleVariableDeclarations.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleVariableDeclarationsExtendedCheck.java similarity index 80% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleVariableDeclarations.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleVariableDeclarationsExtendedCheck.java index 3374445d4d..a83593a2e9 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleVariableDeclarations.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputMultipleVariableDeclarationsExtendedCheck.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputMultipleVariableDeclarations { +public class InputMultipleVariableDeclarationsExtendedCheck { int i, j; int i1; int j1; @@ -19,5 +19,9 @@ void method1() { void method2() { for (int i=0, j=0; i < 10; i++, j--) { } + switch("") { + case "6": + int k = 7; + } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck1.java similarity index 84% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest1.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck1.java index 3e9498948d..fe983b711f 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest1.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck1.java @@ -6,7 +6,7 @@ import org.junit.runners.Suite.SuiteClasses; -public class InputNameConventionForTest1 +public class InputNameConventionForJunit4TestClassesCheck1 { @RunWith(Suite.class) diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck2.java similarity index 79% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck2.java index f597a5ae81..b058081def 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck2.java @@ -3,7 +3,7 @@ import org.junit.Test; import org.junit.runner.RunWith; -public class InputNameConventionForTest2 +public class InputNameConventionForJunit4TestClassesCheck2 { public class InnerTestClass { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck3.java similarity index 81% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest3.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck3.java index 02e56d2d6e..8688bc6210 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest3.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck3.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputNameConventionForTest3 +public class InputNameConventionForJunit4TestClassesCheck3 { public class InnerNotTestClass { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest4.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck4.java similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest4.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck4.java index 7ed343c7ab..5e2b448f9c 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest4.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck4.java @@ -2,7 +2,7 @@ import org.junit.Test; -public class InputNameConventionForTest4 +public class InputNameConventionForJunit4TestClassesCheck4 { public class NestedNotTestClass { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest5.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck5.java similarity index 79% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest5.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck5.java index 41c030b4b0..3fd34cf32c 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest5.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck5.java @@ -3,7 +3,7 @@ import java.awt.Component; import java.io.IOException; -public class InputNameConventionForTest5 +public class InputNameConventionForJunit4TestClassesCheck5 { public class InnerTestClass { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest6.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck6.java similarity index 73% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest6.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck6.java index f18eb6b656..a2b251061a 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest6.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck6.java @@ -1,7 +1,7 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputNameConventionForTest6 +public class InputNameConventionForJunit4TestClassesCheck6 { @SomeTestAnnotation public class InnerTestClass @@ -13,4 +13,4 @@ public class InnerTestClass @interface SomeTestAnnotation { -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest7.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck7.java similarity index 79% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest7.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck7.java index 17c31b8510..eaf82c4137 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest7.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck7.java @@ -1,7 +1,7 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputNameConventionForTest7 +public class InputNameConventionForJunit4TestClassesCheck7 { public class InnerTestClass { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest8.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck8.java similarity index 68% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest8.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck8.java index c2923a69bf..71f558ff2c 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForTest8.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNameConventionForJunit4TestClassesCheck8.java @@ -2,7 +2,7 @@ import org.junit.Test; -public class InputNameConventionForTest8 +public class InputNameConventionForJunit4TestClassesCheck8 { @Test public void test() diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNoNullForCollectionReturnCheckConstructor.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNoNullForCollectionReturnCheckConstructor.java new file mode 100644 index 0000000000..753c63b4e6 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNoNullForCollectionReturnCheckConstructor.java @@ -0,0 +1,13 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputNoNullForCollectionReturnCheckConstructor { + public String[] method() { + return null; + } + + InputNoNullForCollectionReturnCheckConstructor() { + if (true) { + return; + } + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck.java similarity index 98% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck.java index d04cf9e4d9..c869e4b8e1 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputNumericLiteralNeedUnderscoreCheck { +public class InputNumericLiteralNeedsUnderscoreCheck { public void goodNumericLiterals() { int goodInt1 = 1234; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck2.java similarity index 98% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck2.java index bcef7dd957..9111ae10bd 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedUnderscoreCheck2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputNumericLiteralNeedsUnderscoreCheck2.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputNumericLiteralNeedUnderscoreCheck2 { +public class InputNumericLiteralNeedsUnderscoreCheck2 { public void goodNumericLiterals() { int goodInt1 = 12; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck1.java similarity index 92% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor1.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck1.java index 505ce5ea0a..0d92ad3bc9 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor1.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck1.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor1 { +public class InputOverridableMethodInConstructorCheck1 { public static void main(String[] args) { @@ -31,4 +31,4 @@ public void overrideMe() { new Child1(999); // will not print x =) } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor10.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck10.java similarity index 88% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor10.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck10.java index 387799b021..b686322bf2 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor10.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck10.java @@ -8,7 +8,7 @@ import java.io.ObjectOutputStream; import java.io.Serializable; -public class InputOverridableMethodInConstructor10 { +public class InputOverridableMethodInConstructorCheck10 { public static void main(String args[]) throws IOException, ClassNotFoundException { @@ -38,7 +38,7 @@ private void doSmth() { } - static class Object2 extends com.github.sevntu.checkstyle.checks.coding.InputOverridableMethodInConstructor10.Object1 implements java.io.Serializable { + static class Object2 extends com.github.sevntu.checkstyle.checks.coding.InputOverridableMethodInConstructorCheck10.Object1 implements java.io.Serializable { String value; @@ -53,4 +53,4 @@ public void readObject(java.io.ObjectInputStream in)throws IOException, ClassNot } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor11.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck11.java similarity index 95% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor11.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck11.java index f42ab2c028..77b02d82a6 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor11.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck11.java @@ -8,7 +8,7 @@ import java.io.ObjectOutputStream; import java.io.Serializable; -public class InputOverridableMethodInConstructor11 { +public class InputOverridableMethodInConstructorCheck11 { public static void main(String args[]) throws IOException, ClassNotFoundException { @@ -52,4 +52,4 @@ public void readObject(java.io.ObjectInputStream in)throws IOException, ClassNot } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor12.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck12.java similarity index 97% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor12.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck12.java index 1413a8253e..b0517203c6 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor12.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck12.java @@ -6,7 +6,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -public class InputOverridableMethodInConstructor12 { +public class InputOverridableMethodInConstructorCheck12 { public static void main(String args[]) throws IOException, ClassNotFoundException { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor13.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck13.java similarity index 96% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor13.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck13.java index 6f03fa5d5f..1b8be6ffaa 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor13.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck13.java @@ -6,7 +6,7 @@ import javax.xml.crypto.Data; -public class InputOverridableMethodInConstructor13 { +public class InputOverridableMethodInConstructorCheck13 { public static void main(String args[]) throws IOException, ClassNotFoundException, CloneNotSupportedException { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor14.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck14.java similarity index 97% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor14.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck14.java index 8845ea563e..0ee08e62d3 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor14.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck14.java @@ -8,7 +8,7 @@ import java.io.ObjectOutputStream; import java.io.Serializable; -public class InputOverridableMethodInConstructor14 { +public class InputOverridableMethodInConstructorCheck14 { public static void main(String args[]) throws IOException, ClassNotFoundException { @@ -84,4 +84,4 @@ public void readObject(java.io.ObjectInputStream in)throws IOException, ClassNot } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor15.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck15.java similarity index 95% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor15.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck15.java index cc1b229abd..039cf01f42 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor15.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck15.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor15 { +public class InputOverridableMethodInConstructorCheck15 { public static void main(String[] args) { @@ -47,4 +47,4 @@ public void overrideMe() { new Child1(999); // will not print x =) } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor16.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck16.java similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor16.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck16.java index ad100214aa..6957397d93 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor16.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck16.java @@ -8,7 +8,7 @@ import java.io.ObjectOutputStream; import java.io.Serializable; -public class InputOverridableMethodInConstructor16 { +public class InputOverridableMethodInConstructorCheck16 { private class Object1 implements Serializable { @@ -26,4 +26,4 @@ public final void doSmth(String value) { } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor17.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck17.java similarity index 92% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor17.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck17.java index 354b2fd0ac..3288d0b1e1 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor17.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck17.java @@ -8,7 +8,7 @@ import java.io.ObjectOutputStream; import java.io.Serializable; -public class InputOverridableMethodInConstructor17 { +public class InputOverridableMethodInConstructorCheck17 { private class Object1 implements Serializable { @@ -33,4 +33,4 @@ public void readObject(java.io.ObjectInputStream in) throws IOException, ClassNo } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor18.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck18.java similarity index 88% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor18.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck18.java index d9fda58fe9..b7b59a3682 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor18.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck18.java @@ -4,7 +4,7 @@ import com.puppycrawl.tools.checkstyle.gui.Main; -public class InputOverridableMethodInConstructor18 { +public class InputOverridableMethodInConstructorCheck18 { private class Object1 implements Serializable { @@ -22,4 +22,4 @@ private void registerColumnType(int i, String string) { } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor19.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck19.java similarity index 92% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor19.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck19.java index 772ea72e6e..a2ff757516 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor19.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck19.java @@ -30,12 +30,12 @@ * * @author Gavin King */ -public abstract class InputOverridableMethodInConstructor19 { +public abstract class InputOverridableMethodInConstructorCheck19 { private String persister; private Object alias; - public InputOverridableMethodInConstructor19( + public InputOverridableMethodInConstructorCheck19( String persister, String factory, String loadQueryInfluencers, diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck2.java old mode 100755 new mode 100644 similarity index 95% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck2.java index 074cfc0fce..ad3ed4f8f7 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck2.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor2 { +public class InputOverridableMethodInConstructorCheck2 { public static void main(String[] args) { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor20.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck20.java similarity index 64% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor20.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck20.java index ff5e26c476..825670b265 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor20.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck20.java @@ -1,7 +1,7 @@ package com.github.sevntu.checkstyle.checks.coding; -public interface InputOverridableMethodInConstructor20 { +public interface InputOverridableMethodInConstructorCheck20 { Object readObject(Object obj, String name, Object oldValue); -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor21.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck21.java similarity index 63% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor21.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck21.java index 13fb7a49ea..69360d805b 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor21.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck21.java @@ -1,7 +1,7 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor21 { +public class InputOverridableMethodInConstructorCheck21 { - public InputOverridableMethodInConstructor21() { + public InputOverridableMethodInConstructorCheck21() { doSmth(); } @@ -17,4 +17,4 @@ private void doSmth3() { doSmth(); } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor22.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck22.java similarity index 74% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor22.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck22.java index 7bc8fc6335..afd078f438 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor22.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck22.java @@ -1,7 +1,7 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor22 { +public class InputOverridableMethodInConstructorCheck22 { - InputOverridableMethodInConstructor22() { + InputOverridableMethodInConstructorCheck22() { doSMTH(); // a warning here! } @@ -25,4 +25,4 @@ private void doSMTH4() { public void doPublic() { } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor23.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck23.java similarity index 96% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor23.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck23.java index 884543c915..922d09b303 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor23.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck23.java @@ -12,10 +12,10 @@ * * @author Emmanuel Bernard */ -public class InputOverridableMethodInConstructor23 { +public class InputOverridableMethodInConstructorCheck23 { private Set associations; - public InputOverridableMethodInConstructor23( + public InputOverridableMethodInConstructorCheck23( String[] persister, HashMap> associationsPerEntityPersister, String factory) { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor24.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck24.java similarity index 60% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor24.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck24.java index fab44088bf..cd1a56735c 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor24.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck24.java @@ -2,11 +2,11 @@ import java.lang.reflect.Method; import java.util.Iterator; -public abstract class InputOverridableMethodInConstructor24 { +public abstract class InputOverridableMethodInConstructorCheck24 { protected abstract String buildGetter(String component, String prop); - protected InputOverridableMethodInConstructor24(String component, String prop) { + protected InputOverridableMethodInConstructorCheck24(String component, String prop) { buildGetter(component, prop); diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor25.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck25.java similarity index 69% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor25.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck25.java index 37d0196dd0..66fe7b3599 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor25.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck25.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor25 { +public class InputOverridableMethodInConstructorCheck25 { final class A { A() { @@ -7,4 +7,4 @@ final class A { } void doSmth() {} } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor26.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck26.java similarity index 87% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor26.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck26.java index 4dce70dec5..d8d74399cd 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor26.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck26.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor26 +public class InputOverridableMethodInConstructorCheck26 { class ULCWorkbenchPartSite diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor27.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck27.java similarity index 91% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor27.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck27.java index 3849feb1cc..5b5fdaeeae 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor27.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck27.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor27 +public class InputOverridableMethodInConstructorCheck27 { public static void main(String[] args) @@ -44,7 +44,7 @@ class Child27 extends Base27 void init() { - System.out.println("Overrriden init"); + System.out.println("Overridden init"); } void overrideMe(String aString) diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck28.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck28.java new file mode 100644 index 0000000000..2ff8af232c --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck28.java @@ -0,0 +1,19 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import java.io.IOException; + +public class InputOverridableMethodInConstructorCheck28 { + class InputStream extends java.io.InputStream { + InputStream() { + method(); + } + + @Override + public int read() throws IOException { + return 0; + } + } + + public void method() { + }; +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck3.java old mode 100755 new mode 100644 similarity index 94% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor3.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck3.java index 9194b32e0e..88791d41d8 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor3.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck3.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor3 { +public class InputOverridableMethodInConstructorCheck3 { public static void main(String[] args) { @@ -37,4 +37,4 @@ public void overrideMe() { new Child3(999); // will print "0" } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor4.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck4.java old mode 100755 new mode 100644 similarity index 95% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor4.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck4.java index f2ba4a9446..dbcca08b92 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor4.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck4.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor4 { +public class InputOverridableMethodInConstructorCheck4 { public static void main(String[] args) { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor5.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck5.java old mode 100755 new mode 100644 similarity index 96% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor5.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck5.java index 46274ffa9c..aba0375b55 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor5.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck5.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputOverridableMethodInConstructor5 { +public class InputOverridableMethodInConstructorCheck5 { public static void main(String[] args) { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor6.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck6.java old mode 100755 new mode 100644 similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor6.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck6.java index ea617d6abb..d4a05a3902 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor6.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck6.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; import java.io.IOException; -public class InputOverridableMethodInConstructor6 { +public class InputOverridableMethodInConstructorCheck6 { public static void main(String args[]) throws IOException, ClassNotFoundException, CloneNotSupportedException { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor7.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck7.java old mode 100755 new mode 100644 similarity index 93% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor7.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck7.java index 2ffa0258f2..62d2b286c2 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor7.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck7.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; import java.io.IOException; -public class InputOverridableMethodInConstructor7 { +public class InputOverridableMethodInConstructorCheck7 { public static void main(String args[]) throws IOException, ClassNotFoundException, CloneNotSupportedException { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor8.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck8.java old mode 100755 new mode 100644 similarity index 93% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor8.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck8.java index a351c92cd5..186a983e11 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor8.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck8.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; import java.io.IOException; -public class InputOverridableMethodInConstructor8 { +public class InputOverridableMethodInConstructorCheck8 { public static void main(String args[]) throws IOException, ClassNotFoundException, CloneNotSupportedException { @@ -38,4 +38,4 @@ public Object clone() throws CloneNotSupportedException { return clone; } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor9.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck9.java similarity index 94% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor9.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck9.java index 2047ef7ddf..0bd8c5a5e3 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructor9.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputOverridableMethodInConstructorCheck9.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; import java.io.IOException; -public class InputOverridableMethodInConstructor9 { +public class InputOverridableMethodInConstructorCheck9 { public static void main(String args[]) throws IOException, ClassNotFoundException, CloneNotSupportedException { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturn.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheck.java similarity index 94% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturn.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheck.java index 38e658712f..d401ce7b2f 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturn.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheck.java @@ -1,16 +1,16 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputRedundantReturn { +public class InputRedundantReturnCheck { /** * @param args */ - public InputRedundantReturn(){ + public InputRedundantReturnCheck(){ //allowed/not empty c-tor return; //WARNING if option 'allowReturnInEmptyMethodsAndConstructors' is off }//c-tor - public InputRedundantReturn(String s){ + public InputRedundantReturnCheck(String s){ //non empty constructor boolean b = true; b = b ? true: false; @@ -166,7 +166,7 @@ public void setFormats3() { public int getRandomNumber() { return 4; } - public InputRedundantReturn(double content) { + public InputRedundantReturnCheck(double content) { } public void setFormat() { @@ -195,4 +195,4 @@ private static void foo1() { } } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnFalsePositive.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckFalsePositive.java similarity index 91% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnFalsePositive.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckFalsePositive.java index 3fcdcd51b7..e868da31fd 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnFalsePositive.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckFalsePositive.java @@ -2,9 +2,9 @@ import java.util.StringTokenizer; -public class InputRedundantReturnFalsePositive +public class InputRedundantReturnCheckFalsePositive { - public InputRedundantReturnFalsePositive(String text) { + public InputRedundantReturnCheckFalsePositive(String text) { try { StringTokenizer toks = new StringTokenizer(text, ";\n\r"); while (toks.hasMoreTokens()) { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckMethodInEmptyMethod.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckMethodInEmptyMethod.java new file mode 100644 index 0000000000..28356f5420 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckMethodInEmptyMethod.java @@ -0,0 +1,11 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputRedundantReturnCheckMethodInEmptyMethod { + public native void method(); +} +abstract class InputRedundantReturnCheckMethodInEmptyMethod2 { + public abstract void method(); +} +interface InputRedundantReturnCheckMethodInEmptyMethod3 { + void method(); +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnMethodInInterface.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckMethodInInterface.java similarity index 60% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnMethodInInterface.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckMethodInInterface.java index 3155c125cd..8bce668d40 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnMethodInInterface.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckMethodInInterface.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public interface InputRedundantReturnMethodInInterface +public interface InputRedundantReturnCheckMethodInInterface { void applyContent(String content); } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckNestedMethods.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckNestedMethods.java new file mode 100644 index 0000000000..1913d61281 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRedundantReturnCheckNestedMethods.java @@ -0,0 +1,41 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputRedundantReturnCheckNestedMethods { + public void method() { + try { + if (true) { + new Nested() { + @Override + public boolean accept(String s) { + return true; + } + }; + } + } + catch (Exception ex) { + } + finally { + } + } + + public void method2() { + try { + if (new Nested() { + @Override + public boolean accept(String s) { + return true; + } + }.accept(null)) { + return; // violation + } + } + catch (Exception ex) { + } + finally { + } + } + + public abstract class Nested { + public abstract boolean accept(String s); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck1.java new file mode 100644 index 0000000000..e262e3ab80 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck1.java @@ -0,0 +1,48 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class InputRequireFailForTryCatchInJunitCheck1 { + static { + } + + static { + try { + } + catch (Exception e) { + } + } + + public void method1() { + } + + public void method2() { + try { + } + catch (Exception e) { + } + } + + @Test + public void method3() { + } + + @Test + public void method4() throws Exception { + try { + } + finally { + } + try (MyAutoClosable test = new MyAutoClosable()) { + test.close(); + } + } +} + +class MyAutoClosable implements AutoCloseable { + @Override + public void close() throws Exception { + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck2.java new file mode 100644 index 0000000000..d502eb6171 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck2.java @@ -0,0 +1,14 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputRequireFailForTryCatchInJunitCheck2 { + @Test + public void method() { + try { + } + catch (Exception e) { + } + } +} + +@interface Test { +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck3.java new file mode 100644 index 0000000000..b2cc1c7ae6 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck3.java @@ -0,0 +1,94 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import org.junit.Test; + +public class InputRequireFailForTryCatchInJunitCheck3 { + @Test + public void method1() throws Exception { + try { + } + catch (Exception e) { + } + try { + for (int a = 0; a < 5; a++) { + } + } + catch (Exception e) { + } + try { + method1(); + } + catch (Exception e) { + } + try { + InputRequireFailForTryCatchInJunitCheck3.method(); + } + catch (Exception e) { + } + try { + fail("message"); + } + catch (Exception e) { + } + try { + Assert.fail("message"); + } + catch (Exception e) { + } + } + + @org.junit.Test + public void method2() throws Exception { + try { + } + catch (Exception e) { + } + try { + for (int a = 0; a < 5; a++) { + } + } + catch (Exception e) { + } + try { + method2(); + } + catch (Exception e) { + } + try { + InputRequireFailForTryCatchInJunitCheck3.method(); + } + catch (Exception e) { + } + try { + fail("message"); + } + catch (Exception e) { + } + try { + Assert.fail("message"); + } + catch (Exception e) { + } + } + + @Test + public void method3() throws Exception { + try { + int a = 0; + a++; + } + catch (Exception e) { + } + } + + public static void method() { + } + + public static void fail(String s) { + } + + public static class Assert { + public static void fail(String s) { + } + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck4.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck4.java new file mode 100644 index 0000000000..36fd214de7 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck4.java @@ -0,0 +1,25 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import org.junit.Assert; +import org.junit.Test; + +public class InputRequireFailForTryCatchInJunitCheck4 { + @Test + public void method1() throws Exception { + try { + Assert.assertEquals("", ""); + } + catch (Exception e) { + } + try { + Dummy.fail(); + } + catch (Exception e) { + } + } + + public static class Dummy { + public static void fail() { + } + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck5.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck5.java new file mode 100644 index 0000000000..47cc619ec1 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputRequireFailForTryCatchInJunitCheck5.java @@ -0,0 +1,58 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import static org.junit.Assert.fail; + +import java.util.function.Consumer; + +import org.junit.Assert; +import org.junit.Test; + +public class InputRequireFailForTryCatchInJunitCheck5 { + @Test + public void method1() throws Exception { + try { + Assert.fail(); + } + catch (Exception e) { + } + try { + fail(); + } + catch (Exception e) { + } + + final Consumer test = ast -> { + try { + } + catch (Exception e) { + // fail can't be required because lambdas can't throw checked + // exceptions, so they must be caught and if warranted, + // re-thrown as an unchecked exception + } + }; + } + + @org.junit.Test + public void method2() throws Exception { + try { + Assert.fail(); + } + catch (Exception e) { + } + try { + fail(); + } + catch (Exception e) { + } + + final Consumer test = ast -> { + try { + } + catch (Exception e) { + // fail can't be required because lambdas can't throw checked + // exceptions, so they must be caught and if warranted, + // re-thrown as an unchecked exception + } + }; + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnBooleanFromTernary.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnBooleanFromTernaryCheck.java similarity index 71% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnBooleanFromTernary.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnBooleanFromTernaryCheck.java index 921c580fd1..d2453b217d 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnBooleanFromTernary.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnBooleanFromTernaryCheck.java @@ -1,12 +1,14 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputReturnBooleanFromTernary{ +public class InputReturnBooleanFromTernaryCheck{ public void logged() { boolean i1 = true ? false : true; Object i2 = (2 == 2) ? 1 : true; Object i3 = (2 == 2) ? false : 1; boolean i4 = true ? false ? true : true : true; + boolean i5 = false ? true : false; + boolean i6 = true ? true : i1; } public void notLogged() { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnCountExtendedCheckAnonymousClasses.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnCountExtendedCheckAnonymousClasses.java new file mode 100644 index 0000000000..e60b766dec --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnCountExtendedCheckAnonymousClasses.java @@ -0,0 +1,29 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputReturnCountExtendedCheckAnonymousClasses { + public int method() { + class InnerClass { + public int method() { + return 1; + } + } + + return 1; + } + + public int method2() { + class InnerClass { + public int method2() { + if (false) + return 0; + + return 1; + } + } + + if (false) + return 0; + + return 1; + } +} \ No newline at end of file diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnCountExtendedCheckLambdas.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnCountExtendedCheckLambdas.java new file mode 100644 index 0000000000..cdcc47e103 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnCountExtendedCheckLambdas.java @@ -0,0 +1,60 @@ +package com.github.sevntu.checkstyle.checks.coding; + +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.function.Supplier; + +public class InputReturnCountExtendedCheckLambdas { + Runnable fieldWithOneReturnInLambda = () -> { + return; + }; + + Callable fieldWithTwoReturnInLambda = () -> { + if (hashCode() == 0) return 0; + else return 1; + }; + + Optional methodWithOneReturnInLambda() { + return Optional.of(hashCode()).filter(i -> { + return i > 0; + }); + } + + Optional methodWithTwoReturnInLambda() { + return Optional.of(hashCode()).filter(i -> { + if (i > 0) return true; + else return false; + }); + } + + Optional methodWithThreeReturnInLambda(int number) { + return Optional.of(number).map(i -> { + if (i == 42) return true; + else if (i == 7) return true; + else return false; + }); + } + + int methodWithTwoReturnWithLambdas(final int number) { + if (hashCode() > 0) { + new Thread( + () -> { + } + ).start(); + return number; + } else { + return Optional.of(hashCode()).orElseGet(() -> { + if (number > 0) return number; + else return 0; + }); + } + } + + Supplier> methodWithOneReturnPerLambda() { + return () -> { + return () -> { + return 1; + }; + }; + } +} \ No newline at end of file diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnNullInsteadOfBoolean.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnNullInsteadOfBooleanCheck.java similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnNullInsteadOfBoolean.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnNullInsteadOfBooleanCheck.java index 3cb5513323..69096d6a8e 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnNullInsteadOfBoolean.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputReturnNullInsteadOfBooleanCheck.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputReturnNullInsteadOfBoolean{ +public class InputReturnNullInsteadOfBooleanCheck{ public Boolean test1() { int i = 1; @@ -25,7 +25,7 @@ public Boolean testMethod(){ }; } - public InputReturnNullInsteadOfBoolean(){ + public InputReturnNullInsteadOfBooleanCheck(){ return; //here was NPE once apon a time } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation.java deleted file mode 100644 index 19accf0549..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; -public class InputSimpleAccessorNameNotation { - private int mFirst; - private int mSecond; - private int mA; - private int preB; - public void setFirs(int k){ - mFirst=k; - } - public int getFir(){ - return this.mFirst; - } - public void setSec(int k){ - this.mSecond=k; - } - public int getSec(){ - return mSecond; - } - public void setAa(int k){ - k=mA; - } - public int getAa(int k){ - return k; - } - public void setB(int k){ - this.preB=k; - } - public int getB(){ - return preB; - } - public void setFirst(int mFirst){ - this.mFirst = mFirst; - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck.java new file mode 100644 index 0000000000..f428b4500c --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck.java @@ -0,0 +1,87 @@ +package com.github.sevntu.checkstyle.checks.coding; +public class InputSimpleAccessorNameNotationCheck { + private int mFirst; + private int mSecond; + private int mA; + private int preB; + public void setFirs(int k){ + mFirst=k; + } + public int getFir(){ + return this.mFirst; + } + public void setSec(int k){ + this.mSecond=k; + } + public int getSec(){ + return mSecond; + } + public void setAa(int k){ + k=mA; + } + public int getAa(int k){ + return k; + } + public void setB(int k){ + this.preB=k; + } + public int getB(){ + return preB; + } + public void setFirst(int mFirst){ + this.mFirst = mFirst; + } + public int setFirstAgain(int mFirst){ + this.mFirst = mFirst; + return mFirst; + } + public void setTest(int mFirst){ + } + public void setTest2(int mFirst){ + setTest(mFirst); + } + private java.util.List names; + public void setNames(String[] names) { + this.names = java.util.Arrays.asList(names); + } + public void setNamesTwo(String[] names) { + if (names == null) + this.names = null; + if (names != null) + this.names = null; + } + boolean isExpiredToken() { + return ((System.currentTimeMillis() - 0) >= 0); + } + public static boolean isTrue() { + return Boolean.TRUE; + } + private int colors[]; + private void setColor(int color) { + colors[0] = color; + } + private Object object; + public void setInvocation(Object invocation) { + this.object = ((Object)invocation); + } + public void setObject(Object object, Object ignore) { + object = object; + } + public static java.util.function.BinaryOperator getTest() { + return (t1, t2) -> { + throw new IllegalStateException(); + }; + } + int getTest2() { + return ((java.util.Hashtable[]) object).length; + } + private static Object sfield; + public void setTest3(int test) throws Exception { + InputSimpleAccessorNameNotationCheck.sfield = sfield; + } +} +interface InnerIterface { + default void getFoo() { + return; + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck1.java similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation1.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck1.java index 3b02a33f32..40dd1577b3 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation1.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck1.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputSimpleAccessorNameNotation1 +public class InputSimpleAccessorNameNotationCheck1 { private String field1; private int mField2; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck2.java similarity index 94% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck2.java index 52bb9bc169..f62544083c 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck2.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputSimpleAccessorNameNotation2 +public class InputSimpleAccessorNameNotationCheck2 { private String field1; private int field2; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck3.java similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation3.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck3.java index 5ff459c584..db1e7ac9ff 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation3.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck3.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputSimpleAccessorNameNotation3 +public class InputSimpleAccessorNameNotationCheck3 { private String field1; private int mField2; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation4.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck4.java similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation4.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck4.java index 84ccbe0749..4ca280db5a 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation4.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck4.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputSimpleAccessorNameNotation4 +public class InputSimpleAccessorNameNotationCheck4 { private String field1; private int mField2; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation5.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck5.java similarity index 92% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation5.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck5.java index f99e9c7bb9..50e0c34bb3 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation5.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck5.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputSimpleAccessorNameNotation5 +public class InputSimpleAccessorNameNotationCheck5 { private boolean field1; private boolean field2; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation6.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck6.java similarity index 88% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation6.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck6.java index 904ff02f1d..436c317ba4 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation6.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck6.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputSimpleAccessorNameNotation6 +public class InputSimpleAccessorNameNotationCheck6 { public static void updateCheckSum(final String metadataFile, String metadataFileSum, String hashFunction) diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation7.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck7.java similarity index 58% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation7.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck7.java index 2af00e7da3..f44d4ee20c 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotation7.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputSimpleAccessorNameNotationCheck7.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public interface InputSimpleAccessorNameNotation7 +public interface InputSimpleAccessorNameNotationCheck7 { String getSmth(); } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParentheses.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheck.java old mode 100755 new mode 100644 similarity index 97% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParentheses.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheck.java index 580f47a4e3..fd8bab2ce4 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParentheses.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheck.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputUnnecessaryParentheses { +public class InputUnnecessaryParenthesesExtendedCheck { int f1() { int x = 0; for (int i = (0+1); ((i) < (6+6)); i += (1+0)) { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/Input15Extensions.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheck2.java old mode 100755 new mode 100644 similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/Input15Extensions.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheck2.java index 7e27230792..dfffb0671a --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/Input15Extensions.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheck2.java @@ -6,7 +6,7 @@ } @MyAnnotation1(name = "ABC", version = 1) -public class Input15Extensions +public class InputUnnecessaryParenthesesExtendedCheck2 { } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesUbv.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheckUbv.java similarity index 94% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesUbv.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheckUbv.java index 31c31c4bb1..f2a1707bbc 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesUbv.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUnnecessaryParenthesesExtendedCheckUbv.java @@ -1,5 +1,5 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputUnnecessaryParenthesesUbv { +public class InputUnnecessaryParenthesesExtendedCheckUbv { int f1() { int x = 0; for (int i = (0+1); ((i) < (6+6)); i += (1+0)) { @@ -119,6 +119,10 @@ boolean test (int y, boolean flag, TypeA x) { return (flag != b); } } + void f8() { + for (int i = 1; ((i) == (6+6)); i += 1) { + } + } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall1.java deleted file mode 100644 index 6bec1fd301..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall1.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputUselessSuperCtorCall1 -{ - public InputUselessSuperCtorCall1() - { - super(); - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall2.java deleted file mode 100644 index aee4f08b37..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall2.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputUselessSuperCtorCall2 extends java.lang.Object -{ - public InputUselessSuperCtorCall2() - { - super(); - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall3.java deleted file mode 100644 index 1690147724..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall3.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputUselessSuperCtorCall3 -{ - public InputUselessSuperCtorCall3() - { - super(); - } - - public InputUselessSuperCtorCall3(int i) - { - super(); - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall6.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall6.java deleted file mode 100644 index f9f8776654..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall6.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.github.sevntu.checkstyle.checks.coding; - -public class InputUselessSuperCtorCall6 extends java.lang.Object -{ - public InputUselessSuperCtorCall6() { - super(); - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck1.java new file mode 100644 index 0000000000..d83a4bdd53 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck1.java @@ -0,0 +1,9 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputUselessSuperCtorCallCheck1 +{ + public InputUselessSuperCtorCallCheck1() + { + super(); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck2.java new file mode 100644 index 0000000000..e3b5db6103 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck2.java @@ -0,0 +1,9 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputUselessSuperCtorCallCheck2 extends java.lang.Object +{ + public InputUselessSuperCtorCallCheck2() + { + super(); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck3.java new file mode 100644 index 0000000000..cca876ca9f --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck3.java @@ -0,0 +1,14 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputUselessSuperCtorCallCheck3 +{ + public InputUselessSuperCtorCallCheck3() + { + super(); + } + + public InputUselessSuperCtorCallCheck3(int i) + { + super(); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall4.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck4.java similarity index 69% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall4.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck4.java index fca2f2f4e6..c17ca27c7a 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall4.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck4.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputUselessSuperCtorCall4 extends java.lang.Object +public class InputUselessSuperCtorCallCheck4 extends java.lang.Object { public class Inner { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall5.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck5.java similarity index 88% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall5.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck5.java index 88b10c0020..e822d2ebfe 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall5.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck5.java @@ -3,7 +3,7 @@ import java.io.File; import java.io.PrintWriter; -public class InputUselessSuperCtorCall5 +public class InputUselessSuperCtorCallCheck5 { private static class Base { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck6.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck6.java new file mode 100644 index 0000000000..6dd096ce84 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck6.java @@ -0,0 +1,8 @@ +package com.github.sevntu.checkstyle.checks.coding; + +public class InputUselessSuperCtorCallCheck6 extends java.lang.Object +{ + public InputUselessSuperCtorCallCheck6() { + super(); + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall7.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck7.java similarity index 92% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall7.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck7.java index 1b32c0044f..bebe958384 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCall7.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputUselessSuperCtorCallCheck7.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputUselessSuperCtorCall7 +public class InputUselessSuperCtorCallCheck7 { class Base { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputWhitespaceBeforeArrayIntializer.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputWhitespaceBeforeArrayInitializerCheck.java similarity index 93% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputWhitespaceBeforeArrayIntializer.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputWhitespaceBeforeArrayInitializerCheck.java index b56fa76b7f..cec4281504 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputWhitespaceBeforeArrayIntializer.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/InputWhitespaceBeforeArrayInitializerCheck.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.coding; -public class InputWhitespaceBeforeArrayIntializer { +public class InputWhitespaceBeforeArrayInitializerCheck { public void check(String[] args) { calculate(new int[]{1,2,3,4}); int[] ints0 = {1,2,3,4}; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/MyMap.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/external/InputMyMap.java similarity index 87% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/MyMap.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/external/InputMyMap.java index b8ac165500..822b218737 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/MyMap.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/coding/external/InputMyMap.java @@ -1,10 +1,10 @@ -package com.github.sevntu.checkstyle.checks.coding; +package com.github.sevntu.checkstyle.checks.coding.external; import java.util.Collection; import java.util.Map; import java.util.Iterator; import java.util.Set; -public class MyMap implements Iterable, Map +public class InputMyMap implements Iterable, Map { @@ -93,7 +93,7 @@ public Collection values() } - public Set> entrySet() + public Set> entrySet() { return null; } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputAvoidConditionInversion.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputAvoidConditionInversionCheck.java similarity index 97% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputAvoidConditionInversion.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputAvoidConditionInversionCheck.java index 263cb3b32e..4afee0e74f 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputAvoidConditionInversion.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputAvoidConditionInversionCheck.java @@ -1,6 +1,6 @@ package com.github.sevntu.checkstyle.checks.design; import java.util.*; -public class InputAvoidConditionInversion +public class InputAvoidConditionInversionCheck { private boolean flag = false; private boolean isDifferent(int a, int b) { diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException3.java deleted file mode 100644 index 0dcb2ee361..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException3.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.github.sevntu.checkstyle.checks.design; -@SuppressWarnings("serial") -public class InputCauseParameterInException3 extends RuntimeException { - - public InputCauseParameterInException3() { - super(); - } - - public InputCauseParameterInException3(String message) { - super(message); - } - - public InputCauseParameterInException3(Throwable cause) { - super(cause); - } - - public InputCauseParameterInException3(String message, Throwable cause) { - super(message, cause); - } - -} \ No newline at end of file diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException4.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException4.java deleted file mode 100644 index 26b6063032..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException4.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.github.sevntu.checkstyle.checks.design; -public class InputCauseParameterInException4 extends Exception { - -public InputCauseParameterInException4(Exception cause) { - super(cause); - } -} - diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException5.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException5.java deleted file mode 100644 index 1fe289c55e..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException5.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.github.sevntu.checkstyle.checks.design; -public enum InputCauseParameterInException5{ - B; - private InputCauseParameterInException5() {} -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck.java similarity index 69% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck.java index d87a63786a..cb30e55347 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck.java @@ -1,9 +1,9 @@ package com.github.sevntu.checkstyle.checks.design; -public class InputCauseParameterInException extends Exception +public class InputCauseParameterInExceptionCheck { - - public InputCauseParameterInException(String str) + private class TestException extends Exception { + public TestException(String str) { super(str, null); } @@ -28,9 +28,9 @@ public MyException(String str, Exception ex) // Exception | Throwable only! } - public InputCauseParameterInException(String str, int integer) + public TestException(String str, int integer) { super(str, null); } - -} \ No newline at end of file + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck2.java similarity index 65% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck2.java index 29b88cc5e8..b0aaab7e6a 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInException2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck2.java @@ -1,14 +1,14 @@ package com.github.sevntu.checkstyle.checks.design; -public class InputCauseParameterInException2 extends Exception +public class InputCauseParameterInExceptionCheck2 { - - public InputCauseParameterInException2(String str) + private class TestException2 extends Exception { + public TestException2(String str) { super(str, null); } - public InputCauseParameterInException2(String str, int integer) + public TestException2(String str, int integer) { super(str, null); } @@ -28,5 +28,5 @@ public MyException2(String str, int integer) } } - -} \ No newline at end of file + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck3.java new file mode 100644 index 0000000000..a42343aa80 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck3.java @@ -0,0 +1,21 @@ +package com.github.sevntu.checkstyle.checks.design; +@SuppressWarnings("serial") +public class InputCauseParameterInExceptionCheck3 extends RuntimeException { + + public InputCauseParameterInExceptionCheck3() { + super(); + } + + public InputCauseParameterInExceptionCheck3(String message) { + super(message); + } + + public InputCauseParameterInExceptionCheck3(Throwable cause) { + super(cause); + } + + public InputCauseParameterInExceptionCheck3(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck4.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck4.java new file mode 100644 index 0000000000..dd22cb6212 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck4.java @@ -0,0 +1,8 @@ +package com.github.sevntu.checkstyle.checks.design; +public class InputCauseParameterInExceptionCheck4 extends Exception { + +public InputCauseParameterInExceptionCheck4(Exception cause) { + super(cause); + } +} + diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck5.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck5.java new file mode 100644 index 0000000000..8ff924d2d3 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCauseParameterInExceptionCheck5.java @@ -0,0 +1,5 @@ +package com.github.sevntu.checkstyle.checks.design; +public enum InputCauseParameterInExceptionCheck5{ + B; + private InputCauseParameterInExceptionCheck5() {} +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheck.java new file mode 100644 index 0000000000..b1a0ef0f55 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheck.java @@ -0,0 +1,58 @@ +package com.github.sevntu.checkstyle.checks.design; + +import org.junit.Test; + +public class InputCheckstyleTestMakeupCheck { + private String s; + + public void method1() { + } + + public void method2() { + String s = ""; + method1(); + } + + @Test + public void method3() { + } + + @org.junit.Test + public void method4() { + } + + @Test + public void method5() { + new Thread(new Runnable() { + private String s; + + @Override + public void run() { + } + }); + } + + @Test + public void method6() { + String s = ""; + java.util.List t; + method1(); + InputCheckstyleTestMakeupCheck.test(); + addAttribute("", ""); + test2().test3(); + } + + private static void test() { + } + + private static void addAttribute(String s, String t) { + } + + private InputCheckstyleTestMakeupCheck test2() { + return this; + } + + private InputCheckstyleTestMakeupCheck test3() { + return this; + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheckInvalid.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheckInvalid.java new file mode 100644 index 0000000000..be8f62d9a4 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheckInvalid.java @@ -0,0 +1,87 @@ +package com.github.sevntu.checkstyle.checks.design; + +import java.io.File; + +import org.junit.Test; + +public class InputCheckstyleTestMakeupCheckInvalid { + @Test + public void method1() { + verify(); + } + + @Test + public void method2() { + DefaultConfiguration config; + verify(); + } + + @Test + public void method3() { + DefaultConfiguration config = customCreateConfig(); + verify(); + } + + @Test + public void method4() { + DefaultConfiguration config = new DefaultConfiguration(); + verify(); + } + + @Test + public void method5() { + final Configuration config = createModuleConfig(); + File file = new File(""); + file = new File(""); + config.addAttribute("", file.getPath()); + config.addAttribute("", file.getAbsolutePath()); + config.addAttribute("", customValue()); + config.addAttribute("", ENUM.TEST.getName(0)); + config.addAttribute("", ENUM.TEST.other()); + config.addAttribute("", ENUM.TEST.same.getName(0)); + config.addAttribute("", 0); + config.addAttribute("", "" + 0); + config.addAttribute("", 0 + ""); + verify(); + } + + private static String customValue() { + return null; + } + + private static void verify() { + } + + private DefaultConfiguration customCreateConfig() { + return new DefaultConfiguration(); + } + + private static DefaultConfiguration createModuleConfig() { + return new DefaultConfiguration(); + } + + private static class Configuration { + public void addAttribute(String s, String t) { + } + + public void addAttribute(String s, int i) { + } + } + + private static class DefaultConfiguration extends Configuration { + } + + private enum ENUM { + TEST; + + private static final ENUM same = TEST; + + public String other() { + return name(); + } + + public String getName(int i) { + return name(); + } + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheckValid.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheckValid.java new file mode 100644 index 0000000000..f696a159ba --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputCheckstyleTestMakeupCheckValid.java @@ -0,0 +1,99 @@ +package com.github.sevntu.checkstyle.checks.design; + +import java.io.File; + +import org.junit.Test; + +public class InputCheckstyleTestMakeupCheckValid { + @Test + public void method1() { + final Configuration config = null; + verify(); + } + + @Test + public void method2() { + final Configuration config = createModuleConfig(); + verify(); + } + + @Test + public void method3() { + final DefaultConfiguration config = createRootConfig(); + verifyWarns(); + } + + @Test + public void method4() { + final Configuration config = createModuleConfig(); + config.addAttribute("", null); + config.addAttribute("", ""); + config.addAttribute("", "" + ""); + final File file = new File(""); + config.addAttribute("", file.getPath()); + config.addAttribute("", ENUM.TEST.toString()); + config.addAttribute("", ENUM.TEST.getName()); + config.addAttribute("", ENUM.TEST.name()); + config.addAttribute("", getPath("")); + config.addAttribute("", getNonCompilablePath("")); + config.addAttribute("", getUriString("")); + config.addAttribute("", getResourcePath("")); + verify(); + } + + @Test + public void method5() { + // simulation of PowerMockito.mock(DefaultConfiguration.class); + DefaultConfiguration config = InputCheckstyleTestMakeupCheckValid.createModuleConfig(); + verify(); + } + + private String getPath(String s) { + return s; + } + + private String getNonCompilablePath(String s) { + return s; + } + + private String getUriString(String s) { + return s; + } + + private String getResourcePath(String s) { + return s; + } + + private static void verify() { + } + + private static void verifyWarns() { + } + + private static void verifySuppressed() { + } + + private static DefaultConfiguration createModuleConfig() { + return new DefaultConfiguration(); + } + + private static DefaultConfiguration createRootConfig() { + return new DefaultConfiguration(); + } + + private static class Configuration { + public void addAttribute(String s, String t) { + } + } + + private static class DefaultConfiguration extends Configuration { + } + + private enum ENUM { + TEST; + + public String getName() { + return name(); + } + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheck.java index 495a29681e..c0d7d9f56e 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheck.java @@ -14,7 +14,7 @@ public static void main(String[] args) if (isTrue()) { // 2: simple if with braces number = 2; } - + if (isTrue()) { // 3: if-else number = 3; } else { @@ -57,8 +57,17 @@ public static void main(String[] args) default: number = 15; break; - } + } + + try { + } + catch (Exception e) { + } + finally + { + } + if (isTrue()) {} } } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckCheckNPE.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckCheckNPE.java index 3d5198e450..5f4dba87c1 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckCheckNPE.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckCheckNPE.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckDoubleNested.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckDoubleNested.java index 0b6db7fb33..265b7a7451 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckDoubleNested.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckDoubleNested.java @@ -49,4 +49,13 @@ public void nestedForFiveLevel() { } } } + + public void inClass(int type) { + switch (type) { + case 3: + new Object() { + public void anonymousMethod() {} + }; + } + } } \ No newline at end of file diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckManyBlocksOnOneScope.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckManyBlocksOnOneScope.java index 4c6339ed61..aceb86c7ea 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckManyBlocksOnOneScope.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputChildBlockLengthCheckManyBlocksOnOneScope.java @@ -42,6 +42,17 @@ public static void main(String[] args) } + public void test() { + int number; + + if (isTrue()) { + if (isTrue()) + number = 3; + else + number = 3; + } + } + public static boolean isTrue() { return Boolean.TRUE; } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputConstructorWithoutParamsCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputConstructorWithoutParamsCheck.java index 34f02d3407..7b82cfe8c1 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputConstructorWithoutParamsCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputConstructorWithoutParamsCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20,7 +20,12 @@ package com.github.sevntu.checkstyle.checks.design; import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import java.util.stream.Stream; public class InputConstructorWithoutParamsCheck { @@ -111,4 +116,6 @@ class MockExceptionHandler { } + private static final Set TEST = Collections.unmodifiableSortedSet(Stream.of("test") + .collect(Collectors.toCollection(TreeSet::new))); } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnType.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnTypeCheck.java similarity index 98% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnType.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnTypeCheck.java index 925644cb0f..b96447d850 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnType.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnTypeCheck.java @@ -4,7 +4,7 @@ import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.ArrayList; -class Wildscards +class Wildcards { public List met1() { @@ -310,8 +310,8 @@ class MethodsWithAnnotations extends SomeClass { @SuppressWarnings("unchecked") public List met3() { return null; } - @Deprecated - @Override + @java.lang.Deprecated + @java.lang.Override @SuppressWarnings("unused") public List met4() { return null; @@ -335,7 +335,7 @@ class MyClass {} class A extends MyClass{} class B extends A{} -public class InputForbidWildcardAsReturnType +public class InputForbidWildcardAsReturnTypeCheck { public static void main(String args[]) { A objA = max(new ArrayList()); diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnTypeCheckQualifiedAnnotation.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnTypeCheckQualifiedAnnotation.java new file mode 100644 index 0000000000..d3fc680ba7 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputForbidWildcardAsReturnTypeCheckQualifiedAnnotation.java @@ -0,0 +1,7 @@ +package com.github.sevntu.checkstyle.checks.design; + +public class InputForbidWildcardAsReturnTypeCheckQualifiedAnnotation { + @org.junit.After + public void doAfterTest() { + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputArrayTypeStyle.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck.java old mode 100755 new mode 100644 similarity index 95% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputArrayTypeStyle.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck.java index ab74fe4b42..b75ecd111f --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputArrayTypeStyle.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck.java @@ -8,7 +8,7 @@ * Test case for ArrayTypeStyle (Java vs C) * @author lkuehne **/ -public class InputArrayTypeStyle +public class InputHideUtilityClassConstructorCheck { private int[] javaStyle = new int[0]; private int cStyle[] = new int[0]; diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor1.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck1.java similarity index 61% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor1.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck1.java index cd9ad96095..396d9b1377 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor1.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck1.java @@ -2,7 +2,7 @@ import java.io.Serializable; -public abstract class InputHideUtilityClassContructor1 implements Serializable { +public abstract class InputHideUtilityClassConstructorCheck1 implements Serializable { private static final long serialVersionUID = 1L; } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor2.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck2.java similarity index 64% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor2.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck2.java index b2467eb8fb..4d13e2f663 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor2.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck2.java @@ -2,7 +2,7 @@ import java.io.Serializable; -public class InputHideUtilityClassContructor2 implements Serializable { +public class InputHideUtilityClassConstructorCheck2 implements Serializable { private static final long serialVersionUID = 1L; } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor3.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck3.java similarity index 88% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor3.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck3.java index 089f1aac23..98d893e807 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassContructor3.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck3.java @@ -2,10 +2,10 @@ import java.io.Serializable; -public class InputHideUtilityClassContructor3 implements Serializable { +public class InputHideUtilityClassConstructorCheck3 implements Serializable { private static final long serialVersionUID = 1L; - public InputHideUtilityClassContructor3(int i) { + public InputHideUtilityClassConstructorCheck3(int i) { // no code } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputDesignForExtension.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck4.java old mode 100755 new mode 100644 similarity index 90% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputDesignForExtension.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck4.java index 994ae6f12d..7c0de5cd98 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputDesignForExtension.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck4.java @@ -8,7 +8,7 @@ * Test case for the "design for inheritance" check. * @author Lars Kühne **/ -public abstract class InputDesignForExtension +public abstract class InputHideUtilityClassConstructorCheck4 { // some methods that are OK @@ -41,7 +41,7 @@ private void aPrivateMethod() protected abstract void nonFinalButAbstract(); - // this one is bad: neither abtract, final, or empty + // this one is bad: neither abstract, final, or empty protected void doh() { @@ -55,7 +55,7 @@ protected void doh() // tries to trigger bug #884035 // MyComparator is a private class, so there cannot be subclasses - // and it should not be neccessary to declare compare() as final + // and it should not be necessary to declare compare() as final private class MyComparator implements java.util.Comparator { public int compare(Object o1, Object o2) diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputNonUtilityClass.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck5.java old mode 100755 new mode 100644 similarity index 77% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputNonUtilityClass.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck5.java index 1eac488937..1e5b57a27c --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputNonUtilityClass.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck5.java @@ -6,10 +6,10 @@ /** * Not a util class because it's not directly derived from java.lang.Object. */ -public class InputNonUtilityClass extends JPanel +public class InputHideUtilityClassConstructorCheck5 extends JPanel { /** HideUtilityClassConstructorCheck should not report this */ - public InputNonUtilityClass() + public InputHideUtilityClassConstructorCheck5() { this.setPreferredSize(new Dimension(100, 100)); } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputRegression.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck6.java old mode 100755 new mode 100644 similarity index 56% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputRegression.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck6.java index e37b5cd153..875ee8867f --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputRegression.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputHideUtilityClassConstructorCheck6.java @@ -5,12 +5,12 @@ * * @author lkuehne */ -public class InputRegression +public class InputHideUtilityClassConstructorCheck6 { public long constructionTime = System.currentTimeMillis(); - public static InputRegression create() + public static InputHideUtilityClassConstructorCheck6 create() { - return new InputRegression(); + return new InputHideUtilityClassConstructorCheck6(); } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputInnerClassCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputInnerClassCheck.java index d8e9f2e676..b193edd036 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputInnerClassCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputInnerClassCheck.java @@ -80,3 +80,10 @@ public int[] getDefaultTokens() return new int[]{1, }; } } + +class Temp4 { + class InnerCheck1 { + } + class InnerCheck2 { + } +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputPublicReferenceToPrivateTypeCheck20.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputPublicReferenceToPrivateTypeCheck20.java new file mode 100644 index 0000000000..90e9da7208 --- /dev/null +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputPublicReferenceToPrivateTypeCheck20.java @@ -0,0 +1,16 @@ +package com.github.sevntu.checkstyle.checks.design; + +import java.lang.invoke.MethodType; +import java.lang.ref.WeakReference; + +public class InputPublicReferenceToPrivateTypeCheck20 { + static final ConcurrentWeakInternSet internTable = new ConcurrentWeakInternSet<>(); + + private static class ConcurrentWeakInternSet { + private static class WeakEntry extends WeakReference { + public WeakEntry(T referent) { + super(referent); + } + } + } +} \ No newline at end of file diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidate.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheck.java similarity index 96% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidate.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheck.java index 02aed24769..70c895c9e4 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidate.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheck.java @@ -8,7 +8,7 @@ import com.puppycrawl.tools.checkstyle.utils.ScopeUtils; -public class InputStaticMethodCandidate extends ClassB { +public class InputStaticMethodCandidateCheck extends ClassB { protected int instanceField; private static int classField; @@ -54,8 +54,8 @@ private static class Nested { private static int nestedClassField; private void nestedFoo1() { //violation - InputStaticMethodCandidate local = new InputStaticMethodCandidate(); - InputStaticMethodCandidate.classField = local.instanceField; + InputStaticMethodCandidateCheck local = new InputStaticMethodCandidateCheck(); + InputStaticMethodCandidateCheck.classField = local.instanceField; Nested nested = new Nested(); nested.nestedClassField = nestedClassField + local.classField; nested.nestedFoo4(); @@ -154,7 +154,7 @@ public void foo(String i) { } // ok, as only private methods are checked } -class TestExtended extends InputStaticMethodCandidate { +class TestExtended extends InputStaticMethodCandidateCheck { static {int i = 1;} {int i = 2;} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateSkippedMethods.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckSkippedMethods.java similarity index 74% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateSkippedMethods.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckSkippedMethods.java index a5e6c3f59b..0b5f87095f 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateSkippedMethods.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/design/InputStaticMethodCandidateCheckSkippedMethods.java @@ -3,7 +3,7 @@ /** * */ -public class InputStaticMethodCandidateSkippedMethods { +public class InputStaticMethodCandidateCheckSkippedMethods { private void foo() {} private void foo(int i) {} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputAbstractClassName.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputAbstractClassName.java deleted file mode 100644 index ea90eaf87a..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputAbstractClassName.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.github.sevntu.checkstyle.checks.naming; - -abstract public class InputAbstractClassName { -} -// abstract --> ^Abstract.*$|^.*Factory$ -abstract class NonAbstractClassName { -} - -abstract class FactoryWithBadName { -} - -abstract class AbstractClassName { - abstract class NonAbstractInnerClass { - } -} - -abstract class ClassFactory { - abstract class WellNamedFactory { - } -} - -class NonAbstractClass { -} - -//^Abstract.*$|^.*Factory$ --> abstract -class AbstractClass { -} - -class Class1Factory { -} - -abstract class AbstractClassName2 { - class AbstractInnerClass { - } -} - -abstract class Class2Factory { - class WellNamedFactory { - } -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputEnumValueNameCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputEnumValueNameCheck.java index 48a07c7a6d..5daa51214f 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputEnumValueNameCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputEnumValueNameCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputInterfaceTypeParameterName.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputInterfaceTypeParameterNameCheck.java similarity index 80% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputInterfaceTypeParameterName.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputInterfaceTypeParameterNameCheck.java index 6d63e4d22e..33abda0fe3 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputInterfaceTypeParameterName.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputInterfaceTypeParameterNameCheck.java @@ -2,7 +2,7 @@ import java.util.List; -public interface InputInterfaceTypeParameterName { +public interface InputInterfaceTypeParameterNameCheck { } @@ -17,4 +17,4 @@ interface ThirdInterface { class OuterClass { interface InnerInterface { } -} \ No newline at end of file +} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputUniformEnumConstantNameCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputUniformEnumConstantNameCheck.java index 3e4a999f1e..faa2a31c3e 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputUniformEnumConstantNameCheck.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/naming/InputUniformEnumConstantNameCheck.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputLineLengthCheck.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputLineLengthCheck.java deleted file mode 100644 index b2121b758e..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputLineLengthCheck.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.github.sevntu.checkstyle.checks.sizes; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -public class InputLineLengthCheck { - - public InputLineLengthCheck() { - - } - - Map> mTempVariableForCheck = new HashMap>(); - - public static HashMap newInstance(int mParametr1, int mParametr2, int mParametr3) throws IndexOutOfBoundsException, InstantiationException, IllegalMonitorStateException { - String str = "This InputLineLengthCheck contains declaration of class, constructor, field and method. Their length is more then 120 characters, but it should be ignored"; - System.out.println(str); - return new HashMap(); - } - - class InnerClassCheck - { - Map> mTempVariableForInnerClass = new HashMap>(); - - public HashMap newInstanceForInnerClass(int mParametr1, int mParametr2, int mParametr3) throws IndexOutOfBoundsException, InstantiationException, IllegalMonitorStateException { - String str = "This InputLineLengthCheck contains declaration of class, constructor, field and method in Inner Class. Their length is more then 120 characters, but it should be ignored"; - System.out.println(str); - return new HashMap(); - } - } -} - -abstract class AbstractTreeNodeEntityModel, N extends InputLineLengthCheck> -extends InputLineLengthCheck { - /* (non-Javadoc) - * @see com.revere.ria.workbench.spring.config.xml.AbstractDescriptorDefinitionParser#parseDescriptorAttributes(org.w3c.dom.Element, org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.beans.factory.xml.ParserContext) - */ - protected void parseDescriptorAttributes(String element, - Integer beanBuilder, Double parserContext) { - } - //This is a vary long coment, This is a vary long coment, This is a vary long coment, This is a vary long coment, This is a vary long coment, This is a vary long coment, This is a vary long coment, This is a vary long coment, This is a vary long coment! - - /* Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text - * Some text Some text Some text Some text Some text Some text Some text Some text - * Some text*/ -} diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputSimple.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputLineLengthExtendedCheck.java similarity index 97% rename from sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputSimple.java rename to sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputLineLengthExtendedCheck.java index a6d62b291f..0a873a84b6 100644 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputSimple.java +++ b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/sizes/InputLineLengthExtendedCheck.java @@ -13,7 +13,7 @@ * - Order of modifiers * @author Oliver Burn **/ -final class InputSimple +final class InputLineLengthExtendedCheck { // Long line ---------------------------------------------------------------- // Contains a tab -> <- @@ -99,7 +99,7 @@ private void longMethod() } /** constructor that is 10 lines long **/ - private InputSimple() + private InputLineLengthExtendedCheck() { // a line // a line @@ -220,6 +220,6 @@ enum MyEnum1 /** XYZ constant */ XYZ; - /** Should be mSomeMemeber */ + /** Should be mSomeMember */ private int someMember; } diff --git a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/test/utils/File.java b/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/test/utils/File.java deleted file mode 100644 index 897511e15f..0000000000 --- a/sevntu-checks/src/test/resources/com/github/sevntu/checkstyle/checks/test/utils/File.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.github.sevntu.checkstyle.checks.test.utils; - -public class File -{ - - public File(String string) - { - } - -} diff --git a/sevntu-checks/suppressions.xml b/sevntu-checks/suppressions.xml index 1ca95a8e50..e0d38689c5 100644 --- a/sevntu-checks/suppressions.xml +++ b/sevntu-checks/suppressions.xml @@ -6,43 +6,25 @@ - - - - + + - - - - - - - - - - - - - + + - - + - - - diff --git a/sevntu-checkstyle-idea-extension/pom.xml b/sevntu-checkstyle-idea-extension/pom.xml index ca06c41857..7a0f11f972 100644 --- a/sevntu-checkstyle-idea-extension/pom.xml +++ b/sevntu-checkstyle-idea-extension/pom.xml @@ -1,32 +1,36 @@ - + 4.0.0 - com.github.sevntu.checkstyle + + org.sonatype.oss + oss-parent + 9 + + + com.github.sevntu-checkstyle sevntu-checkstyle-idea-extension - 1.22.0 + 1.30.0 jar Sevntu Checkstyle Idea extension + + + LGPL-2.1+ + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + + - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle sevntu-checks ${project.version} - - - com.github.sevntu.checkstyle - Sevntu Checkstyle Idea extension - file://${basedir}/../gh-pages/maven2/ - - - @@ -34,6 +38,55 @@ + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + package + + jar + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + package + + jar + + + ${basedir}/src + + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + + sonatype-nexus-staging + https://oss.sonatype.org/ + true + true + + + org.apache.maven.plugins maven-dependency-plugin @@ -48,7 +101,7 @@ - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle sevntu-checks ${sevntu.checks.version} jar @@ -67,4 +120,42 @@ + + + + local-deploy + + + com.github.sevntu-checkstyle + Sevntu Checkstyle Idea extension + file://${deployDir}/maven2/ + + + + + + + gpg + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + + + + + diff --git a/sevntu-checkstyle-idea-extension/src/Dummy.java b/sevntu-checkstyle-idea-extension/src/Dummy.java new file mode 100644 index 0000000000..4c00aebf4d --- /dev/null +++ b/sevntu-checkstyle-idea-extension/src/Dummy.java @@ -0,0 +1,4 @@ +/** +* Just need smth to make javadoc to pass maven central requirements +*/ +public class Dummy {} diff --git a/sevntu-checkstyle-maven-plugin/pom.xml b/sevntu-checkstyle-maven-plugin/pom.xml index a6a640cc47..edbb53f969 100644 --- a/sevntu-checkstyle-maven-plugin/pom.xml +++ b/sevntu-checkstyle-maven-plugin/pom.xml @@ -1,18 +1,31 @@ - + 4.0.0 - com.github.sevntu.checkstyle + + + org.sonatype.oss + oss-parent + 9 + + + com.github.sevntu-checkstyle sevntu-checkstyle-maven-plugin Sevntu Checkstyle Maven Plugin - 1.22.0 + 1.30.0 + + + + LGPL-2.1+ + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle sevntu-checks - 1.22.0 + 1.30.0 org.apache.maven.plugins @@ -21,12 +34,92 @@ - - - com.github.sevntu.checkstyle - Sevntu Checkstyle Maven Plugin - file://${basedir}/../gh-pages/maven2/ - - + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + package + + jar + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + package + + jar + + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + + sonatype-nexus-staging + https://oss.sonatype.org/ + true + true + + + + + + + + + + local-deploy + + + com.github.sevntu-checkstyle + Sevntu Checkstyle Maven Plugin + file://${deployDir}/maven2/ + + + + + + + gpg + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + + + diff --git a/sevntu-checkstyle-sonar-plugin/.classpath b/sevntu-checkstyle-sonar-plugin/.classpath deleted file mode 100644 index e3119bfce1..0000000000 --- a/sevntu-checkstyle-sonar-plugin/.classpath +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sevntu-checkstyle-sonar-plugin/.project b/sevntu-checkstyle-sonar-plugin/.project deleted file mode 100644 index 049073edc3..0000000000 --- a/sevntu-checkstyle-sonar-plugin/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - sevntu-checkstyle-sonar-plugin - - - - - - org.eclipse.jdt.core.javabuilder - - - - - net.sf.eclipsecs.core.CheckstyleBuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - net.sf.eclipsecs.core.CheckstyleNature - - diff --git a/sevntu-checkstyle-sonar-plugin/checkstyle.properties b/sevntu-checkstyle-sonar-plugin/checkstyle.properties index 6b8f3fc973..b33a3850a5 100644 --- a/sevntu-checkstyle-sonar-plugin/checkstyle.properties +++ b/sevntu-checkstyle-sonar-plugin/checkstyle.properties @@ -1,4 +1,6 @@ checkstyle.suppressions.file=suppressions.xml +checkstyle.suppressions-xpath.file=suppressions.xml checkstyle.header.file=https://raw.githubusercontent.com/checkstyle/checkstyle/master/config/java.header checkstyle.regexp.header.file=https://raw.githubusercontent.com/checkstyle/checkstyle/master/config/java_regexp.header checkstyle.importcontrol.file=import-control.xml +checkstyle.importcontroltest.file=import-control-test.xml diff --git a/sevntu-checkstyle-sonar-plugin/import-control-test.xml b/sevntu-checkstyle-sonar-plugin/import-control-test.xml new file mode 100644 index 0000000000..051a6bec66 --- /dev/null +++ b/sevntu-checkstyle-sonar-plugin/import-control-test.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/sevntu-checkstyle-sonar-plugin/pom.xml b/sevntu-checkstyle-sonar-plugin/pom.xml index 2775b6a849..a1cc662022 100644 --- a/sevntu-checkstyle-sonar-plugin/pom.xml +++ b/sevntu-checkstyle-sonar-plugin/pom.xml @@ -1,19 +1,32 @@ - + 4.0.0 - com.github.sevntu.checkstyle + + + org.sonatype.oss + oss-parent + 9 + + + com.github.sevntu-checkstyle sevntu-checkstyle-sonar-plugin - 1.22.0 + 1.30.0 sonar-plugin SevNTU Checkstyle Sonar Extension Plugin SevNTU Checkstyle extension plugin for Sonar + + + LGPL-2.1+ + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + + UTF-8 - 7.2 + 8.7 2.17 @@ -25,7 +38,7 @@ - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle sevntu-checks ${project.version} @@ -39,6 +52,52 @@ + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + package + + jar + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + package + + jar + + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + + sonatype-nexus-staging + https://oss.sonatype.org/ + true + true + + + org.codehaus.mojo xml-maven-plugin @@ -74,7 +133,7 @@ 1.0-beta-4 ${project.build.directory}/${project.build.finalName}.jar - file://${basedir}/../gh-pages/sonar/ + file://${deployDir}/sonar/ @@ -138,7 +197,7 @@ - @@ -238,7 +297,7 @@ - + @@ -249,6 +308,30 @@ + + + + gpg + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + + + diff --git a/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/CheckstyleExtensionPlugin.java b/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/CheckstyleExtensionPlugin.java index b6e07d0fe8..e960317040 100644 --- a/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/CheckstyleExtensionPlugin.java +++ b/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/CheckstyleExtensionPlugin.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -34,4 +34,5 @@ public final class CheckstyleExtensionPlugin extends SonarPlugin { public List getExtensions() { return Arrays.asList(CheckstyleExtensionRepository.class); } + } diff --git a/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/CheckstyleExtensionRepository.java b/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/CheckstyleExtensionRepository.java index 8694e86337..041f21b4f4 100644 --- a/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/CheckstyleExtensionRepository.java +++ b/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/CheckstyleExtensionRepository.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -79,4 +79,5 @@ public List createRules() { IOUtils.closeQuietly(input); } } + } diff --git a/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/package-info.java b/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/package-info.java index 50ee6373e5..fa38ef0d7b 100644 --- a/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/package-info.java +++ b/sevntu-checkstyle-sonar-plugin/src/main/java/com/github/sevntu/checkstyle/sonar/package-info.java @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2016 the original author or authors. +// Copyright (C) 2001-2018 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public diff --git a/sevntu-checkstyle-sonar-plugin/src/main/resources/com/github/sevntu/checkstyle/sonar/checkstyle-extensions.xml b/sevntu-checkstyle-sonar-plugin/src/main/resources/com/github/sevntu/checkstyle/sonar/checkstyle-extensions.xml index d28225b142..17019d942f 100644 --- a/sevntu-checkstyle-sonar-plugin/src/main/resources/com/github/sevntu/checkstyle/sonar/checkstyle-extensions.xml +++ b/sevntu-checkstyle-sonar-plugin/src/main/resources/com/github/sevntu/checkstyle/sonar/checkstyle-extensions.xml @@ -135,7 +135,7 @@ false - Check overrided methods. + Check overridden methods. false @@ -159,7 +159,7 @@ com.github.sevntu.checkstyle.checks.design.NoMainMethodInAbstractClassCheck No Main Method In Abstract Class - Forbids main methods in abstract classes. Rationale: existance of 'main' method can mislead a developer to consider this class as a ready-to-use implementation. + Forbids main methods in abstract classes. Rationale: existence of 'main' method can mislead a developer to consider this class as a ready-to-use implementation. Checker/TreeWalker/com.github.sevntu.checkstyle.checks.design.NoMainMethodInAbstractClassCheck @@ -377,6 +377,22 @@ + + com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck + Forbid Certain Method + + Forbids certain method in class. + Checker/TreeWalker/com.github.sevntu.checkstyle.checks.coding.ForbidCertainMethodCheck + + ^$ + Regex to match method name. + + + 0- + Number or range to match number of arguments. Multiple numbers/ranges must be comma separated. + + + com.github.sevntu.checkstyle.checks.coding.ForbidInstantiationCheck Forbid Instantiation @@ -486,7 +502,7 @@ false - Check to highlight all dublicates. + Check to highlight all duplicates. @@ -607,7 +623,7 @@ com.github.sevntu.checkstyle.checks.design.PublicReferenceToPrivateTypeCheck Public Reference To Private Type - This Check warns on propagation of inner private types to outer classes: - Externally accessible method if it returns private inner type. - Externally accessible field if it's type is a private inner type. These types could be private inner classe, interfaces or enumerations. + This Check warns on propagation of inner private types to outer classes: - Externally accessible method if it returns private inner type. - Externally accessible field if it's type is a private inner type. These types could be private inner classes, interfaces or enumerations. Checker/TreeWalker/com.github.sevntu.checkstyle.checks.design.PublicReferenceToPrivateTypeCheck @@ -777,21 +793,13 @@ com.github.sevntu.checkstyle.checks.naming.EnumValueNameCheck Check for enum values name - Check forces enum values to match the specific pattern + Checks that enumeration value names conform to a format specified by the format property. Checker/TreeWalker/com.github.sevntu.checkstyle.checks.naming.EnumValueNameCheck - - Regex for Values Enumeration name to conform + + Regex for enumeration value names to conform ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$ - - Regex for Class Enumeration name to conform - ^[A-Z][a-zA-Z0-9]*$ - - - Exclude method and field names regexp list (comma-separated) - toString - @@ -904,4 +912,36 @@ Check nested (internal) classes to be declared at the bottom of the class after all methods (fields) declaration. Checker/TreeWalker/com.github.sevntu.checkstyle.checks.design.InnerClassCheck + + + com.github.sevntu.checkstyle.checks.coding.MoveVariableInsideIfCheck + Move variable inside if check + + Checks if a variable is only used inside if statements and asks for it's declaration to be moved there too. + Checker/TreeWalker/com.github.sevntu.checkstyle.checks.coding.MoveVariableInsideIfCheck + + + + com.github.sevntu.checkstyle.checks.coding.RequireFailForTryCatchInJunitCheck + Require fail for try/catch in junit check + + Checks if a try/catch block has a junit fail assertion inside the try for a junit method. + Checker/TreeWalker/com.github.sevntu.checkstyle.checks.coding.RequireFailForTryCatchInJunitCheck + + + + com.github.sevntu.checkstyle.checks.design.CheckstyleTestMakeupCheck + Custom check to ensure Checkstyle tests are designed correctly. + + Custom check to ensure Checkstyle tests are designed correctly. + Checker/TreeWalker/com.github.sevntu.checkstyle.checks.design.CheckstyleTestMakeupCheck + + create(Root|Module)Config|getModuleConfig + Regular expression for matching a create configuration method by name. + + + verify(Warns|Suppressed)? + Regular expression for matching a verify method by name. + + diff --git a/sevntu_xdoc_freemarker.template b/sevntu_xdoc_freemarker.template new file mode 100644 index 0000000000..484ee49a93 --- /dev/null +++ b/sevntu_xdoc_freemarker.template @@ -0,0 +1,56 @@ + <#escape x as x?html> +
      +

      Release ${releaseNo}

      +
      + <#if breakingMessages?has_content> +

      Breaking backward compatibility:

      +
      + + <#if newMessages?has_content> +

      New:

      +
        + <#list newMessages as message> +
      • + ${message.title}. + Author: ${message.author}<#if message.issueNo != -1> + #${message.issueNo} +
      • + +
      + + <#if bugMessages?has_content> +

      Bug fixes:

      +
        + <#list bugMessages as message> +
      • + ${message.title}. + Author: ${message.author}<#if message.issueNo != -1> + #${message.issueNo} +
      • + +
      + + <#if notesMessages?has_content> +

      Notes:

      +
        + <#list notesMessages as message> +
      • + ${message.title}. + Author: ${message.author}<#if message.issueNo != -1> + #${message.issueNo} +
      • + +
      + +
      +
      + + diff --git a/update-site/pom.xml b/update-site/pom.xml index b30e27b106..321c5d0a46 100644 --- a/update-site/pom.xml +++ b/update-site/pom.xml @@ -1,20 +1,26 @@ - + 4.0.0 ../eclipse-pom.xml - com.github.sevntu.checkstyle + com.github.sevntu-checkstyle parent - 1.22.0 + 1.30.0 com.github.sevntu.checkstyle.p2updatesite eclipse-repository Tycho Test Build + + + LGPL-2.1+ + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + + @@ -47,7 +53,7 @@ ${project.build.directory}/repository/ ** update-site - file://${project.build.directory}/../../gh-pages + file://${deployDir} diff --git a/wercker.yml b/wercker.yml new file mode 100644 index 0000000000..8139b2aae0 --- /dev/null +++ b/wercker.yml @@ -0,0 +1,160 @@ +box: maven:3.5.2-jdk-8 + +build: + steps: + - script: + name: setup maven local repo + code: | + export MAVEN_OPTS="-Dmaven.repo.local=${WERCKER_CACHE_DIR}" + mvn -version + echo "------" + du -hs ${WERCKER_CACHE_DIR} + echo "------" + du -hs ${WERCKER_CACHE_DIR}/* | sort -h + + - script: + name: install groovy + code: | + if [ ! -d ${WERCKER_CACHE_DIR}/groovy ]; then + GROOVY_LINK="https://dl.bintray.com/groovy/maven/apache-groovy-binary-2.4.7.zip" + wget -O ${WERCKER_CACHE_DIR}/groovy.zip $GROOVY_LINK; + unzip ${WERCKER_CACHE_DIR}/groovy.zip -d ${WERCKER_CACHE_DIR}; + mv ${WERCKER_CACHE_DIR}/groovy-2.4.7 ${WERCKER_CACHE_DIR}/groovy + fi + export GROOVY_HOME=${WERCKER_CACHE_DIR}/groovy + PATH=$GROOVY_HOME/bin:$PATH + groovy -v + + - script: + name: Build Sevntu + code: | + SKIP_FILES1="appveyor.yml|codeship-*|buddy.yml|circleci|travis" + SKIP_FILES2="|shippable|sonar-|fast-forward-merge.sh|LICENSE|LICENSE.apache20" + SKIP_FILES3="|README.md|release.sh|RIGHTS.antlr|intellij-idea-inspections.xml" + SKIP_FILES4="|org.eclipse.jdt.core.prefs|distelli-manifest.yml|jsoref-spellchecker" + SKIP_FILES5="|check-only-javadoc-error.sh|eclipse-compiler-javac.sh|idea_inspection" + SKIP_FILES6="|test-spelling-unknown-words.sh" + SKIP_FILES=$SKIP_FILES1$SKIP_FILES2$SKIP_FILES3$SKIP_FILES4$SKIP_FILES5$SKIP_FILES6 + export SKIP_CI=false; + if [[ $(git diff --name-only HEAD HEAD~1 | grep -vE "$SKIP_FILES" | cat | wc -c) > 0 ]]; + then + SKIP_CI=false; + else + SKIP_CI=true; + fi + echo "SKIP_CI="$SKIP_CI + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + mvn -e clean install -Pno-validations + cd .. + else + echo "build is skipped ..." + fi + + - script: + name: NoExceptiontest - Apache Struts + code: | + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + echo "Command: ./.ci/wercker.sh no-exception-struts" + ./.ci/wercker.sh no-exception-struts + cd .. + else + echo "build is skipped ..." + fi + + - script: + name: NoExceptiontest - Guava + code: | + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + echo "Command: ./.ci/wercker.sh ./.ci/wercker.sh no-exception-guava" + ./.ci/wercker.sh no-exception-guava + cd .. + else + echo "build is skipped ..." + fi + + - script: + name: NoExceptiontest - Hibernate + code: | + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + echo "Command: ./.ci/wercker.sh no-exception-hibernate-orm" + ./.ci/wercker.sh no-exception-hibernate-orm + cd .. + else + echo "build is skipped ..." + fi + + + - script: + name: NoExceptiontest - spotbugs + code: | + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + echo "Command: ./.ci/wercker.sh no-exception-spotbugs" + ./.ci/wercker.sh no-exception-spotbugs + cd .. + else + echo "build is skipped ..." + fi + + - script: + name: NoExceptiontest - spring-framework + code: | + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + echo "Command: ./.ci/wercker.sh no-exception-spring-framework" + ./.ci/wercker.sh no-exception-spring-framework + cd .. + else + echo "build is skipped ..." + fi + + - script: + name: NoExceptiontest - Hbase + code: | + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + echo "Command: ./.ci/wercker.sh no-exception-hbase" + ./.ci/wercker.sh no-exception-hbase + cd .. + else + echo "build is skipped ..." + fi + + - script: + name: NoExceptiontest - pmd elasticsearch lombok-ast + code: | + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + echo "Command: ./.ci/wercker.sh no-exception-Pmd-elasticsearch-lombok-ast" + ./.ci/wercker.sh no-exception-Pmd-elasticsearch-lombok-ast + cd .. + else + echo "build is skipped ..." + fi + + - script: + name: NoExceptiontest - RxJava apache-ant apache-jsecurity android-launcher .... + code: | + if [[ $SKIP_CI == 'false' ]]; then + cd sevntu-checks + echo "Command: ./.ci/wercker.sh no-exception-alot-of-projects" + ./.ci/wercker.sh no-exception-alot-of-projects + cd .. + else + echo "build is skipped ..." + fi + + - script: + name: Cleanup maven local repo + code: | + find ${WERCKER_CACHE_DIR} -type d -name "*SNAPSHOT" -ls -exec rm -rf {} + + echo "------" + du -hs ${WERCKER_CACHE_DIR} + echo "------" + du -hs ${WERCKER_CACHE_DIR}/* | sort -h + echo "------" + du -hs * | sort -h