How to identify problems in your code with the Salesforce CLI Scanner

Ok, let see what the Salesforce CLI Scanner is and what it can do for us. The tool is a plugin that uses multiple code analysis engines in various languages (including Apex). It currently inspects your code using the PMD rule engine and ESLint, however, they have plans to add support for more rule engines in the future. 

This means that the tool will help you identify potential problems, from inconsistent naming to security vulnerabilities and alert you to these problems with easy to understand results. You can run the scanner on-command in the CLI, or integrate it into your CI/CD framework to enforce rules and expect high-quality code. And you can run it against every code change.

It’s like having a code review in real-time. Following some rules the Salesforce CLI Scanner can identify issues and show them to the developers as feedback to fix the code, saving a lot of time and money.

This tool can be used by ISVs and Salesforce developers to prepare for security review processes. It can improve code quality by identifying a variety of performance and security issues in the development stage. 

Another possible use is to integrate this tool with a CI/CD process to regularly monitor your code’s health.

Remember that the Salesforce CLI Scanner plugin works on all operating systems that Salesforce CLI supports. It has a one-step installation that is quite easy and fast, and if you are uncertain about the command-line commands, it has a built-in help (–help).

They have recently added new functionality that allows you to scan Salesforce Lightning Web Components using ESlint, and it’s amazing to have that.

These are some of the key features of Scanner v2.3, released in October 2020.

Static analysis

Static analysis, also called static code analysis, is a computer program method for debugging. It is done by examining the code without executing the program. The process provides an understanding of the code structure and can help ensure that the code adheres to best practices and doesn’t fall into common antipatterns and coding issues that will have a negative impact on the performance or quality of the code. Based on rules, the engine reports the suggestions for upgrading your code.

Of course, currently there are a lot of static analysis tools, but most of them work only with one or just a few sets of languages, and the most common in Salesforce packages is the use of a variety of components created in different languages. A single static analyzer is insufficient to take into account all the rules, patterns, best practices, etc. Working with multiple static analyzer tools can quickly become a headache.

To solve this, we recommend the Salesforce CLI Scanner plug-in. This plug-in shows the most relevant information to help Salesforce developers improve to the code while providing a unified experience. 

It has a single and easy installation process with an intuitive set of commands to interact with multiple rule engines. You can define a unified set of rules that are checked by their respective rule engines and also get a report that includes all issues identified by all the engines.

What is PMD?

PMD is a very powerful open-source static analyzer that supports many languages. Additionally, it has a large community of developers building rules for Apex. By default, Salesforce CLI Scanner supports code written in Apex, VisualForce, Java, JavaScript, and TypeScript but you can easily extend it to support any language.

Here at Oktana, we have a set of custom rules to improve our code quality and help everyone to have better-structured code.

What is ESlint?

ESlint is an open-source JavaScript linting utility for identifying and reporting on patterns, with the goal of making code more consistent and avoiding bugs. 

Because it’s very flexible in how it parses JavaScript, it can handle many use-cases related to Lightning Web Components. Additionally, with the built-in Eslint-typescript plugin, the Salesforce CLI Scanner can also analyze TypeScript out-of-the-box.

What does the Salesforce CLI Scanner do for me?

By combining two static scanners in one tool, the Salesforce CLI Scanner allows you to detect a wide variety of problems in your code.

Example Apex issues include:

  • Performance issues (e.g. running SOQL or SOSL queries inside loops).
  • Security issues (e.g. basic sharing violations, simplified CRUD/FLS checks, CSRF, and XSS vulnerabilities)
  • Not clear code (variable names, comments in classes and methods, avoid long, and complicated methods)
  • Error-prone code (e.g. empty try/catch/finally blocks)

Example issues with Lightning Web Components include:

  • Unreachable code
  • Unused variables
  • Invalid regular expressions
  • Stylistic preferences such as enforcing semi-colon at the end of a statement and expecting function names in camelcase

Catching these issues early has several advantages:

  • You can fix code issues immediately and rerun Salesforce CLI Scanner right away to confirm that the issues have been resolved, saving time.
  • Ensure the new developers are following the best practices, best patterns, and avoiding common issues.
  • You can shorten the security review processes. These processes are faster and easier when most issues are identified and fixed before the review even begins.

Different report formats

Salesforce CLI Scanner has an array of useful reporting formats for different uses:

  • Simple table-style reporting to get feedback on code you are actively writing
  • CSV reporting for spreadsheet-based filtering and analytics
  • JSON and XML reporting to feed into other tools for further processing
  • HTML reporting for readable, searchable results
  • JUnit-style test failures to use with a CI/CD setup

Conclusion

Salesforce CLI Scanner is a tool that is here to stay. It has a lot of  Salesforce engineers actively implementing new features to further improve it. 

An upcoming feature is the ability to detect and warn of external code dependencies that may have security vulnerabilities. They are also in the process of adding new rules to identify more security issues.

You can get started with Salesforce CLI Scanner within minutes by following this link to improve your code quality and save time.

