repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/codestyle/unnecessaryimport/package1/U.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.codestyle.unnecessaryimport.package1;
import net.sourceforge.pmd.lang.java.rule.codestyle.unnecessaryimport.package2.*; // SUPPRESS CHECKSTYLE needed for test case
public class U {
private void g() {
String k = C.V;
}
}
| 369 | 25.428571 | 125 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/codestyle/unnecessaryimport/package2/C.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.codestyle.unnecessaryimport.package2;
public class C {
private C() { }
public class IC { }
public static class ISC { }
public static final String V = "";
}
| 307 | 18.25 | 80 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/ExcessivePublicCountTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessivePublicCountTest extends PmdRuleTst {
// no additional unit tests
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/ExcessiveParameterListTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveParameterListTest extends PmdRuleTst {
// no additional unit tests
}
| 283 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/CognitiveComplexityTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CognitiveComplexityTest extends PmdRuleTst {
// no additional unit tests
}
| 280 | 22.416667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/SimplifyBooleanExpressionsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class SimplifyBooleanExpressionsTest extends PmdRuleTst {
// no additional unit tests
}
| 287 | 23 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/ExceptionAsFlowControlTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExceptionAsFlowControlTest extends PmdRuleTst {
// no additional unit tests
}
| 283 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/NPathComplexityTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class NPathComplexityTest extends PmdRuleTst {
// no additional unit tests
}
| 276 | 22.083333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/AvoidCatchingGenericExceptionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidCatchingGenericExceptionTest extends PmdRuleTst {
// no additional unit tests
}
| 290 | 23.25 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/AvoidDeeplyNestedIfStmtsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidDeeplyNestedIfStmtsTest extends PmdRuleTst {
// no additional unit tests
}
| 285 | 22.833333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/TooManyMethodsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class TooManyMethodsTest extends PmdRuleTst {
// no additional unit tests
}
| 275 | 22 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/DataClassTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class DataClassTest extends PmdRuleTst {
// no additional unit tests
}
| 270 | 21.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/InvalidJavaBeanTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
public class InvalidJavaBeanTest extends PmdRuleTst {
// no additional unit tests
}
| 282 | 22.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/CyclomaticComplexityTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CyclomaticComplexityTest extends PmdRuleTst {
// no additional unit tests
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/FinalFieldCouldBeStaticTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class FinalFieldCouldBeStaticTest extends PmdRuleTst {
// no additional unit tests
}
| 284 | 22.75 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/LawOfDemeterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class LawOfDemeterTest extends PmdRuleTst {
// no additional unit tests
}
| 273 | 21.833333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/AvoidThrowingRawExceptionTypesTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidThrowingRawExceptionTypesTest extends PmdRuleTst {
public static class Throwable extends java.lang.Throwable {
private static final long serialVersionUID = 1798165250043760600L;
}
public static class Exception extends java.lang.Throwable {
private static final long serialVersionUID = -2518308549741147689L;
}
public static class RuntimeException extends java.lang.Throwable {
private static final long serialVersionUID = 6341520923058239682L;
}
public static class Error extends java.lang.Throwable {
private static final long serialVersionUID = -6965602141393320558L;
}
}
| 847 | 31.615385 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/SimplifyBooleanReturnsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class SimplifyBooleanReturnsTest extends PmdRuleTst {
// no additional unit tests
}
| 283 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/AvoidThrowingNewInstanceOfSameExceptionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidThrowingNewInstanceOfSameExceptionTest extends PmdRuleTst {
// no additional unit tests
}
| 300 | 24.083333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/AvoidUncheckedExceptionsInSignaturesTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidUncheckedExceptionsInSignaturesTest extends PmdRuleTst {
// no additional unit tests
}
| 297 | 23.833333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/ImmutableFieldTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ImmutableFieldTest extends PmdRuleTst {
// no additional unit tests
}
| 275 | 22 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/AbstractClassWithoutAnyMethodTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AbstractClassWithoutAnyMethodTest extends PmdRuleTst {
// no additional unit tests
}
| 290 | 23.25 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/AvoidRethrowingExceptionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidRethrowingExceptionTest extends PmdRuleTst {
// no additional unit tests
}
| 285 | 22.833333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/ExcessiveImportsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveImportsTest extends PmdRuleTst {
// no additional unit tests
}
| 277 | 22.166667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/UseObjectForClearerAPITest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UseObjectForClearerAPITest extends PmdRuleTst {
// no additional unit tests
}
| 283 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/SignatureDeclareThrowsExceptionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class SignatureDeclareThrowsExceptionTest extends PmdRuleTst {
// no additional unit tests
}
| 292 | 23.416667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/DoNotExtendJavaLangErrorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class DoNotExtendJavaLangErrorTest extends PmdRuleTst {
// no additional unit tests
}
| 285 | 22.833333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/SimplifiedTernaryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class SimplifiedTernaryTest extends PmdRuleTst {
// no additional unit tests
}
| 278 | 22.25 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/CouplingBetweenObjectsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CouplingBetweenObjectsTest extends PmdRuleTst {
// no additional unit tests
}
| 283 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/NcssCountTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class NcssCountTest extends PmdRuleTst {
// no additional unit tests
}
| 270 | 21.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/LogicInversionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class LogicInversionTest extends PmdRuleTst {
// no additional unit tests
}
| 275 | 22 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/AvoidThrowingNullPointerExceptionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidThrowingNullPointerExceptionTest extends PmdRuleTst {
// no additional unit tests
}
| 294 | 23.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/GodClassTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class GodClassTest extends PmdRuleTst {
// no additional unit tests
}
| 269 | 21.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/LoosePackageCouplingTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class LoosePackageCouplingTest extends PmdRuleTst {
// no additional unit tests
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/SwitchDensityTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class SwitchDensityTest extends PmdRuleTst {
// no additional unit tests
}
| 274 | 21.916667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/SimplifyConditionalTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class SimplifyConditionalTest extends PmdRuleTst {
// no additional unit tests
}
| 280 | 22.416667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/SingularFieldTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class SingularFieldTest extends PmdRuleTst {
// no additional unit tests
}
| 274 | 21.916667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/MutableStaticStateTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class MutableStaticStateTest extends PmdRuleTst {
// no additional unit tests
}
| 279 | 22.333333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/ClassWithOnlyPrivateConstructorsShouldBeFinalTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ClassWithOnlyPrivateConstructorsShouldBeFinalTest extends PmdRuleTst {
// no additional unit tests
}
| 306 | 24.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/UseUtilityClassTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UseUtilityClassTest extends PmdRuleTst {
// no additional unit tests
}
| 276 | 22.083333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/ExcessiveMethodLengthTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveMethodLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 282 | 22.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/UselessOverridingMethodTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UselessOverridingMethodTest extends PmdRuleTst {
// no additional unit tests
}
| 284 | 22.75 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/TooManyFieldsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class TooManyFieldsTest extends PmdRuleTst {
// no additional unit tests
}
| 274 | 21.916667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/ExcessiveClassLengthTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveClassLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/CollapsibleIfStatementsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CollapsibleIfStatementsTest extends PmdRuleTst {
// no additional unit tests
}
| 284 | 22.75 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/signaturedeclarethrowsexception/MyTestCase.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.signaturedeclarethrowsexception;
import org.junit.Ignore;
import junit.framework.TestCase;
/**
* Warning, this class IS NOT useless. It is used by the some regression tests.
*
* See file: SignatureDeclareThrowsException.xml
*/
@Ignore("not a test case")
public class MyTestCase extends TestCase {
}
| 446 | 21.35 | 82 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/BaseClass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public class BaseClass {
protected void doBase() {
}
protected void doBaseWithArg(String foo) {
}
protected void doBaseWithArgs(String foo, int bar) {
}
protected void methodWithInterface(CharSequence arg) {
}
}
| 412 | 18.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/OtherSubclass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public class OtherSubclass extends BaseClass {
// note: argument type overloaded from CharSequence to String
protected void methodWithInterface(String arg) {
super.methodWithInterface(arg);
}
}
| 379 | 26.142857 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/DirectSynchronizingSubclass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public class DirectSynchronizingSubclass extends BaseClass {
@Override
protected synchronized void doBase() {
// overriding for synchronized
super.doBase();
}
}
| 354 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/DirectSubclass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public class DirectSubclass extends BaseClass {
// overrides to make the methods public
@Override
public void doBase() {
super.doBase();
}
@Override
public void doBaseWithArg(String foo) {
super.doBaseWithArg(foo);
}
@Override
public void doBaseWithArgs(String foo, int bar) {
super.doBaseWithArgs(foo, bar);
}
}
| 545 | 20 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/GeneratedValue.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public @interface GeneratedValue {
GenerationType strategy() default GenerationType.AUTO;
}
| 260 | 25.1 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/DirectSubclass2.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public class DirectSubclass2 extends DirectSubclass {
// useless overrides - it's already public
@Override
public void doBase() {
super.doBase();
}
@Override
public void doBaseWithArg(String foo) {
super.doBaseWithArg(foo);
}
@Override
public void doBaseWithArgs(String foo, int bar) {
super.doBaseWithArgs(foo, bar);
}
}
| 553 | 22.083333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/UselessOverridingMethodHashCode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public class UselessOverridingMethodHashCode {
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
| 390 | 19.578947 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/ExposingSerializer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import org.w3c.dom.Node;
class ExposingSerializer extends Serializer {
ExposingSerializer(OutputStream out, String encoding) throws UnsupportedEncodingException {
super(out, encoding);
}
/**
* Overriding in order to change the access modifier from protected to public - so: not only merely calling super.
*
* <p>Method signature in super class: protected void writeChild(nu.xom.Node arg0) throws java.io.IOException;
*
* <p>See: https://sourceforge.net/tracker/?func=detail&aid=1415525&group_id=56262&atid=479921
*/
public void writeChild(Node node) throws IOException {
super.writeChild(node);
}
}
| 937 | 28.3125 | 118 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/Serializer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
import java.io.IOException;
import java.io.OutputStream;
import org.w3c.dom.Node;
public class Serializer {
public Serializer(OutputStream out, String encoding) {
}
protected void writeChild(Node node) throws IOException {
}
}
| 412 | 18.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/TransitiveSubclass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public class TransitiveSubclass extends OtherSubclass {
// overrides to make the methods public
@Override
public void doBase() {
super.doBase();
}
@Override
public void doBaseWithArg(String foo) {
super.doBaseWithArg(foo);
}
@Override
public void doBaseWithArgs(String foo, int bar) {
super.doBaseWithArgs(foo, bar);
}
}
| 553 | 20.307692 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/Id.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public @interface Id {
}
| 189 | 20.111111 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/GenerationType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod;
public enum GenerationType {
AUTO
}
| 204 | 19.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/other/OtherClassInOtherPackage.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod.other;
public class OtherClassInOtherPackage {
public void foo() {
DirectSubclassInOtherPackage instance = new DirectSubclassInOtherPackage();
// the following calls are only possible, because DirectSubclassInOtherPackage makes this
// method available in this package as well.
instance.doBase();
instance.doBaseWithArg("a");
instance.doBaseWithArgs("a", 1);
}
}
| 583 | 31.444444 | 97 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/other/DirectSubclassInOtherPackage.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod.other;
import net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod.BaseClass;
public class DirectSubclassInOtherPackage extends BaseClass {
// overrides to make the method available in this package
@Override
protected void doBase() {
super.doBase();
}
@Override
protected void doBaseWithArg(String foo) {
super.doBaseWithArg(foo);
}
@Override
protected void doBaseWithArgs(String foo, int bar) {
super.doBaseWithArgs(foo, bar);
}
}
| 677 | 23.214286 | 83 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/singularfield/NoThrowingCloseable.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.singularfield;
public interface NoThrowingCloseable extends AutoCloseable {
@Override
void close();
}
| 249 | 21.727273 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/singularfield/Issue3303.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.singularfield;
public class Issue3303 {
// "private" is a must for reproducing the problem
private final NoThrowingCloseable first;
Issue3303(NoThrowingCloseable first) {
this.first = first;
}
public void performClosing() {
// note: this is uncommented in the test case, it needs
// java 9
// try (first) {
// this block can be empty or not
// }
}
}
| 578 | 23.125 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/donotextendjavalangerror/Error.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.design.donotextendjavalangerror;
/**
* @author Akshat Bahety
* @since 6.4.0
*/
public class Error {
}
| 239 | 16.142857 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/internal/DataflowPassTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.internal;
import static org.hamcrest.MatcherAssert.assertThat;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.DataflowResult;
/**
* @author Clément Fournier
*/
class DataflowPassTest extends BaseParserTest {
@Test
void testSimple() {
ASTCompilationUnit ast = java.parseResource(
"/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/RecordPatternsInEnhancedFor.java",
"20-preview"
);
DataflowResult dataflow = DataflowPass.getDataflowResult(ast);
assertThat(dataflow.getUnusedAssignments(), Matchers.hasSize(2));
}
}
| 930 | 24.861111 | 106 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/internal/JavaRuleUtilTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.internal;
import static net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil.containsCamelCaseWord;
import static net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil.startsWithCamelCaseWord;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class JavaRuleUtilTest extends BaseParserTest {
@Test
void testCamelCaseWords() {
assertFalse(startsWithCamelCaseWord("getter", "get"), "no word boundary");
assertFalse(startsWithCamelCaseWord("get", "get"), "no following word");
assertTrue(startsWithCamelCaseWord("getX", "get"), "ok prefix");
assertFalse(startsWithCamelCaseWord("ge", "get"), "shorter word");
assertThrows(NullPointerException.class, () -> startsWithCamelCaseWord(null, "get"));
assertThrows(NullPointerException.class, () -> startsWithCamelCaseWord("fnei", null));
}
@Test
void testContainsCamelCaseWords() {
assertFalse(containsCamelCaseWord("isABoolean", "Bool"), "no word boundary");
assertTrue(containsCamelCaseWord("isABoolean", "A"), "ok word in the middle");
assertTrue(containsCamelCaseWord("isABoolean", "Boolean"), "ok word at the end");
assertThrows(NullPointerException.class, () -> containsCamelCaseWord(null, "A"));
assertThrows(NullPointerException.class, () -> containsCamelCaseWord("fnei", null));
assertThrows(AssertionError.class, () -> containsCamelCaseWord("fnei", ""), "empty string");
assertThrows(AssertionError.class, () -> containsCamelCaseWord("fnei", "a"), "not capitalized");
}
}
| 1,916 | 42.568182 | 104 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/InvocationMatcherTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static net.sourceforge.pmd.lang.java.types.InvocationMatcher.parse;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
class InvocationMatcherTest extends BaseParserTest {
@Test
void testSimpleMatcher() {
ASTMethodCall call =
java.parse("class Foo {{ Integer.valueOf('c'); }}")
.descendants(ASTMethodCall.class).firstOrThrow();
assertMatch(call, "_#valueOf(int)");
assertMatch(call, "java.lang.Integer#valueOf(int)");
assertMatch(call, "java.lang.Integer#_(int)");
assertMatch(call, "java.lang.Integer#_(_*)");
assertNoMatch(call, "java.lang.Integer#valueOf(char)");
assertNoMatch(call, "java.lang.Integer#valueOf2(_*)");
assertNoMatch(call, "java.lang.Object#valueOf(_*)");
}
@Test
void testCtorMatchers() {
ASTConstructorCall call =
java.parse("class Foo {{ new java.util.ArrayList('c'); }}")
.descendants(ASTConstructorCall.class).firstOrThrow();
assertMatch(call, "_#new(int)");
assertMatch(call, "java.util.ArrayList#new(int)");
assertMatch(call, "java.util.ArrayList#_(int)");
assertMatch(call, "java.util.ArrayList#_(_*)");
assertNoMatch(call, "java.util.ArrayList#new()");
assertNoMatch(call, "java.util.ArrayList#_()");
assertNoMatch(call, "java.util.List#new(_*)");
assertNoMatch(call, "java.util.List#_(_*)");
assertNoMatch(call, "java.lang.Object#new(int)");
}
@Test
void testArray() {
ASTMethodCall call =
java.parse("class Foo {{ new int[0].toString(); }}")
.descendants(ASTMethodCall.class).firstOrThrow();
assertMatch(call, "int[]#toString()");
assertMatch(call, "_#toString()");
assertMatch(call, "int[]#_()");
assertMatch(call, "int[]#_(_*)");
assertMatch(call, "_#_(_*)");
assertNoMatch(call, "_#new(int)");
assertNoMatch(call, "_[][]#_(_*)");
// maybe we should support this one later
assertNoMatch(call, "_[]#toString()");
}
@Test
void testWhitespaceErrorMessage() {
parse("_#_(int,int)"); // does not fail
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> parse("_#_(int, int)"));
assertThat(e.getMessage(), equalTo("Expected type at index 8:\n"
+ " \"_#_(int, int)\"\n"
+ " ^\n"));
}
private void assertMatch(InvocationNode call, String sig) {
assertTrue(parse(sig).matchesCall(call), sig + " should match " + call);
}
private void assertNoMatch(InvocationNode call, String s) {
assertFalse(parse(s).matchesCall(call), s + " should not match " + call);
}
}
| 3,486 | 34.581633 | 112 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/TypesTreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.InvocationNode;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
/**
*
*/
class TypesTreeDumpTest extends BaseTreeDumpTest {
TypesTreeDumpTest() {
super(new JavaTypeAttrPrinter(), ".java");
}
@Override
public @NonNull BaseParsingHelper<?, ?> getParser() {
return JavaParsingHelper.DEFAULT.withResourceContext(getClass());
}
@Test
void testIteratorUtilCopy() {
doTest("IteratorUtilCopy");
}
@Override
protected @NonNull String normalize(@NonNull String str) {
return super.normalize(str)
// capture IDs are unstable from run to run
.replaceAll("capture#-?\\d+", "capture#...");
}
/**
* Only prints the type of type nodes
*/
private static class JavaTypeAttrPrinter extends RelevantAttributePrinter {
@Override
protected void fillAttributes(@NonNull Node node, @NonNull List<AttributeInfo> result) {
if (node instanceof TypeNode) {
result.add(new AttributeInfo("TypeMirror", ((TypeNode) node).getTypeMirror().toString()));
}
if (node instanceof InvocationNode) {
InvocationNode invoc = (InvocationNode) node;
result.add(new AttributeInfo("MethodName", invoc.getMethodName()));
result.add(new AttributeInfo("VarargsCall", invoc.getOverloadSelectionInfo().isVarargsCall()));
result.add(new AttributeInfo("Unchecked", invoc.getOverloadSelectionInfo().needsUncheckedConversion()));
result.add(new AttributeInfo("Failed", invoc.getOverloadSelectionInfo().isFailed()));
result.add(new AttributeInfo("Function", TypePrettyPrint.prettyPrint(invoc.getMethodType())));
}
if (node instanceof ASTNamedReferenceExpr) {
result.add(new AttributeInfo("Name", ((ASTNamedReferenceExpr) node).getName()));
}
if (node instanceof ASTVariableDeclaratorId) {
result.add(new AttributeInfo("Name", ((ASTVariableDeclaratorId) node).getName()));
}
if (node instanceof ASTMethodDeclaration) {
result.add(new AttributeInfo("Name", ((ASTMethodDeclaration) node).getName()));
}
}
@Override
protected boolean ignoreAttribute(@NonNull Node node, @NonNull Attribute attribute) {
return true;
}
}
}
| 3,296 | 37.337209 | 120 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/GenericMethodReferenceTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.function.Supplier;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.types.testdata.GenericMethodReference;
class GenericMethodReferenceTest {
@Test
void typeResolveVariable() {
ASTCompilationUnit root = JavaParsingHelper.DEFAULT.parseClass(GenericMethodReference.class);
root.descendants(ASTVariableDeclaratorId.class).forEach(variable -> {
assertTrue(variable.getName().startsWith("supplier"));
@Nullable
JTypeDeclSymbol symbol = variable.getInitializer().getTypeMirror().getSymbol();
assertEquals(Supplier.class.getSimpleName(), symbol.getSimpleName());
});
}
}
| 1,253 | 34.828571 | 101 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/TypeTestUtilTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.concurrent.Callable;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotationTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTAnonymousClassDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.types.testdata.SomeClassWithAnon;
class TypeTestUtilTest extends BaseParserTest {
@Test
void testIsAFallback() {
ASTClassOrInterfaceDeclaration klass =
java.parse("package org; import java.io.Serializable; "
+ "class FooBar implements Serializable {}")
.getFirstDescendantOfType(ASTClassOrInterfaceDeclaration.class);
assertNull(klass.getType());
assertTrue(TypeTestUtil.isA("org.FooBar", klass));
assertTrue(TypeTestUtil.isA("java.io.Serializable", klass));
assertTrue(TypeTestUtil.isA(Serializable.class, klass));
}
@Test
void testIsAFallbackWithUnresolvedClassReference() { // != declaration
ASTAnnotation annot =
java.parse("import a.b.Test;"
+ "class FooBar { @Test void bar() {} }")
.getFirstDescendantOfType(ASTAnnotation.class);
assertTrue(TypeTestUtil.isA("a.b.Test", annot));
assertTrue(TypeOps.isUnresolved(annot.getTypeMirror()));
assertFalse(TypeTestUtil.isA(org.junit.Test.class, annot));
assertFalse(TypeTestUtil.isA("org.junit.Test", annot));
assertFalse(TypeTestUtil.isA(Override.class, annot));
assertFalse(TypeTestUtil.isA("java.lang.Override", annot));
}
@Test
void testIsAFallbackEnum() {
ASTEnumDeclaration klass =
java.parse("package org; "
+ "enum FooBar implements Iterable {}")
.getFirstDescendantOfType(ASTEnumDeclaration.class);
assertNull(klass.getType());
assertTrue(TypeTestUtil.isA("org.FooBar", klass));
assertIsStrictSubtype(klass, Iterable.class);
assertIsStrictSubtype(klass, Enum.class);
assertIsStrictSubtype(klass, Serializable.class);
assertIsStrictSubtype(klass, Object.class);
}
@Test
void testIsAnArrayClass() {
ASTType arrayT =
java.parse("import java.io.ObjectStreamField; "
+ "class Foo { private static final ObjectStreamField[] serialPersistentFields; }")
.getFirstDescendantOfType(ASTType.class);
assertIsExactlyA(arrayT, ObjectStreamField[].class);
assertIsStrictSubtype(arrayT, Object[].class);
assertIsStrictSubtype(arrayT, Serializable.class);
assertIsNot(arrayT, Serializable[].class);
assertIsStrictSubtype(arrayT, Object.class);
}
@Test
void testIsAnAnnotationClass() {
ASTType arrayT =
java.parse("class Foo { org.junit.Test field; }")
.getFirstDescendantOfType(ASTType.class);
assertIsExactlyA(arrayT, org.junit.Test.class);
assertIsStrictSubtype(arrayT, Annotation.class);
assertIsStrictSubtype(arrayT, Object.class);
}
@Test
void testIsAPrimitiveArrayClass() {
ASTType arrayT =
java.parse("import java.io.ObjectStreamField; "
+ "class Foo { private static final int[] serialPersistentFields; }")
.getFirstDescendantOfType(ASTType.class);
assertIsExactlyA(arrayT, int[].class);
assertIsNot(arrayT, long[].class);
assertIsNot(arrayT, Object[].class);
assertIsStrictSubtype(arrayT, Serializable.class);
assertIsStrictSubtype(arrayT, Object.class);
}
@Test
void testIsAPrimitiveSubtype() {
ASTType arrayT =
java.parse("import java.io.ObjectStreamField; "
+ "class Foo { private static final int serialPersistentFields; }")
.getFirstDescendantOfType(ASTType.class);
assertIsExactlyA(arrayT, int.class);
assertIsNot(arrayT, long.class);
assertIsNot(arrayT, double.class);
assertIsNot(arrayT, float.class);
assertIsNot(arrayT, Object.class);
}
@Test
void testIsAFallbackAnnotation() {
ASTAnnotationTypeDeclaration klass =
java.parse("package org; import foo.Stuff;"
+ "public @interface FooBar {}")
.getFirstDescendantOfType(ASTAnnotationTypeDeclaration.class);
assertNull(klass.getType());
assertTrue(TypeTestUtil.isA("org.FooBar", klass));
assertIsA(klass, Annotation.class);
assertIsA(klass, Object.class);
}
@Test
void testIsATypeVarWithUnresolvedBound() {
// a type var with an unresolved bound should not be considered
// a subtype of everything
ASTType field =
java.parse("class Foo<T extends Unresolved> {\n"
+ "\tT field;\n"
+ "}")
.descendants(ASTFieldDeclaration.class)
.firstOrThrow().getTypeNode();
assertIsA(field, Object.class);
assertIsNot(field, String.class);
}
@Test
void testIsAStringWithTypeArguments() {
ASTAnyTypeDeclaration klass =
java.parse("package org;"
+ "public class FooBar {}")
.getFirstDescendantOfType(ASTAnyTypeDeclaration.class);
assertThrows(IllegalArgumentException.class,
() -> TypeTestUtil.isA("java.util.List<java.lang.String>", klass));
}
@Test
void testIsAStringWithTypeArgumentsAnnotation() {
ASTAnyTypeDeclaration klass =
java.parse("package org;"
+ "public @interface FooBar {}")
.getFirstDescendantOfType(ASTAnyTypeDeclaration.class);
assertThrows(IllegalArgumentException.class, () ->
TypeTestUtil.isA("java.util.List<java.lang.String>", klass));
}
@Test
void testAnonClassTypeNPE() {
// #2756
ASTAnonymousClassDeclaration anon =
java.parseClass(SomeClassWithAnon.class)
.getFirstDescendantOfType(ASTAnonymousClassDeclaration.class);
assertTrue(anon.getSymbol().isAnonymousClass(), "Anon class");
assertTrue(TypeTestUtil.isA(Runnable.class, anon), "Should be a Runnable");
// This is not a canonical name, so we give up early
assertFalse(TypeTestUtil.isA(SomeClassWithAnon.class.getName() + "$1", anon));
assertFalse(TypeTestUtil.isExactlyA(SomeClassWithAnon.class.getName() + "$1", anon));
// this is the failure case: if the binary name doesn't match, we test the canoname, which was null
assertFalse(TypeTestUtil.isA(Callable.class, anon));
assertFalse(TypeTestUtil.isA(Callable.class.getCanonicalName(), anon));
assertFalse(TypeTestUtil.isExactlyA(Callable.class, anon));
assertFalse(TypeTestUtil.isExactlyA(Callable.class.getCanonicalName(), anon));
}
/**
* If we don't have the annotation on the classpath,
* we should resolve the full name via the import, if possible
* and compare then. Only after that, we should compare the
* simple names.
*/
@Test
void testIsAFallbackAnnotationSimpleNameImport() {
ASTAnnotation annotation = java.parse("package org; import foo.Stuff; @Stuff public class FooBar {}")
.getFirstDescendantOfType(ASTAnnotation.class);
assertNull(annotation.getType());
assertTrue(TypeTestUtil.isA("foo.Stuff", annotation));
assertFalse(TypeTestUtil.isA("other.Stuff", annotation));
// we know it's not Stuff, it's foo.Stuff
assertFalse(TypeTestUtil.isA("Stuff", annotation));
}
@Test
void testNullNode() {
assertFalse(TypeTestUtil.isA(String.class, (TypeNode) null));
assertFalse(TypeTestUtil.isA("java.lang.String", (JTypeMirror) null));
assertFalse(TypeTestUtil.isA("java.lang.String", (TypeNode) null));
assertFalse(TypeTestUtil.isExactlyA(String.class, (TypeNode) null));
assertFalse(TypeTestUtil.isExactlyA("java.lang.String", null));
}
@Test
void testNullClass() {
final ASTAnnotation node = java.parse("package org; import foo.Stuff; @Stuff public class FooBar {}")
.getFirstDescendantOfType(ASTAnnotation.class);
assertNotNull(node);
assertThrows(NullPointerException.class, () -> TypeTestUtil.isA((String) null, node));
assertThrows(NullPointerException.class, () -> TypeTestUtil.isA((Class<?>) null, node));
assertThrows(NullPointerException.class, () -> TypeTestUtil.isExactlyA((Class<?>) null, node));
assertThrows(NullPointerException.class, () -> TypeTestUtil.isExactlyA((String) null, node));
}
private void assertIsA(TypeNode node, Class<?> type) {
assertIsA(node, type, false, true);
}
private void assertIsExactlyA(TypeNode node, Class<?> type) {
assertIsA(node, type, true, true);
assertIsA(node, type, false, true);
}
private void assertIsNot(TypeNode node, Class<?> type) {
assertIsA(node, type, true, false);
assertIsA(node, type, false, false);
}
private void assertIsNotExactly(TypeNode node, Class<?> type) {
assertIsA(node, type, true, false);
}
private void assertIsStrictSubtype(TypeNode node, Class<?> type) {
assertIsNotExactly(node, type);
assertIsA(node, type);
}
private void assertIsA(TypeNode node, Class<?> type, boolean exactly, boolean expectTrue) {
assertEquals(expectTrue,
exactly ? TypeTestUtil.isExactlyA(type, node)
: TypeTestUtil.isA(type, node),
"TypeTestUtil::isA with class arg: " + type.getCanonicalName());
assertEquals(expectTrue,
exactly ? TypeTestUtil.isExactlyA(type.getCanonicalName(), node)
: TypeTestUtil.isA(type.getCanonicalName(), node),
"TypeTestUtil::isA with string arg: " + type.getCanonicalName());
}
}
| 11,280 | 36.108553 | 110 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/Overloads.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
import static java.util.EnumSet.noneOf;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
public class Overloads {
private Overloads() {
}
public static void ambig(String s1, String s2, CharSequence... args) {
}
public static void ambig(String s1, CharSequence... args) {
}
@SafeVarargs
public static <T> List<T> genericOf(T... args) {
return Collections.emptyList();
}
public static <T> List<T> genericOf(T arg) {
return Collections.emptyList();
}
// these are disambiguated with phases
@SafeVarargs
public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) {
EnumSet<E> result = noneOf(first.getDeclaringClass());
result.add(first);
Collections.addAll(result, rest);
return result;
}
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2) {
EnumSet<E> result = noneOf(e1.getDeclaringClass());
result.add(e1);
result.add(e2);
return result;
}
public static <E extends Enum<E>> EnumSet<E> of(E e) {
EnumSet<E> result = noneOf(e.getDeclaringClass());
result.add(e);
return result;
}
}
| 1,365 | 22.152542 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/DummyCompiledClass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
public class DummyCompiledClass {
public String toString() {
return getClass().toString();
}
}
| 254 | 20.25 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/MutualTypeRecursion.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
public class MutualTypeRecursion
<T extends MutualTypeRecursion<T, S>,
S extends MutualTypeRecursion<S, T>> {
}
| 269 | 19.769231 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/SomeEnum.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
public enum SomeEnum {
FOO,
BAR
}
| 186 | 14.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/MyListAbstract.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
/**
* @see <a href="https://github.com/pmd/pmd/issues/3101">[java] NullPointerException when running PMD under JRE 11 #3101</a>
*/
public abstract class MyListAbstract<E> implements MyList<E> {
public <E> MyListAbstract<E> of(E e1) {
return null;
}
}
| 413 | 24.875 | 124 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/LubTestData.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
public class LubTestData {
public interface I1 {
}
public interface I2<T> extends I1 {
}
public interface I3 {
}
public interface I4 {
}
public static class Sub1 implements Comparable<Sub1>, I1, I3 {
@Override
public int compareTo(LubTestData.Sub1 o) {
return 0;
}
}
public static class Sub2 implements Comparable<Sub2>, I2<I3> {
@Override
public int compareTo(LubTestData.Sub2 o) {
return 0;
}
}
public static class GenericSuper<T> implements I3 {
}
public static class GenericSub<T> extends GenericSuper<T> implements I2<I1> {
}
public static class GenericSub2<T> extends GenericSuper<T> implements I2<I3>, I4 {
}
}
| 921 | 17.078431 | 86 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/LocalGenericClass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
public class LocalGenericClass {
private LocalGenericClass() {
}
public static <T> void localClassInGeneric() {
class MyLocalClass implements MyCombiner<T, Optional<T>, MyLocalClass> {
private T state;
@Override
public void accept(T t) { }
@Override
public Optional<T> get() {
return Optional.empty();
}
@Override
public void combine(MyLocalClass other) {
accept(other.state);
}
}
new MyLocalClass();
}
private interface MyCombiner<R, S, T> extends MyConsumer<R>, MySupplier<S> {
void combine(T t);
}
private interface MyConsumer<R> {
void accept(R r);
}
private interface MySupplier<S> {
S get();
}
private static class Optional<T> {
public static <T> Optional<T> empty() {
return new Optional<T>();
}
}
}
| 1,130 | 18.842105 | 80 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/ComparableList.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
// test class for intersections
public class ComparableList<T> extends ArrayList<T> implements Comparable<List<T>> {
@Override
public int compareTo(@NonNull List<T> o) {
return 0;
}
}
| 461 | 21 | 84 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/BoolLogic.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
public class BoolLogic {
static False FALSE() { // SUPPRESS CHECKSTYLE NOW
return new False() { };
}
static True TRUE() { // SUPPRESS CHECKSTYLE NOW
return new True() { };
}
static False and(False a, False b) {
return a;
}
static False and(True a, False b) {
return b;
}
static False and(False a, True b) {
return a;
}
static True and(True a, True b) {
return a;
}
static False or(False a, False b) {
return a;
}
static True or(True a, False b) {
return a;
}
static True or(False a, True b) {
return b;
}
static True or(True a, True b) {
return a;
}
interface Bool { }
interface False extends Bool { }
interface True extends Bool { }
private BoolLogic() {
}
}
| 997 | 16.206897 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/GenericMethodReference.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
import java.util.function.Supplier;
public final class GenericMethodReference {
{
// the constructor is not generic, so <Integer> is unused, but that should just be ignored
Supplier<GenericMethodReference> supplier1 = GenericMethodReference::<Integer>new;
Supplier<GenericMethodReference> supplier2 = GenericMethodReference::<Integer, String>new;
// the create1 method is not generic - any provided types should be ignored
Supplier<GenericMethodReference> supplier3 = GenericMethodReference::<Integer>create1;
Supplier<GenericMethodReference> supplier4 = GenericMethodReference::<Integer, String>create1;
// the create2 method is generic, but takes only one parameter
Supplier<GenericMethodReference> supplier5 = GenericMethodReference::<Integer>create2;
// providing too many parameter here is a compile error
//Supplier<GenericMethodReference> supplier6 = GenericMethodReference::<Integer, String>create2;
}
public static GenericMethodReference create1() {
return null;
}
public static <T> GenericMethodReference create2() {
return null;
}
private GenericMethodReference() {
}
}
| 1,359 | 35.756757 | 104 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/SomeClassWithAnon.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
/**
* #2756
*/
public class SomeClassWithAnon {
{
new Runnable() {
@Override
public void run() {
}
};
}
}
| 318 | 11.269231 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/AnnotationWithEnum.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
public @interface AnnotationWithEnum {
Foo value();
enum Foo {
A, B
}
}
| 237 | 14.866667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/GenericFbound.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
/**
* @author Clément Fournier
*/
public class GenericFbound<T extends GenericFbound<T>> {
public class Inst extends GenericFbound<Inst> {
}
public class InstRaw extends GenericFbound {
}
public class InstRec extends GenericFbound<T> {
}
}
| 416 | 15.68 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/MyList.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
/**
* @see <a href="https://github.com/pmd/pmd/issues/3101">[java] NullPointerException when running PMD under JRE 11 #3101</a>
*/
public interface MyList<E> {
<E> MyList<E> of(E e1);
}
| 336 | 23.071429 | 124 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/TypeInferenceTestCases.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TypeInferenceTestCases {
private TypeInferenceTestCases() {
}
public static <K, L extends List<K>> L appendL(List<? extends K> in, L top) {
top.addAll(in);
// this is just to add imports
new ArrayList<>(Arrays.asList(3, 3));
Stream.of(2).collect(Collectors.toList());
new LinkedList<>();
return top;
}
public static <T> List<T> makeThree(Supplier<T> factory) {
return Collections.emptyList();
}
public static <T, K> T wild(K t) {
return null;
}
public static <U> List<U> m(List<U> src) {
return null;
}
public static <T> T id(T t) {
return t;
}
}
| 1,079 | 21.5 | 81 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/testdata/SomeConstants.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.testdata;
public class SomeConstants {
public static short aShort = 1;
public static byte aByte = 1;
private SomeConstants() {
}
}
| 283 | 16.75 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/internal/infer/InferenceCtxUnitTests.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.lang.java.types.TestUtilitiesForTypesKt.captureMatcher;
import static net.sourceforge.pmd.lang.java.types.internal.infer.BaseTypeInferenceUnitTest.Bound.eqBound;
import static net.sourceforge.pmd.lang.java.types.internal.infer.BaseTypeInferenceUnitTest.Bound.lower;
import static net.sourceforge.pmd.lang.java.types.internal.infer.BaseTypeInferenceUnitTest.Bound.upper;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypeOps;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
/**
*
*/
class InferenceCtxUnitTests extends BaseTypeInferenceUnitTest {
@Test
void testHasPrimaryBound() {
TypeInferenceLogger log = spy(TypeInferenceLogger.noop());
InferenceContext ctx = emptyCtx(log);
InferenceVar v1 = newIvar(ctx);
InferenceVar v2 = newIvar(ctx, ts.SERIALIZABLE);
assertThat(v1, hasBound(BoundKind.UPPER, ts.OBJECT));
assertThat(v2, hasBound(BoundKind.UPPER, ts.SERIALIZABLE));
assertTrue(v1.hasOnlyPrimaryBound());
assertTrue(v2.hasOnlyPrimaryBound());
JTypeMirror listOfV1 = listType(v1);
TypeOps.isConvertible(v2, listOfV1);
assertThat(v2, hasBoundsExactly(upper(ts.SERIALIZABLE), upper(listOfV1)));
assertFalse(v2.hasOnlyPrimaryBound());
assertTrue(v1.hasOnlyPrimaryBound());
verify(log).boundAdded(ctx, v2, BoundKind.UPPER, listOfV1, false);
}
@Test
void testBoundsOnConvertibilityCheck() {
TypeInferenceLogger log = spy(TypeInferenceLogger.noop());
InferenceContext ctx = emptyCtx(log);
InferenceVar v1 = newIvar(ctx);
InferenceVar v2 = newIvar(ctx);
assertThat(v2, hasBound(BoundKind.UPPER, ts.OBJECT));
assertThat(v1, hasBound(BoundKind.UPPER, ts.OBJECT));
JTypeMirror listOfV1 = listType(v1);
TypeOps.isConvertible(v2, listOfV1);
assertThat(v2, hasBoundsExactly(upper(listOfV1), upper(ts.OBJECT)));
verify(log).boundAdded(ctx, v2, BoundKind.UPPER, listOfV1, false);
}
@Test
void testEqBoundWithGenerics() {
TypeInferenceLogger log = spy(TypeInferenceLogger.noop());
InferenceContext ctx = emptyCtx(log);
InferenceVar v1 = newIvar(ctx);
InferenceVar v2 = newIvar(ctx);
JTypeMirror listOfV1 = listType(v1);
JTypeMirror listOfListOfV2 = listType(listType(v2));
TypeOps.isConvertible(listOfV1, listOfListOfV2);
assertThat(v1, hasBoundsExactly(eqBound(listType(v2)), upper(ts.OBJECT)));
assertThat(v2, hasBoundsExactly(upper(ts.OBJECT)));
ctx.incorporate();
verify(log, never()).ivarMerged(any(), any(), any());
assertFalse(v1.isEquivalentTo(v2));
assertFalse(v2.isEquivalentTo(v1));
ctx.solve();
assertEquals(ts.OBJECT, v2.getInst());
assertEquals(listType(ts.OBJECT), v1.getInst());
}
@Test
void testEqBoundMergesIvar() {
TypeInferenceLogger log = spy(TypeInferenceLogger.noop());
InferenceContext ctx = emptyCtx(log);
InferenceVar v1 = newIvar(ctx);
InferenceVar v2 = newIvar(ctx);
JTypeMirror listOfV1 = listType(v1);
JTypeMirror listOfV2 = listType(v2);
TypeOps.isConvertible(listOfV1, listOfV2);
assertThat(v2, hasBoundsExactly(eqBound(v1), upper(ts.OBJECT)));
assertThat(v1, hasBoundsExactly(upper(ts.OBJECT))); // bound is propagated to v1 later
ctx.incorporate();
verify(log, times(1)).ivarMerged(ctx, v2, v1);
assertTrue(v1.isEquivalentTo(v2));
assertTrue(v2.isEquivalentTo(v1));
}
@Test
void testSymmetricPropagationOfUpper() {
TypeInferenceLogger log = spy(TypeInferenceLogger.noop());
InferenceContext ctx = emptyCtx(log);
InferenceVar a = newIvar(ctx);
InferenceVar b = newIvar(ctx);
// 'a <: 'b
// ~> 'b >: 'a
addSubtypeConstraint(ctx, a, b);
assertThat(a, hasBoundsExactly(upper(b)));
assertThat(b, hasBoundsExactly(lower(a)));
verify(log, never()).ivarMerged(any(), any(), any());
verify(log, times(2)).boundAdded(any(), any(), any(), any(), eq(false));
verify(log, never()).boundAdded(any(), any(), any(), any(), eq(true));
}
@Test
void testWildLowerLower() {
InferenceContext ctx = emptyCtx();
InferenceVar a = newIvar(ctx);
InferenceVar b = newIvar(ctx);
// List<? super 'a> <: List<? super 'b>
// ~> 'b <: 'a
addSubtypeConstraint(ctx, listType(superWild(a)), listType(superWild(b)));
assertThat(a, hasBoundsExactly(lower(b)));
assertThat(b, hasBoundsExactly(upper(a)));
}
@Test
void testWildUpperUpper() {
InferenceContext ctx = emptyCtx();
InferenceVar a = newIvar(ctx);
InferenceVar b = newIvar(ctx);
// List<? extends 'a> <: List<? extends 'b>
// ~> 'a <: 'b
addSubtypeConstraint(ctx, listType(extendsWild(a)), listType(extendsWild(b)));
assertThat(a, hasBoundsExactly(upper(b)));
assertThat(b, hasBoundsExactly(lower(a)));
}
/* Remember:
let S, T != Object, S <: T
G<? super T> </: G<? extends T>
G<? extends T> </: G<? super T>
G<? super T> <: G<? super S>
G<? extends S> <: G<? extends T>
if T = Object, then G<? extends T> = G<?>, and
G<A> <: G<?> forall A (incl. wildcards)
*/
@Test
void testWildLowerUpper() {
InferenceContext ctx = emptyCtx();
InferenceVar a = newIvar(ctx);
InferenceVar b = newIvar(ctx);
// List<? super 'a> <: List<? extends 'b>
// ~> 'b >: Object
addSubtypeConstraint(ctx, listType(superWild(a)), listType(extendsWild(b)));
assertThat(b, hasBoundsExactly(upper(ts.OBJECT), lower(ts.OBJECT)));
assertThat(a, hasBoundsExactly(upper(ts.OBJECT)));
}
@Test
void testWildUpperLower() {
InferenceContext ctx = emptyCtx();
InferenceVar a = newIvar(ctx);
InferenceVar b = newIvar(ctx);
// List<? extends 'a> <: List<? super 'b>
// ~> 'b <: capture of ? extends 'a
// Proof:
// capture(List<? extends 'a>) <: List<? super 'b>
// |- List<capture of ? extends 'a> <: List<? super 'b>
// |- capture of ? extends 'a <= ? super 'b
// |- lower(? super 'b) <: lower(capture of ? extends 'a)
// |- 'b <: capture of ? extends 'a
// |- upper(capture of ? extends 'a) <: upper(? super 'b)
// |- 'a <: Object
// Note that lower(capture of ? extends 'a) does not reduce to
// the null type, as that would be useless and disprove valid programs.
addSubtypeConstraint(ctx, listType(extendsWild(a)), listType(superWild(b)));
assertThat(b, hasBoundsExactly(upper(ts.OBJECT), upper(captureMatcher(extendsWild(a)))));
assertThat(a, hasBoundsExactly(upper(ts.OBJECT)));
}
@Test
void testIntersectionRight() {
InferenceContext ctx = emptyCtx();
InferenceVar a = newIvar(ctx);
InferenceVar b = newIvar(ctx);
// 'a <: List<? extends 'b> & Serializable
// ~> 'b >: List<? extends 'a>
// ~> 'b >: Serializable
JTypeMirror listOfB = listType(extendsWild(b));
addSubtypeConstraint(ctx,
a,
intersect(listOfB, ts.SERIALIZABLE));
assertThat(a, hasBoundsExactly(upper(ts.SERIALIZABLE), upper(listOfB)));
assertThat(b, hasBoundsExactly(upper(ts.OBJECT)));
}
@Test
void testIntersectionLeft() {
InferenceContext ctx = emptyCtx();
InferenceVar a = newIvar(ctx);
InferenceVar b = newIvar(ctx);
// List<? extends 'a> & Serializable <: 'b
// ~> 'b >: List<? extends 'a> & Serializable
// Note that this does not split the intersection into several constraints, like eg
// 'b >: List<? extends 'a>
// 'b >: Serializable
// This is because those constraints together would require 'b
// to be a supertype of both, whereas `'b >: x & y` only requires
// that 'b be a supertype of either
// When the intersection is on the right it is appropriate to split it,
// in order to have more constraints to propagate
JTypeMirror listOfA = listType(extendsWild(a));
addSubtypeConstraint(ctx,
intersect(listOfA, ts.SERIALIZABLE),
b);
assertThat(a, hasBoundsExactly(upper(ts.OBJECT)));
assertThat(b, hasBoundsExactly(lower(intersect(listOfA, ts.SERIALIZABLE))));
}
@Test
void testArrayLower() {
InferenceContext ctx = emptyCtx();
InferenceVar a = newIvar(ctx);
// Boolean[] <: 'a[]
// ~> Boolean <: 'a
addSubtypeConstraint(ctx,
ts.arrayType(ts.BOOLEAN.box()),
ts.arrayType(a));
assertThat(a, hasBoundsExactly(lower(ts.BOOLEAN.box())));
}
@Test
void testArrayUpper() {
InferenceContext ctx = emptyCtx();
InferenceVar a = newIvar(ctx);
// 'a[] <: Boolean[]
// ~> 'a <: Boolean
addSubtypeConstraint(ctx,
ts.arrayType(a),
ts.arrayType(ts.BOOLEAN.box()));
assertThat(a, hasBoundsExactly(upper(ts.BOOLEAN.box())));
}
}
| 10,386 | 31.561129 | 105 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/internal/infer/BaseTypeInferenceUnitTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.types.internal.infer;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.SelfDescribing;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JIntersectionType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.JTypeVar;
import net.sourceforge.pmd.lang.java.types.JWildcardType;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.internal.infer.InferenceVar.BoundKind;
/**
*
*/
class BaseTypeInferenceUnitTest {
protected final TypeSystem ts = JavaParsingHelper.TEST_TYPE_SYSTEM;
protected final JClassSymbol listSym = ts.getClassSymbol(List.class);
protected InferenceContext emptyCtx() {
return emptyCtx(TypeInferenceLogger.noop());
}
protected InferenceContext emptyCtx(TypeInferenceLogger log) {
return new InferenceContext(ts, new SupertypeCheckCache(), Collections.emptyList(), log);
}
protected InferenceVar newIvar(InferenceContext ctx) {
return newIvar(ctx, ts.OBJECT);
}
protected InferenceVar newIvar(InferenceContext ctx, JTypeMirror upperBound) {
JTypeVar mock = mock(JTypeVar.class);
when(mock.getTypeSystem()).thenReturn(ts);
when(mock.getLowerBound()).thenReturn(ts.NULL_TYPE);
when(mock.getUpperBound()).thenReturn(upperBound);
return ctx.addVar(mock);
}
/**
* Note: we systematically incorporate because the order in which
* constraints are added should not be overly specified by tests.
* Eg whether {@code a.isConvertibleTo(b)} creates {@code 'a <: 'b} or
* {@code 'b >: 'a} is irrelevant, provided the incorporation phase
* properly propagates either.
*/
protected void addSubtypeConstraint(InferenceContext ctx, JTypeMirror t, JTypeMirror s) {
t.isConvertibleTo(s); // nota: this captures t
ctx.incorporate();
}
protected void subtypeConstraintShouldFail(InferenceContext ctx, JTypeMirror t, JTypeMirror s) {
t.isConvertibleTo(s); // nota: this captures t
assertThrows(ResolutionFailedException.class, ctx::incorporate);
}
@NonNull JTypeMirror listType(JTypeMirror t) {
return ts.parameterise(listSym, listOf(t));
}
@NonNull JWildcardType extendsWild(JTypeMirror t) {
return ts.wildcard(true, t);
}
@NonNull JWildcardType superWild(JTypeMirror t) {
return ts.wildcard(false, t);
}
@NonNull JIntersectionType intersect(JTypeMirror... types) {
JTypeMirror glb = ts.glb(Arrays.asList(types));
assertThat(glb, Matchers.isA(JIntersectionType.class));
return (JIntersectionType) glb;
}
static Matcher<InferenceVar> hasBound(BoundKind kind, JTypeMirror t) {
return new BaseMatcher<InferenceVar>() {
@Override
public void describeTo(Description description) {
}
@Override
public boolean matches(Object actual) {
if (!(actual instanceof InferenceVar)) {
return false;
}
return ((InferenceVar) actual).getBounds(kind).contains(t);
}
};
}
/**
* Exactly, modulo the upper(OBJECT), which can be omitted.
*/
static Matcher<InferenceVar> hasBoundsExactly(Bound... bounds) {
return new BaseMatcher<InferenceVar>() {
@Override
public void describeTo(Description description) {
description.appendText("'_ ");
Bound.describeList(description, Arrays.asList(bounds));
}
@Override
public void describeMismatch(Object item, Description description) {
if (!(item instanceof InferenceVar)) {
description.appendText("Not an ivar: ").appendValue(item);
return;
}
InferenceVar ivar = (InferenceVar) item;
description.appendText("was ");
description.appendText(ivar.getName());
description.appendText(" ");
Bound.describeList(description, getBoundsObj(ivar));
}
@Override
public boolean matches(Object actual) {
if (!(actual instanceof InferenceVar)) {
return false;
}
InferenceVar ivar = (InferenceVar) actual;
JClassType top = ivar.getTypeSystem().OBJECT;
// note: don't use ivar.getBounds(ALL) as this would merge 'a >: T and 'a <: T
Map<BoundKind, Set<JTypeMirror>> actualBounds = getBounds(ivar);
// note: don't use sets/ maps to put Bound instances in,
// as captureMatchers don't support hashing. Also don't
// use Set::contains
// caller may omit OBJECT for conciseness
boolean expectTop = Arrays.stream(bounds).anyMatch(it -> it.kind == BoundKind.UPPER && it.t == top);
// may not have top if it has a different default bound
boolean hasTop = actualBounds.get(BoundKind.UPPER).contains(top);
int numToTest = actualBounds.values().stream().mapToInt(Set::size).sum();
if (!expectTop && hasTop) {
numToTest--;
}
if (numToTest != bounds.length) {
return false;
}
b:
for (Bound bound : bounds) {
for (JTypeMirror t : actualBounds.getOrDefault(bound.kind, Collections.emptySet())) {
if (t.equals(bound.t)) {
numToTest--;
continue b;
}
}
}
return numToTest == 0;
}
};
}
static @NonNull Map<BoundKind, Set<JTypeMirror>> getBounds(InferenceVar actual) {
Map<BoundKind, Set<JTypeMirror>> actualBounds = new HashMap<>();
for (BoundKind kind : BoundKind.values()) {
Set<JTypeMirror> bounds = actual.getBounds(kind);
actualBounds.put(kind, bounds);
if (!bounds.isEmpty()) {
}
}
return actualBounds;
}
static @NonNull Set<Bound> getBoundsObj(InferenceVar actual) {
Set<Bound> bounds = new LinkedHashSet<>();
for (BoundKind kind : BoundKind.values()) {
for (JTypeMirror t : actual.getBounds(kind)) {
bounds.add(new Bound(kind, t));
}
}
return bounds;
}
static class Bound implements SelfDescribing {
final BoundKind kind;
final JTypeMirror t;
Bound(BoundKind kind, JTypeMirror t) {
this.kind = kind;
this.t = t;
}
@Override
public void describeTo(Description description) {
description.appendText(toString());
}
public static Bound lower(JTypeMirror t) {
return new Bound(BoundKind.LOWER, t);
}
public static Bound eqBound(JTypeMirror t) {
return new Bound(BoundKind.EQ, t);
}
public static Bound upper(JTypeMirror t) {
return new Bound(BoundKind.UPPER, t);
}
public static Description describeList(Description description, Collection<Bound> bounds) {
return description.appendList("{", ", ", "}", bounds);
}
@Override
public String toString() {
return "_" + kind.getSym() + t;
}
}
}
| 8,554 | 32.681102 | 116 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/internal/JavaViolationDecoratorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.internal;
import static net.sourceforge.pmd.RuleViolation.CLASS_NAME;
import static net.sourceforge.pmd.RuleViolation.METHOD_NAME;
import static net.sourceforge.pmd.RuleViolation.PACKAGE_NAME;
import static net.sourceforge.pmd.RuleViolation.VARIABLE_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTNumericLiteral;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
/**
* @author Philip Graf
*/
class JavaViolationDecoratorTest {
// TODO there are no tests for anon or local classes
@Test
void testASTFormalParameterVariableName() {
ASTCompilationUnit ast = parse("class Foo { void bar(int x) {} }");
ASTFormalParameter node = ast.descendants(ASTFormalParameter.class).first();
Map<String, String> info = decorate(node);
assertThat(info, hasEntry(VARIABLE_NAME, "x"));
assertThat(info, hasEntry(METHOD_NAME, "bar"));
}
private ASTCompilationUnit parse(final String code) {
return JavaParsingHelper.DEFAULT.parse(code);
}
/**
* Tests that the method name is taken correctly from the given node.
*
* @see <a href="https://sourceforge.net/p/pmd/bugs/1250/">#1250</a>
*/
@Test
void testMethodName() {
ASTCompilationUnit ast = parse("class Foo { void bar(int x) {} }");
ASTMethodDeclaration md = ast.descendants(ASTMethodDeclaration.class).first();
assertThat(decorate(md), hasEntry(METHOD_NAME, "bar"));
}
static Map<String, String> decorate(JavaNode md) {
Map<String, String> result = new HashMap<>();
JavaViolationDecorator.INSTANCE.decorate(md, result);
return result;
}
/**
* Tests that the enum name is taken correctly from the given node.
*/
@Test
void testEnumName() {
ASTCompilationUnit ast = parse("enum Foo {FOO; void bar(int x) {} }");
ASTMethodDeclaration md = ast.descendants(ASTMethodDeclaration.class).first();
assertThat(decorate(md), hasEntry(CLASS_NAME, "Foo"));
}
/**
* Tests that the class name is taken correctly, even if the node is outside
* of a class scope, e.g. a import declaration.
*
* @see <a href="https://sourceforge.net/p/pmd/bugs/1529/">#1529</a>
*/
@Test
void testPackageAndClassNameForImport() {
ASTCompilationUnit ast = parse("package pkg; import java.util.List; public class Foo { }");
ASTImportDeclaration importNode = ast.descendants(ASTImportDeclaration.class).first();
Map<String, String> violation = decorate(importNode);
assertThat(violation, hasEntry(PACKAGE_NAME, "pkg"));
assertThat(violation, hasEntry(CLASS_NAME, "Foo"));
}
@Test
void testPackageAndClassNameForField() {
ASTCompilationUnit ast = parse("package pkg; public class Foo { int a; }");
ASTClassOrInterfaceDeclaration classDeclaration = ast.descendants(ASTClassOrInterfaceDeclaration.class).first();
ASTFieldDeclaration field = ast.descendants(ASTFieldDeclaration.class).first();
Map<String, String> violation = decorate(classDeclaration);
assertThat(violation, hasEntry(PACKAGE_NAME, "pkg"));
assertThat(violation, hasEntry(CLASS_NAME, "Foo"));
violation = decorate(field);
assertThat(violation, hasEntry(PACKAGE_NAME, "pkg"));
assertThat(violation, hasEntry(CLASS_NAME, "Foo"));
}
@Test
void testPackageAndEnumName() {
ASTCompilationUnit ast = parse("package pkg; import java.util.List; public enum FooE { }");
ASTImportDeclaration importNode = ast.descendants(ASTImportDeclaration.class).first();
Map<String, String> violation = decorate(importNode);
assertThat(violation, hasEntry(PACKAGE_NAME, "pkg"));
assertThat(violation, hasEntry(CLASS_NAME, "FooE"));
}
@Test
void testDefaultPackageAndClassName() {
ASTCompilationUnit ast = parse("import java.util.List; public class Foo { }");
ASTImportDeclaration importNode = ast.descendants(ASTImportDeclaration.class).first();
Map<String, String> violation = decorate(importNode);
assertThat(violation, hasEntry(PACKAGE_NAME, ""));
assertThat(violation, hasEntry(CLASS_NAME, "Foo"));
}
@Test
void testPackageAndMultipleClassesName() {
ASTCompilationUnit ast = parse("package pkg; import java.util.List; class Foo { } public class Bar { }");
ASTImportDeclaration importNode = ast.descendants(ASTImportDeclaration.class).first();
Map<String, String> violation = decorate(importNode);
assertThat(violation, hasEntry(PACKAGE_NAME, "pkg"));
assertThat(violation, hasEntry(CLASS_NAME, "Bar"));
}
@Test
void testPackageAndPackagePrivateClassesName() {
ASTCompilationUnit ast = parse("package pkg; import java.util.List; class Foo { }");
ASTImportDeclaration importNode = ast.descendants(ASTImportDeclaration.class).first();
Map<String, String> violation = decorate(importNode);
assertThat(violation, hasEntry(PACKAGE_NAME, "pkg"));
assertThat(violation, hasEntry(CLASS_NAME, "Foo"));
}
/**
* Test that the name of the inner class is taken correctly.
* Also check fields.
*/
@Test
void testInnerClass() {
ASTCompilationUnit ast = parse("class Foo { int a; class Bar { int a; } }");
List<ASTClassOrInterfaceDeclaration> classes = ast.descendants(ASTClassOrInterfaceDeclaration.class).toList();
assertEquals(2, classes.size());
assertThat(decorate(classes.get(0)), hasEntry(CLASS_NAME, "Foo"));
assertThat(decorate(classes.get(1)), hasEntry(CLASS_NAME, "Bar"));
List<ASTFieldDeclaration> fields = ast.descendants(ASTFieldDeclaration.class).crossFindBoundaries().toList();
assertEquals(2, fields.size());
assertThat(decorate(fields.get(0)), hasEntry(CLASS_NAME, "Foo"));
assertThat(decorate(fields.get(1)), hasEntry(CLASS_NAME, "Bar"));
}
@Test
void testInitializers() {
ASTCompilationUnit ast = parse("class Foo { int a = 1; { int x = 2; } }");
List<ASTNumericLiteral> expressions = ast.descendants(ASTNumericLiteral.class).toList();
assertEquals(2, expressions.size());
assertThat(decorate(expressions.get(0)), hasEntry(CLASS_NAME, "Foo"));
assertThat(decorate(expressions.get(0)), hasEntry(VARIABLE_NAME, "a"));
assertThat(decorate(expressions.get(1)), hasEntry(CLASS_NAME, "Foo"));
assertThat(decorate(expressions.get(1)), hasEntry(VARIABLE_NAME, "x"));
}
}
| 7,429 | 39.380435 | 120 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/coverage/PMDCoverageTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.coverage;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.PmdAnalysis;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.java.JavaLanguageModule;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class PMDCoverageTest {
@TempDir
private Path tempFolder;
@Test
void runAllJavaPmdOnSourceTree() {
runPmd("src/main/java", conf -> {});
}
@Test
void runAllJavaPmdOnTestResourcesWithLatestJavaVersion() {
LanguageVersion latest = JavaLanguageModule.getInstance().getLatestVersion();
runPmd("src/test/resources", conf -> conf.setDefaultLanguageVersion(latest));
}
/**
* Run the PMD command line tool, i.e. call PMD.main().
*/
private void runPmd(String inputPath, Consumer<PMDConfiguration> configure) {
StringBuilder report = new StringBuilder("missing report");
try {
Path f = Files.createTempFile(tempFolder, PMDCoverageTest.class.getSimpleName(), null);
String output = SystemLambda.tapSystemOut(() -> {
String errorOutput = SystemLambda.tapSystemErr(() -> {
PMDConfiguration conf = new PMDConfiguration();
conf.addInputPath(Paths.get(inputPath));
conf.setReportFile(f);
conf.addRuleSet("rulesets/internal/all-java.xml");
conf.setThreads(Runtime.getRuntime().availableProcessors());
configure.accept(conf);
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
pmd.performAnalysis();
}
report.setLength(0);
report.append(IOUtil.readFileToString(f.toFile(), StandardCharsets.UTF_8));
});
assertThat(errorOutput, not(containsString("Exception applying rule")));
assertThat(errorOutput, not(containsString("Ruleset not found")));
assertThat(errorOutput, not(containsString("Use of deprecated attribute")));
});
assertThat(output, is(emptyString()));
// No processing errors expected
assertThat(report.toString(), not(containsString("Error while processing")));
// we might have explicit examples of parsing errors, so these are maybe false positives
// these examples of parsing errors need to be excluded in rulesets/internal/all-java.xml via
// exclude-patterns.
assertThat(report.toString(), not(containsString("Error while parsing")));
} catch (IOException ioe) {
fail("Problem creating temporary file: " + ioe.getLocalizedMessage());
} catch (AssertionError ae) {
System.out.println("\nReport:\n");
System.out.println(report);
throw ae;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 3,704 | 36.806122 | 105 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/cpd/MatchAlgorithmTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.jupiter.api.Test;
class MatchAlgorithmTest {
private static final String LINE_1 = "public class Foo { ";
private static final String LINE_2 = " public void bar() {";
private static final String LINE_3 = " System.out.println(\"hello\");";
private static final String LINE_4 = " System.out.println(\"hello\");";
private static final String LINE_5 = " int i = 5";
private static final String LINE_6 = " System.out.print(\"hello\");";
private static final String LINE_7 = " }";
private static final String LINE_8 = "}";
private static String getSampleCode() {
return LINE_1 + "\n" + LINE_2 + "\n" + LINE_3 + "\n" + LINE_4 + "\n" + LINE_5 + "\n" + LINE_6
+ "\n" + LINE_7 + "\n" + LINE_8;
}
@Test
void testSimple() throws IOException {
JavaTokenizer tokenizer = new JavaTokenizer();
SourceCode sourceCode = new SourceCode(new SourceCode.StringCodeLoader(getSampleCode(), "Foo.java"));
Tokens tokens = new Tokens();
TokenEntry.clearImages();
tokenizer.tokenize(sourceCode, tokens);
assertEquals(41, tokens.size());
Map<String, SourceCode> codeMap = new HashMap<>();
codeMap.put("Foo.java", sourceCode);
MatchAlgorithm matchAlgorithm = new MatchAlgorithm(codeMap, tokens, 5);
matchAlgorithm.findMatches();
Iterator<Match> matches = matchAlgorithm.matches();
Match match = matches.next();
assertFalse(matches.hasNext());
Iterator<Mark> marks = match.iterator();
Mark mark1 = marks.next();
Mark mark2 = marks.next();
assertFalse(marks.hasNext());
assertEquals(3, mark1.getBeginLine());
assertEquals("Foo.java", mark1.getFilename());
assertEquals(LINE_3, mark1.getSourceCodeSlice());
assertEquals(4, mark2.getBeginLine());
assertEquals("Foo.java", mark2.getFilename());
assertEquals(LINE_4, mark2.getSourceCodeSlice());
}
@Test
void testIgnore() throws IOException {
JavaTokenizer tokenizer = new JavaTokenizer();
tokenizer.setIgnoreLiterals(true);
tokenizer.setIgnoreIdentifiers(true);
SourceCode sourceCode = new SourceCode(new SourceCode.StringCodeLoader(getSampleCode(), "Foo.java"));
Tokens tokens = new Tokens();
TokenEntry.clearImages();
tokenizer.tokenize(sourceCode, tokens);
Map<String, SourceCode> codeMap = new HashMap<>();
codeMap.put("Foo.java", sourceCode);
MatchAlgorithm matchAlgorithm = new MatchAlgorithm(codeMap, tokens, 5);
matchAlgorithm.findMatches();
Iterator<Match> matches = matchAlgorithm.matches();
Match match = matches.next();
assertFalse(matches.hasNext());
Iterator<Mark> marks = match.iterator();
marks.next();
marks.next();
marks.next();
assertFalse(marks.hasNext());
}
}
| 3,300 | 36.089888 | 109 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/cpd/JavaTokenizerTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
// TODO - enable test
@Disabled("Needs to be enabled after java-grammar changes are finalized")
class JavaTokenizerTest extends CpdTextComparisonTest {
JavaTokenizerTest() {
super(".java");
}
@Override
public Tokenizer newTokenizer(Properties properties) {
JavaTokenizer javaTokenizer = new JavaTokenizer();
javaTokenizer.setProperties(properties);
return javaTokenizer;
}
@Override
protected String getResourcePrefix() {
return "../lang/java/cpd/testdata";
}
@Test
void testCommentsIgnored() {
doTest("simpleClassWithComments");
}
@Test
void testDiscardedElements() {
doTest("discardedElements", "_ignore_annots", ignoreAnnotations());
}
@Test
void testDiscardedElementsExceptAnnots() {
doTest("discardedElements", "_no_ignore_annots");
}
@Test
void testIgnoreBetweenSpecialComments() {
doTest("specialComments");
}
@Test
void testIgnoreBetweenSpecialAnnotation() {
doTest("ignoreSpecialAnnotations");
}
@Test
void testIgnoreBetweenSpecialAnnotationAndIgnoreAnnotations() {
doTest("ignoreSpecialAnnotations", "_ignore_annots", ignoreAnnotations());
}
@Test
void testIgnoreIdentifiersDontAffectConstructors() {
doTest("ignoreIdentsPreservesCtor", "", ignoreIdents());
}
@Test
void testIgnoreIdentifiersHandlesEnums() {
doTest("ignoreIdentsPreservesEnum", "", ignoreIdents());
}
@Test
void testIgnoreIdentifiersWithClassKeyword() {
doTest("ignoreIdentsPreservesClassLiteral", "", ignoreIdents());
}
@Test
void testIgnoreLiterals() {
doTest("ignoreLiterals", "", ignoreLiterals());
}
@Test
void testNoIgnoreLiterals() {
doTest("ignoreLiterals", "_noignore");
}
@Test
void testTabWidth() {
doTest("tabWidth");
}
private static Properties ignoreAnnotations() {
return properties(true, false, false);
}
private static Properties ignoreIdents() {
return properties(false, false, true);
}
private static Properties ignoreLiterals() {
return properties(false, true, false);
}
@Override
public Properties defaultProperties() {
return properties(false, false, false);
}
private static Properties properties(boolean ignoreAnnotations,
boolean ignoreLiterals,
boolean ignoreIdents) {
Properties properties = new Properties();
properties.setProperty(Tokenizer.IGNORE_ANNOTATIONS, Boolean.toString(ignoreAnnotations));
properties.setProperty(Tokenizer.IGNORE_IDENTIFIERS, Boolean.toString(ignoreIdents));
properties.setProperty(Tokenizer.IGNORE_LITERALS, Boolean.toString(ignoreLiterals));
return properties;
}
}
| 3,221 | 24.776 | 98 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/Thread.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
/**
* Shadows java.lang.Thread
*
*/
public class Thread {
}
| 182 | 13.076923 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/NestedClasses.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
public class NestedClasses {
void foo() {
class InMethod {
class IInMethod {
}
}
}
public class Inner {
public Inner() {
}
public <T> Inner(T t) {
}
class IInner {
}
}
}
| 403 | 11.242424 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/SomeClassA.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
public class SomeClassA {
}
| 148 | 13.9 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/Enums.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
public class Enums {
public enum Empty {}
public enum SomeConstants {A, B}
}
| 208 | 12.933333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/BrokenGeneric.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
import net.sourceforge.pmd.lang.java.symbols.internal.asm.Classpath;
/**
* For this test we exclude SuperItf.class from the {@link Classpath}
* to mimic an incomplete classpath.
*
* @see net.sourceforge.pmd.lang.java.symbols.internal.asm.BrokenClasspathTest
*/
public class BrokenGeneric<T0, T1>
extends SuperKlass<T0, T0>
implements SuperItf<T1, T1> {
}
class SuperKlass<A, B> { }
interface SuperItf<A, B> { }
| 546 | 22.782609 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/TestCase1.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
public class TestCase1 {
String foo;
SomeClassA a;
}
| 185 | 10.625 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/Statics.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
public class Statics extends StaticsSuper {
public static final int PUBLIC_FIELD = 0;
public final int publicField = 0;
protected static final int PROTECTED_FIELD = 0;
static final int PACKAGE_FIELD = 0;
private static final int PRIVATE_FIELD = 0;
public void publicInstanceMethod() {
}
private static void privateMethod() {
}
protected static void protectedMethod() {
}
static void packageMethod() {
}
public static void publicMethod() {
}
public static void publicMethod(int i) {
}
public static void publicMethod2() {
}
static class PackageStatic {
}
public static class PublicStatic {
}
protected static class ProtectedStatic {
}
private static class PrivateStatic {
}
public static class PublicShadowed {
}
public static class SomeClassA {
}
class PackageInner {
}
public class PublicInner {
}
}
| 1,100 | 12.107143 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/StaticNameCollision.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
public class StaticNameCollision {
public static final int Ola = 0;
public static int Ola() {
return 0;
}
public static String publicMethod() {
return "";
}
public static String publicMethod(int other) {
return "";
}
public static class Ola {
}
}
| 435 | 13.533333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/javasymbols/testdata/StaticsSuper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package javasymbols.testdata;
public class StaticsSuper {
public static void oha() {
}
public static int oha;
public static class oha {}
}
| 249 | 12.888889 | 79 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.