fundacionjala / enforce-sonarqube-plugin Goto Github PK
View Code? Open in Web Editor NEWApex static code analyzer.
License: MIT License
Apex static code analyzer.
License: MIT License
The check shows its message
"The method "[methodName]" is marked as a testMethod but it is not in a test class, move it to a proper class or add the "@istest" annotation to the class "[className]".
But for some cases it displays the wrong "className" and in others it incorrectly marks some methods as invalid when they are actually in proper test classes.
It was noticeable that the incorrect className it displays was always the one of the first class analyzed, so it probably has something to do with the lazy loading character of the check's implementation.
Implement the necessary rules to validate Not bulkifying apex methods statements
Scope:
Sample:
sObject sObj = New sObject{};
...
insert sObj;
the suggested way would be:
sObject[] objList = New sObject[]{};
sObject sObj = New sObject{};
objList.addAll(sObj);
insert objList;
Run unit tests from the plugin so code coverage / file is included.
Implement the necessary rules to validate Async (@future) methods statements inside loops
Scope:
Sample:
trigger accountAsyncTrigger on Account (after insert, after update) {
for(Account a: Trigger.new) {
asyncApex.processAccount((String)a.id);
}
}
global class asyncApex {
@future
public static void processAccount(Id accountId) { ... }
}
SFDC issue
"Test methods must have no arguments"
e.g.
error:
public static testMethod void fillInFirstName(List<Contact> contacts) {}
no error:
public static testMethod void fillInFirstName() {}
Implement the necessary rules to validate SOQL statements inside loops
Scope:
Sample:
for(...) {
List availableAccountList = [SELECT ID FROM Account LIMIT 2000];
}
for(...) {
List availableAccountList = Database.query('SELECT ID FROM Account LIMIT 2000');
}
The parser should not crash when it stumbles into a parsing error; instead, it should be able to skip it and keep parsing, and later on log it and report it. For this, a new rule should be created, one that is inserted in the AST anytime the parser can't find a rule syntax that matches any of the existing rules, this way the application will not crash at the moment of creating the AST.
After that, a visitor must be subscribed to this special node and with the information it provides it should log it and report it.
Hola! @k3rv3r05 has created a ZenHub account for the fundacionjala organization. ZenHub is the only project management tool integrated natively in GitHub – created specifically for fast-moving, software-driven teams.
To get set up with ZenHub, all you have to do is download the browser extension and log in with your GitHub account. Once you do, you’ll get access to ZenHub’s complete feature-set immediately.
ZenHub adds a series of enhancements directly inside the GitHub UI:
Still curious? See more ZenHub features or read user reviews. This issue was written by your friendly ZenHub bot, posted by request from @k3rv3r05.
JUnit assertions should not be made from the run method of a Runnable, because failed assertions result in AssertionErrors being thrown. If the error is thrown from a thread other than the one that ran the test, the thread will exit but the test won't fail.
Noncompliant Code Example
public void run() {
// ...
Assert.assertEquals(expected, actual); // Noncompliant
}
static testMethod void myTest {
.... // variable initializations
test.startTest();
.....// test code
test.stopTest();
test.startTest();
.....// test code
test.stopTest();
}
static testMethod void myTest {
.... // variable initializations
test.startTest();
.....// test code
test.stopTest();
}
TestMethods should be declared only in test classes to maintain the code more organized and well-split
Non-compilant code
public with sharing SomeClass {
...
public testMethod void someTestMethod() {...} // this isn't a test class, so it shouldn't have a test method
}
Browsing the rules in the running Sonarqube dashboard, the description of a couple of the checks looks odd
public static void testRunAs() { // missing keyword testMethod
System.runAs(u){
......System.debug(....);
}
}
public static testMethod void myTestRunAs {
System.runAs(u) { //it is possible to have nested more than one runAs method
...
System.debug(....);
...
}
System.runAs(u2){
...
System.debug(....);
...
}
System.runAs(u3){
...
System.debug(....);
...
}
}
Find and implement a way to analyze code even among other classes, apex plugin should generate a symbol table and then it can be used to do so.
Stacktrace error is "Type has not been loaded occurred while retrieving component type of array."
on Console I get below
Parse error at line 23 column 102:
20: ;
21: startDate=strstartDate;
22: endDate=strendDate;
--> objCase = [SELECT id,Subject,Description,Target_Group_HF__c,Type,Sub_Type__c FROM Case WHERE id=caseID];
24: } catch(Exception e) {
25: ErrorLogUtility_HF.processErrorGeneric(null,'', '', 'parseCampaignExcel_HF', 'parseCampaignExcel_HF', e);
26: }
27: }
28:
29:
30:
31:
32:
33:
34:
35:
36: global Iterable
assertions should receive a boolean parameter that may be a boolean expression.
Noncompliant Code Examples
System.assert((4 + 3)/n); // Noncompliant
Compliant Solution
System.assert(cond1 || cond2 || (cond3&cond4));
System.assert(a boolean boo = x/y >= 2;
To define an Apex method as a 'test method', simply define the method as static and add the keyword testMethod. A test method can be defined in any Apex class. A test method can not be defined in an Apex trigger. (Note: Testmethods cannot be called outside of a test context.)
public class myClass {
static void myTest(){} // missing testMethod keyword.
}
public class myClass {
static testMethod void myTest() {
// Add test method logic using System.assert(), System.assertEquals()
// and System.assertNotEquals() here.
}
testMethod void myTest() {
}
}
The following code example:
ChartSettingBars.XAxis = m.APropValue
seems to generate a parsing error, at first it was thought it was an issue of all instances of properties being set, but looking into it more deeply we realized it was caused by the tokenization of the word 'XAxis'; apparently it is mistaken for an Hexadecimal string. For this reason, it will be necessary to review the Lexer and make sure this doesn't happen.
The node visitor isn't able to recognize SOQL statements when they are invoked by Database.query('...') because the content of the query is tokenized as a String before the parser has a chance to relate it to the SOQL_EXPRESSION rule, so the checks related to SOQL won't pop-up.
After some analysis, we figured the best way to solve this issue could be by re-parsing the value of what is recognized as a STRING, and then we could apply the same checks to the new smaller "pseudo-tree" that will be the result of the new parse process.
Check for empty catch statements:
Non complaint:
Try {
// do something
} catch (exception e) {
// do nothing with exception
}
Complaint:
Try {
// do something
} catch (exception e) {
// handle exception
}
Implement the necessary rules to validate SOQL statements
Scope:
Sample:
In addition:
Database.query(string_limit_1);
Hello,
Thank you for this apex plugin. I get this error when i try to analyse my apex project after adding it to sonarqube
Can you help me please ?
Sincerely,
The following error message:
Unable to parse file: [file path and name] ERROR: Parse error at line 48 column 111:
Is displayed when the parser runs into a SOQL statement which uses the format '[.... :somevariable]' (with colon before the variable name)
e.g.:
List<Relationship_Lookup__c> rlList = new List<Relationship_Lookup__c>(); StaticResource sr = [select body from StaticResource where Name = :RECIPROCAL_DEFAULT_RESOURCE_NAME];
Fixing this will require the SOQL part of the grammar to be enhanced to support this format.
Hola! @JimmyRojas has created a ZenHub account for the fundacionjala organization. ZenHub is the only project management tool integrated natively in GitHub – created specifically for fast-moving, software-driven teams.
To get set up with ZenHub, all you have to do is download the browser extension and log in with your GitHub account. Once you do, you’ll get access to ZenHub’s complete feature-set immediately.
ZenHub adds a series of enhancements directly inside the GitHub UI:
Still curious? See more ZenHub features or read user reviews. This issue was written by your friendly ZenHub bot, posted by request from @JimmyRojas.
Hi,
Great projet! I thinks it's not easy to implement apex language.
i get a lot of parse error :(
Is this a working prototype? if yes please provide a simple apex class to parse as an example.
Thanks
Due to apex is based on java, we can analyze its checks whether these can be implemented according our grammar or not.
Implement the necessary rules to validate Hardcoding IDs statements
Scope:
Sample:
for (Account a: Trigger.new) {
if (a.RecordTypeId=='012500000009WAr') {
...
}
}
or
ID recordId = '012500000009WAr';
or
method('0A1GBER123258AG');
Implement the necessary rules to validate SOSL statements inside loops
Scope:
Sample:
for(...) {
List<List> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead];
}
for(...) {
Search.SearchResults searchResults = Search.find('FIND 'map' IN ALL FIELDS RETURNING
Account (Id, Name), Contact, Opportunity, Lead');
}
there should be a bundle from all tech debt will be collected for checks, this will allow to change them by modifying this bundle only.
The @istest class annotation defines classes that only contain code used for testing the application. Only classes can be annotated with @istest and they can be declared either as private or public.
private class MyTest { // missing annotation @istest.
}
@istest
class MyTest { // missing modifier access.
}
@istest
public enum MyTest { //@istest annotation should not be used for enums
}
@istest
public interface MyTest { //@istest annotation should not be used for interfaces
}
@istest
private class MyTest {
...
}
@istest
public class MyTest {
public void testMyTest() {
// some assertion.
}
}
A test method should always have at least one assertion (System.assert, System.assertEquals, etc.) in it
Non Compilant
static testMethod void someTestMethod() {
//a block of code, without System.assert
}
Compilant
static testMethod void someTestMethod() {
...
System.assert(something);
}
...
static testMethod void someTestMethod() {
...
System.assertEquals(something, otherThing, 'message');
}
There are some classes that after been analyzed these classes threw an error because of code inside comment blocks
There would be a sheet to see checks with its respective IDs
The parameters passed to the "System.assert" method in a test method should be a boolean variable that returns a boolean.
Noncompliant Code Examples
System.assert(myList.remove(3)); // Noncompliant
System.assert('some string'); // Noncompliant
AnObject someObject = new AnObject();
System.assert(someObject); // Noncompliant
Compliant Solution
boolean removed = myList.remove(myList.get(0));
System.assert(removed);
Exceptions
The case where the expression passed is a method call, in which's return type can't be known, the rule will be ignored.
System.assert(something.aMethod());
Check for empty if statement:
Non compliant :
If (isChecked) {
// do nothing
} else {
// do something
}
Complaint:
If (!isChecked) {
// do something
}
"System.assert" statement should not be passed literal boolean values (true or false) as parameter
Non Compilant
System.assert(true);
System.assert(FALSE);
Adding messages to JUnit assertions is an investment in your future productivity. Spend a few seconds writing them now, and you'll save a lot of time on the other end when either the tests fail and you need to quickly diagnose the problem, or when you need to maintain the tests and the assertion messages work as a sort of documentation.
Noncompliant Code Example
assertEquals(4, list.size()); // Noncompliant
try {
fail(); // Noncompliant
} catch (Exception e) {
assertThat(list.get(0)).isEqualTo("pear"); // Noncompliant
}
Compliant Solution
assertEquals("There should have been 4 Fruits in the list", 4, list.size());
try {
fail("And exception is expected here");
} catch (Exception e) {
assertThat(list.get(0)).as("check first element").overridingErrorMessage("The first element should be a pear, not a %s", list.get(0)).isEqualTo("pear");
}
When performing a sonar-runner analysis on a project, if any of the files to be analyzed contains any errors that prevent it from being parsed correctly, this shouldn't cause an issue for the rest of the files and the analysis should be completed with the error filed being logged and reported.
@istest(SeeAllData=True) annotation should be avoided, as the test shouldn't rely on other data than it created itself.
The code should be refactored in order to get all of it's output texts, strings, default values or any text that will be displayed for the user retrieved from an external resource bundle file.
[a-zA-Z0-9]{18}|[a-zA-Z0-9]{15} check regular expresion for sfdc ids
shouldn't show any messages for strings
If a class is declared as "@istTest" or contains the word "Test" in it's name, it should have at least one test method
sonar should not throw any error messages for try catch statements
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.