What are you waiting for? Go ahead and give this amazing tool a try, and leave your comments about how your experience was!

Learn more from our team here, or check out our services.

Agile Testing Mindset: A change to empower quality

Let’s start at the beginning. When we talk about Agile development, we have an almost inherent perception of producing high-quality software in the shortest time possible. In addition, to maximize the value of the business by delivering part of the solution, which generates value, incrementally, and iteratively. With this idea in mind, we began the design and deployment of a multidisciplinary team in an Agile framework. However, in reality, it can be seen that quality tends not to be the priority in the team since it is often displaced by the pressure of time-to-market that stakeholders, with good reason, exert throughout the workgroup.

This phenomenon, recurrent in most of the projects in which I have been able to participate, obviously leads to a greater problem. On the one hand: We comply with the requirements, we deliver the product on time, we launch the releases; in short, we deliver more and more work. However, on the other hand, the quality of the product and the motivation of the work team are damaged, which generates stress and reluctance in the people involved in the development of the product in the long term.

Agile Testing approach

An alternative approach that attempts to solve this phenomenon is called Agile Testing. It was born as a test practice that follows the principles of agile development. This approach is composed of activities that ensure the generation of quality software throughout the agile framework. By knowing the level of agile maturity of the team -including the company where those involved in the production of the product operate-, these activities are executed based on a list of responsibilities and a framework that synchronizes and directs the “test-driven development”. Promotes early and cross-cutting participation of software testing at all levels of the production process.

What is new about this Agile Testing approach is determined by the involvement of the “Whole Team”. That is, everyone is responsible for quality. Everyone has a responsibility to ensure that they deliver a high-quality product. Everyone has the slogan to contribute to the quality of the software. This approach uses the technical skills of team members to proactively and early check their work at the pace of the project. It seems that by common sense we should carry out these activities; however, sometimes common sense is the least common and more so when there is pressure to deliver the work in the agreed time. I don’t mean to deliver less work, I mean to change your mindset. To stop appointing the quality engineer as solely responsible for the quality of the product. I mean, we all get involved in quality and take advantage of our technical and soft skills to enhance it.

 

A crucial problem that I notice in the implementation of agile practices is the lack of commitment of the workgroup to participate in the activities that are defined, which leads to demotivation for continuing the practices tending to distort them. In my experience, training, and deploying agile teams, I can conclude that we should first develop the agile “being” and then the “doing”. For this reason, the team must internalize the Mindset for the execution of the tasks to be carried out in the project. Agile Testing is a framework that tries to solve this problem by emphasizing the Mindset of people and encouraging them to get involved in the quality of the product developed at each stage of the development process.

Agile Testing Manifesto

There is Agile Testing Manifesto -similar to the Agile Manifesto- which aims to guide the commitment and behavior of the team. It supports defining the correct parameters that the team can follow within an agile framework. This Manifesto prioritizes the “being” that those involved should be clear about to start any project and then execute each iteration. In this regard, Samantha Laing and Karen Greaves (2016), in their Book “Growing Agile”, express the following:

  1. Testing throughout OVER testing at the end”: This would mean changing the paradigm and making early involvement of quality activities. That is, change the Quality Control for Quality Assurance.
  2. “Preventing bugs OVER finding bugs”: This means that we must break the traditional premise of “our mission is to find all defects”. On the contrary, we must really work as a team so that defects can be avoided in advance.
  3. “Testing understanding OVER checking functionality”: That is, understanding the business, what the user wants, why he wants it, and not just comply with the documented specifications.
  4. “Building the best system OVER breaking the system”: It refers to focusing the tests to develop a better system. Collaborate and lend our knowledge to build the best possible software.
  5. “Team responsibility for quality OVER tester responsibility”: I reiterate, the key point to deliver a quality product is to have the entire team committed and work together to generate a better result and make a difference. All engaged in agile activities and practices.

 

Now, within this new framework, there is a new role that will have the mission of collaborating with the team at a functional and technical level. This new role called Agile Tester must have the ability to communicate agile practices. Likewise, it will guarantee that all those involved are concerned about the quality of the process from the role where they are located. The Agile Tester will have a technical mastery and focus on the business. In this regard, Lisa Crispin and Janet Gregory (2009), in their book “Agile Testing: A practical guide for testers and agile teams.” propose 10 principles that the Agile Tester must develop and are the following:

 

1. Provide continuous feedback to the team and the business

2. Keep actions and decisions simple

3. Enable face-to-face communication

4. Practice continuous improvement

5. Focus on people

6. Deliver value to the customer

7. Respond to change

8. Self organize

9. Have courage

10. Enjoy

These principles dominate the development of soft skills. In addition, they have a close relationship with the Mindset of an agile team. Finally, they empower the leadership that is needed to direct, motivate, and guide the activities that diminish over time in a traditional agile situation.

For the implementation of the Agile Testing Manifesto and the principles, we can make use of various dynamics and liberating structures. These try to help people internalize the new paradigms in the entire work team. However, the key to this new framework is having the team’s commitment to do things differently.

If we want different results, let us stop doing the same.”

Albert Eisten

Learn more from our team here, or check out our services.

 

 

Selenium Automation in Salesforce

Lightning and its components have more auto-generated code than other apps, this usually makes the development in Salesforce easier, faster, and more stable! Keep reading and learn more about Selenium Salesforce Automation.

From an automation perspective, this makes things harder and forces us to be more creative when finding locators and interacting with apps. Some things like the ID’s auto-generation and the possibility of multiple attributes with almost the same code makes us rethink the way we locate the WebElement.

In order to select these elements, we need to use all that is in our hands. To do so, we need to understand more about locators.



In general, deciding on which kind of locator is better is like debating whether winter or summer is better. You will have people going for CSS and other people going for Xpath.

The important thing here is understanding when to use each and how to use them in the best way.

CSS:

Most people consider that CSS is better because the operation of finding an element with CSS is faster than Xpath and most of the time it’s easier to read.

Ten years ago the difference in time was a couple milliseconds, but nowadays with the processors we have, it’s just a fraction of a millisecond.

XPATH:

Xpath is the most powerful method. For example, it allows us to go forward and backward in the HTML, lets us search for the text of an element and it’s easier to find a sibling with it.

Unfortunately, there is a bigger learning curve so people tend to fear it.

So, which one should I use to automate Salesforce tests?

It depends on many things. For example:

Is your team already using one of them?
In most cases, the priority is going to be maintainability, so try to keep using what your team has already been using.

Are the elements you are trying to find complex and hard to identify?
In this case, Xpath can be a good choice as we need as much power as we can.

Both of these are things to consider when deciding between CSS and Xpath

How to find a CSS locator:

In browser:
Right click -> Inspect Element ->Console

There are two ways to look for elements, we can use a single $ symbol or use it twice, like $.

When using the single $ symbol, we are looking for the first element that meets the criteria that we specify.
When using the $, we are looking for the list of elements that meet the criteria.

I recommend to always use the $ so we can see the full list of elements that meet these criteria. Be aware that our locator is pointing to multiple elements because this could cause issues in our automation.

Search for element type (button, div, a, span, etc):
$(“elementType”)

Search for attribute (src, title, placeholder)
$(“[attribute=’attributeValue‘]”)


Example: $(“[title='Users']”)

Search for id:
$(“#elementId”)


Example: $(“#username”)

Search for class:
$(“.className1.className2”)

Example: $(“.slds-clearfix.slds-card.detail-panel-root”)
Also: $(“[class=’slds-clearfix slds-card detail-panel-root’]”)

If you want to select a class just for one of the classes you can do something like this:

$(“.detail-panel-root”)

Also you can use the wildcard: $(“[class*=‘detail-panel-root’]”)

Select the child of a specific element:

Status

$("parentElement childElement")
$(".test-id__field-label-container span")

How to find an Xpath locator:

In browser:
Right click -> Inspect Element -> command+f

Search for element type (button, div, a, span, etc):
//elementType

Search for attribute (src, title, placeholder)
//elementType[@attribute=’attributeValue‘]

Example: //span[@title=’Users’]

Search for class:
//elementType[@class=’className‘]

 

Example: //div[@class=’slds-clearfix slds-card detail-panel-root’]

Search for an element with a partial attribute (contains):
//elementType[contains(@attribute,’attributeValue‘)]

 

Example: //div[contains(@title,’123′)]

Search for element’s text:
//elementType[text()=’Text you are looking for‘]

Status

Example: //span[text()=’Status’]

Search for an immediate child:
//elementType[@atribute=’attributeValue‘]/inmediateChildType

 

Example: //div[@id=’test’]/span

Search for a grandchild or any other descendant:
//elementType[@atribute=’attributeValue‘]//descendantType

 

Example: //div[@id=’test’]//a

Search for a sibling:
//elementType[@atribute=’attributeValue‘]/following-sibling::siblingType

Process Name
Test


//span[text()='Process Name']/following-sibling::div/input

Why is it I can find an element in the Developer Tools, but Selenium can’t?

Generally this happens for two reasons:

  1. There are multiple tabs open and Selenium is looking into the wrong one. 

We can fix it executing the following line in our test:

driver.switchTo().window(driver.getWindowHandles().toArray()[{numberOfTabsYouWantToUse}].toString());

I.E: driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());

  1. The element you are looking for is inside an iframe. 

You can verify if it’s in an iframe or not by right clicking on the element you are trying to find and then click in the Console tab. Then you will see if the dropdown is in top ( the default content) or if it’s in an iframe.

If you are in an iframe, you have to switch to it in your test in order to interact with its elements. To do this, you can use the following code:

driver.switchTo().frame({iframeWebelement});

I.E: driver.switchTo().frame(driver.findElement(By.cssSelector(“iframe”)));

Learn more from our team about developing on the Salesforce Platform, or check out our Salesforce custom development services.