Salesforce TDD (Test-Driven Development)

Disclaimer: The following is written on the basis of what has worked for me in the past. This is not intended to be a formal or exhaustive description. Use it as you see fit, I do not take any responsibility if you screw it up! 🙂

Hi, I’m Diego and I have several years (I prefer not to say how many, but let’s say “enough”) working in Salesforce. I am also an Agile enthusiast and lover of applying related techniques throughout my work.

I’ve found test-driven development (TDD) can be a great technique for building robust software, but when we work in Salesforce, I find some constraints or restrictions can make it frustrating. In this post, I’m going to show when and how I use TDD while coding in Salesforce.

Let’s start at the beginning:

What is TDD?

TDD is an Agile development technique that requires you to write a failing unit test before writing any “production code.”

How are you supposed to do TDD?

First I’ll describe how TDD is done in general (this is the way to go in languages like Java).

  1. Write a unit test and make it fail (a compilation error is considered a failing test). Write no more lines of code than needed.
  2. Write the least possible production code lines to make the test pass (fixing a compilation error is considered a pass test).
  3. Refactor the code.
  4. Repeat until you are done.

Let’s check out an example in Java so you see how it works. In this example, we wanna create an advanced calculator of integers.

We work in split view when doing TDD

ROUND 1

Let’s write a failing unit test:

Oops, MyCalculator is not defined yet, compilation issue…therefore, it is a failing test.

Let’s make the test pass:

Compilation problem fixed! The test is passing again. Woohoo!

No tons of code to refactor. 

ROUND 2

Let’s continue with that test to make it fail again.

Mmm…getOpposite is not defined, ergo compilation issue, ergo failing test.

Let’s fix that. Let’s write the minimum code to fix the test:

getOpposite is defined and returns 0 to any parameter (in particular, 0). Test is passing again!!!

Let’s refactor.

We still don’t have much code to refactor, but there are some name changes we could use to make code easier to read ( yup, yup, yup…unit test code is code, too).

Much better now! 😀

Round 3

Let’s add a new minimum test to fail.

Right now, getOpposite returns 0 to any parameter… it’s a fail!

Let’s write the minimum code required to make the test pass.

Yay! It’s green again! Let’s continue.

Round 4

Let’s add a new failing test.

Last test fail (we are return 0 to any value different than 1), so now we need to write the minimum code to fix this test:

Test is passing again… but this solution is not good, let’s refactor.

Tests are still passing and we solve all the cases! We are done! Well, not actually, we still need to document, test more, write more tests and write even more tests…but we’re on the right path.

I expect this silly example gives you a feel for what TDD is and how it is done.

Now, let’s continue with the discussion, focused on Salesforce.

TDD Advantages

  • Code coverage: We get great code coverage without even thinking about it.
  • Testability: The code is designed to be testable by default (we are actually testing every time we change something).
  • Easier to refactor: We should not change or refactor code without having a set of tests we can lean on. As we are constantly writing tests that we know are able to catch bugs (we make it fail at the beginning), we know that we have a set we can rely on.
  • “Better” code: We are constantly refactoring the code, striving for the best possible code.
  • Predictability: After we finish a “round,” we are completely sure the code is working as we designed it to work and we know we didn’t break anything. We can say we have “working software.”
  • Prevents useless work in Salesforce: In Salesforce, aside from Apex, we have plenty of options to make changes like triggers, workflow rules, process builder, etc. Imagine that after we write a test that changes a value on a contact record, it passes. We could discover that there is another moving part that is taking care of that change (or we wrote the test badly).
  • Documentation: Tests are a great tool to communicate with other developers (or the future you) how, for example, a class API should be called and the expected results of each case.

TDD Disadvantages

  • Overtrust: It happens to me that, as we are testing continuously and we are getting test green, I sometimes have a feeling that the code is working perfectly…but it doesn’t mean it is. We may miss, or simply get lazy, and leave a case out of the unit test.
  • Slow in Salesforce: TDD is designed based on the theory that compiling or writing a test is really fast (a jUnit unit test has to run in less than 1ms). In Salesforce, we need several seconds to compile (the code is compiled on the server) and several more seconds to run the test. In my opinion, this is usually 10+ seconds. As we are compiling and running tests constantly, we add several minutes of “waiting for Salesforce.” However, this can be mitigated if you think you will need to write/compile/execute tests later anyway – you might as well do it upfront.

Me when I realize the QA found a case I had not considered when I was doing TDD

I will (probably) use TDD when…

In general, I’ve found that TDD is a great tool in several circumstances and I tend to do it almost always in the below cases.

  • Back-end bug fixes: Doing TDD in this context has two big advantages. First, you make sure you are able to reproduce the bug consistently. Second, and even more important, as you are writing a test specific to the bug, you know you will never introduce that bug again.
  • Back-end work with clear requirements and a clear implementation strategy: In this context, writing tests is going to be easy and implementing the production code will be easy, too, as you know where you are heading when you create the test cases.
  • Back-end work with clear requirements and minor implementation unknowns: In this context, the test is easy to write and the production code may be getting clearer as you move into cases.
  • Back-end work with some requirements discovery: Imagine in our calculator example you write a test to divide by zero and you realize you’ve never discussed that case with the BA. TDD helps you discover opportunities to clarify requirements.

I might do TDD, but it’s unlikely…

  • As part of requirements discovery: You could write unit tests as part of requirements discovery, and discuss it with your stakeholders, BA, or other technical people, but you probably have better techniques to support this process.
  • Front-end work: I’m gonna discuss this briefly later, when we talk about Lightning web components.

I will never do TDD when…

  • I’m doing a prototype: By definition, a prototype or PoC should be discarded after we show it, so I code it as fast as I can, focused on demonstrating the core functionality.
  • I’m experimenting: If I’m trying a new idea, I don’t focus on code quality (again, this is a prototype).
  • I’m evaluating implementation options: There are some cases where you want to compare two implementation options, so focus on having a good-enough-to-decide prototype and throw it away after you decide…then do the stuff well.
  • I don’t care about code quality: I know code quality is not usually negotiable, but in very limited and extreme situations, it may not be the top priority. For example, when everything is screwed up on prod and you need to fix the problem ASAP because the company is losing millions of dollars per minute. In this very extreme circumstance, fix the problem as fast as you can, make your company earn money again, go to sleep (or maybe get a drink) and tomorrow at 10 am (yup, after a stressful night, start working a little later the next day) make the code beautiful with TDD. Make a test that reproduces the bug and then fix and refactor the code properly.

Me again, but on one of THOSE nights.

  • When creating test code is extremely difficult (but not possible): In Salesforce there are a few elements that are very hard to test, like working with CMT. In this scenario, I’d probably split the problem into two parts – one that is TDD-doable using mocking data (@TestVisible is your best friend here) and a second, smaller part that I’d consider how to test later (if I even consider it).

How I do TDD in Salesforce

I really don’t do TDD as I defined at the beginning of this article when I’m working in Salesforce. Why? Mainly because of the slower compile/test flow, but also because in Apex we generally start writing integration tests instead of unit tests. Instead of “regular” TDD, I tweaked the formula a bit to work better under Salesforce circumstances.

  1. Write an entire deployable test that checks the flow or use case. Yup, I said deployable, so if I called a method I haven’t created yet, I will create it, empty, so I can deploy.
  2. Run it and get a failure.
  3. Write the minimum code that makes that test pass.
  4. Refactor.
  5. Continue with the next flow or use case.
  6. When I’m done with all the flows and use cases, I refactor the code again (splitting methods, checking code cleanliness, documentation). I run the unit test continuously, every few changes to check if everything continues to work as expected.

To make everything clear, let’s view an <could-be-real-world> example.

Requirement:
As a user, I want the values stored in any object copied into a number of specified contact fields. The specified “mappings” will be stored in a CustomMetadataType called Contact_Mappings__cmt. The Contact_Mappings_cmt has two fields:

  • Original_Fields__c Text
  • Mapped_Fields__c Text

Round 1
As I said before, I should start writing an Apex test that tests a business case. The first thing I’m thinking of developing is “The contact should not change if there is no mapping defined.” I have to write a deployable test that is going to fail with the minimum amount of code to make it fail:

We work in split view

As expected, the code deploys but the test fails. So, we need to fix it! We can simply return the same object.

Now It passes, but we don’t have a lot of code to refactor (we could extract some constants in the test).

This is a much better test.

Test still passes!

Round 2

Okay, let’s add another case. What if we check that the User.LastName is copied into the contact when I define the Mapping Lastname => Lastname? Great idea, let’s do it!

I start to write the unit test but…. I realize I can’t do an Insert in a CMT. Or, I give seeAllData permission to the test and define it in the project metadata. Or, I have to somehow deploy it. 

Remember that I said that I don’t do TDD when writing the test is extremely hard? Well, it looks like I’m in one of those situations. At this moment, I can quit writing this blog post and go cry…or I can redefine what I am developing with TDD, leaving all the complexities outside of scope. I imagine you would be very annoyed after reading this far to see me just quit, so let’s go with the second option.

I can’t use the CMT right now, so let’s do something different. What if we use a Map<String, String> where the key is the field in the original object and the value is the list of fields names in the Contact Object. It might work, later on we just need to read the CMT and create a Map with that information, but spoiler alert…that won’t be covered in this article.

But okay, great, let’s create a map and write the deployable failing test.

And as it was expected… it fails.

Let’s write the “minimum” code that makes that test pass

Our new test passes, but the other one failed! Let’s fix that.

Let’s do some refactoring, either in test or production code.

I think the put/get part is messy to read (and has its own meaning), so let’s split it into its own method.

Also, as we want that theMap could be injected into test case scenarios, the @TestVisible annotation is useful here.

Round 3

Now we should add a new test that executes a new flow and see it fail. I think you got the idea, so I won’t do it now, but just to specify the cases, I can think:

  • Mapping a field to multiple fields (separated by colon)
  • Does nothing if origin field is wrong
  • Does nothing if destination field is wrong
  • Does nothing if types are not compatible
    …and so on

Can we do TDD in Lightning web components (or front-end)?

The short answer is yes, we can. 
Long answer: As the Jest test can’t see the objects, but they see only the “generated DOM”, it may be harder to do TDD in an efficient way for front-end solutions. Usually, it is better to test visual code by watching the result and THEN write the tests we need to ensure code won’t break in the future.

Conclusion

TDD is a best practice that’s good to master so that you can decide the best moment to apply it (I don’t believe there is One Ring to rule them all, One Ring to find them, One Ring to bring them all, and in the darkness bind them, thank you J.R.R. Tolkien). Applied correctly it will make you produce better, more robust code…and fewer bugs, which means…

Homer is happy

Why you should attend Dreamforce 2021

Dreamforce starts next week, in just 5 days. If you’re new to Salesforce, you may not know about Dreamforce, the annual event that brings together the global Salesforce community for learning, fun, community building, and philanthropy. It’s an experience where Trailblazers from all over the world gather to share their stories, their successes, and learn from each other.

Why Attend Dreamforce

Salesforce is taking a hybrid approach this year, both on-site and online. Dreamforce 2021 takes place September 21-23, 2021, and will host select attendees in San Francisco, while the rest of the world will join virtually. 

Dreamforce will broadcast globally, for free on Salesforce+. There will be four live broadcast channels and 100+ hours of on-demand content. Salesforce is known across the industry for its excellent events. We highly recommend attending if you are working with Salesforce or would like to start learning more about it. There are four key reasons why you want to be a part of Dreamforce 2021. 

  • Learn. Transform your career with breakout sessions, training, and certification opportunities. Participate in cutting-edge demos. Meet new partners with solutions to help your organization grow.
  • Get inspired. The world’s most innovative minds come to Dreamforce to inspire, excite, and motivate attendees every year.
  • Give back. Attendees help build diversity, inclusion, equality, and sustainability with action and volunteerism. Past organizations Salesforce has supported include Girl Scouts of America, RED, and many more.
  • Have fun. When Trailblazers get together, it’s a party. And Dreamforce is the biggest one of all. Dreamforce is a celebration of the community.

Recommendations to attend Dreamforce 

Are you ready for three full days of non-stop events? There are many sessions and topics, that’s why we have some recommendations for you:

Plan your time: One of the biggest challenges with a virtual Dreamforce will be that everyone is spread across different time zones. Dreamforce has everything you need, from session descriptions to calendar links. Don’t forget to add the sessions to your calendar and keep track of what’s coming. Take a look at the schedule and the episodes, so you can choose the sessions that make the most sense for your interests and responsibilities. During the three-day marathon, we recommend blocking off time to catch up on tasks and stay productive. 

To make your life easier, here are some sessions we recommend. Remember that if you cannot attend some sessions, they will be available later in Salesforce+.

Day 1: Tuesday, September 21 

  • Dreamforce Main Show: Trailblazing Together with Marc Benioff and Special Guests (12:45 p.m. ET)
  • Integrate Everything, Automate Anything with MuleSoft (1:00 p.m. ET)
  • Innovation from Anywhere with Salesforce Developers (6:30 p.m. ET)
  • Create User Experiences with Lightning Web Components (7:30 p.m. ET)
  • Develop Enterprise Applications with Apex (8:00 p.m. ET)

Day 2: Wednesday, September 22

  • A Special Conversation with Co-Founder & CTO Parker Harris (12:00 p.m. ET)
  • Build the Future of Business with Salesforce Architects (3:30 p.m. ET)
  • Architecting at Scale (4:30 p.m. ET) 
  • Unlocking Insights with Tableau (5:30 p.m. ET)

Day 3: Thursday, September 23  

  • Your Roadmap for Connected, Effortless Service (12:00 p.m. ET)
  • MuleSoft: Create Integrated Customer 360 Experiences (12:30 p.m. ET)
  • Fast and Easy Integration with MuleSoft Composer (1:00 p.m. ET)
  • The IT Leader’s Guide to the Salesforce Platform Roadmap (2:00 p.m. ET)
  • Empower IT to Ship Faster with Functions and DevOps Center (2:30 p.m. ET)

Test your equipment. Make sure you have all the equipment ready and prepared for a perfect virtual experience. Test your internet speed, and have a backup source just in case. Also, prepare your laptop and phone chargers as well as grabbing additional cables in advance. You don’t want to have your devices run out of power in the middle of a great session. 

Prepare your space: We’ve all been juggling working from home for months, so we know how easy it is to become distracted. The best approach is to find a space in your home that will let you focus on the event with minimal interruptions. Close that email, for example. We know it’s tempting to multitask; avoid it if at all possible. Give yourself the time to focus on learning and engaging as much as you can. And some of those sessions may be early; make sure you have your favorite brew ready!

Whether it is your first time attending Dreamforce, second time, or more, we are sure you will have a great experience! 

Calling Apex methods in Salesforce Lightning web components

[Originally published as ¿Cómo Llamar Apex en Lightning Web Component?]

One of the features that Salesforce gives us is the ability to call Apex methods in Lightning web components. This can be done by importing the method and calling it with the decorator wire service or imperatively.

How to import an Apex method in a Lightning web component?

We can import methods from Apex classes into a component using the import form in ES6 (ECMAScript v6). This way:

  • apexMethodName: Symbol to identify the Apex method.
  • apexMethodReference: Name of the Apex method that we are going to import.
  • Classname: Name of the Apex class in Salesforce.
  • Namespace: If the Apex class is in the same namespace as the component, do not specify a Namespace. If the class is in a managed package, specify the namespace of the managed package.

How to expose an Apex method in Lightning web components?

To expose a method of an Apex class in a component, the method must be static and global or public. Also, we need to add the @AuraEnabled annotation to it.

In the following example, we expose a method called getContactList in the component, which returns a list of contacts.

How to call an Apex method with React Wire?

To read data from Salesforce, the Lightning web component can use the Reactive Wire service. The wire decorator is used to call an Apex method.

In the following example, we call an Apex method using the wire decorator.

How to call an Apex method imperatively?

In the next example, we call an Apex method, which returns a list of contacts, imperatively. The imported function returns a promise.

If you are looking for Salesforce technical content in Spanish written by experts, we recommend visiting Snake on Code, where you will find more information regarding Lightning web components, Apex, and more. 

If you enjoyed this article, here are some more that you might enjoy:

Why Become a Certified MuleSoft Developer

Interested in obtaining your first MuleSoft certification, but still have some questions about it? Ana, a developer in our Ecuador office has some answers:

What is the advantage of learning MuleSoft?

The most important advantage that MuleSoft has against other platforms is that it allows you to easily develop and manage APIs. You can even drag and drop components and integrate systems. With MuleSoft Anypoint™ Exchange you can add your APIs to a marketplace to reach a broader audience. That same marketplace gives you connectors that can make your life easier. For example, MuleSoft gives you the ability to use a Facebook or a Salesforce package, so you can integrate systems more easily.

Do you have to be a programmer?

Knowing how to code, or at least understanding how to do it, is useful because it helps you better understand certain topics in the MuleSoft training. For example, DataWeave, or try-catch blocks for error handling, and other concepts like that are things you will need to know to be successful.

Do I have to know a specific programming language to learn MuleSoft?

You don’t need to know any specific programming language. But you just have to know how to code, that should be all you need.

How does MuleSoft help companies to grow?

When a company needs to integrate systems, MuleSoft gives them an advantage. With pre-built connectors, MuleSoft makes it easier to connect those systems without having to write a large amount of custom code. Also, if a company wants to produce its own APIs and possibly sell them, the MuleSoft Anypoint Platform makes that easier. They can even use MuleSoft Anypoint API Community Manager to create a Salesforce Experience Cloud community for API developers, which can help quickly grow adoption for the APIs.

Are there any prerequisites to have before someone takes the MuleSoft certification? 

It’s important to understand programming and know a bit about APIs, like what they are, how they’re used, and why you’d use them.  MuleSoft certification is not very difficult as long as you know your basics. 

It is possible to achieve the certification by myself?

Of course, it’s possible. And it’s a great opportunity since the course is free. To start, go to the training page and sign up. If you pass the training, then the exam is free.  You should take advantage of this opportunity! Just remember, you need some experience with coding to know the terms and to understand DataWeave. It shouldn’t be too challenging for you.

What is the best API?

Which API is best depends on the project you’re working on. So maybe, if you want to incorporate a map in your system, consuming the Google Maps API would be the best solution for you (if it complies with all the requirements you need to meet).

What is the next step after you earn the MuleSoft developer certification Level I – Mule 4?

After you achieve your certification, your next step could be to go for the  Integration Architect certification. In my case, I want to gain more experience with MuleSoft projects before I become a certified Integration Architect. For that certification, MuleSoft has training that can help you, but it is not free. 

How long does it take to get MuleSoft certified?

That’s a great question, but it really depends on you. You could finish this course in five days if you are 100% committed, but you can also use other kinds of resources. Just to be sure you are ready before you take the exam. So it could take, five days, one week, two weeks, it all depends on you and the time and effort you put into it.

Here are some great resources that helped me: 

In which kind of projects can I use MuleSoft?

You will use MuleSoft only for projects that require integrating systems. For example, if in your project you integrate a database and then you want to use that data in another system, you can use a specific API for that. But it really depends on the project and your requirements.

As a front-end developer, do you think it is useful? or is it only used in the back-end?

I think that as a front-end or a back-end developer it could be very useful to have a full understanding of what MuleSoft can do. So it’s worth getting this certification to give yourself a better understanding. As I said, this is a huge opportunity and the exam is free,  so you must take it!

If you want to know more, watch the webinar about MuleSoft certification and Ana’s experience.

Interested in learning more? Check out some of our latest MuleSoft articles:

Salesforce Direct Message API: the new way to communicate

APIs (application programming interfaces) make our professional life, as developers, much simpler. This feeling is more remarkable when it comes to IT messaging apps. As we built Tok to boost Chatter’s capabilities, we can say APIs were always good allies. Today, we will share how the Salesforce Direct message API is helping us improve communication for our customers.

APIs: What are they for? 

Firstly, we want you to picture this: developers are normally running huge projects and need to create brilliant solutions in a short period of time. Therefore, we need to build bridges between different systems that, often, have never been related. In these situations, we need to be strategic and creative to meet our customer’s expectations and enhance the user experience. 

This is when APIs become our best friends. They are able to make two or more systems interact with one another. Oxford defines an API as: 

“A set of functions and procedures allowing the creation of applications that access the features or data of an operating system, application, or other services.”

This might sound difficult but the fact is, APIs are everywhere. Every time you use your phone, check your social media apps, share data within your company, or chat with your teammates, there are APIs working behind the scenes. 

Direct Message API, a whole new messaging experience in Salesforce

Chatter, the Salesforce enterprise collaboration tool, is no exception. Since Chatter is part of Salesforce, there are several Message APIs that make it possible to integrate this product with other solutions. 

For those who are not familiar with Chatter, we are talking about the product Salesforce built to provide a collaborative communication platform. All Salesforce employees, partners, and most customers interact, collaborate, and share information from within Salesforce using Chatter. Everything is available to your teammates and securely archived.

At Oktana we are obsessed with Chatter and that’s why we created Tok, our messaging app to boost Chatter capabilities. Tok is 100% integrated with Salesforce and enables real-time conversations in your company. You can maintain your company culture in a secure way, archiving everything in Salesforce to meet compliance requirements.

As Salesforce has improved Chatter, we’ve been able to refactor Tok several times to take advantage of the new APIs. Previously, we used the Private Message API. However, we started testing the new Direct Message API, and let us tell you, the experience is becoming way more flexible and enjoyable.

New improvements for the next Tok version

First, let us talk about Tok Channels. With the Direct Message API, you will be free to add or remove members whenever you need to. In other words, this is surely a better way to manage real-time communication across projects and assignments. If you are a user and you finish your arrangements on a Channel, you can now leave it and focus on your next project. 

What about big, long-term projects? They usually require big teams working together. Direct Message API allows us to host up to 16 members in every channel. In addition, Salesforce created the Direct message API to take care of private conversations:

“Imagine a scenario where a customer brings up an issue they have with a product in the community feed. A support agent can share that post and address the customer’s concerns privately in a direct message. Similarly, a channel manager can discuss sensitive sales data with one or more partner users in a partner community.” 


Our team of developers is always working to take advantage of most of the Message APIs available within Salesforce. What is more, we are currently working to support 100% of the Direct Message API. We are committed to real-time communication and this drives us to constantly incorporate new resources. We want to provide you with a solution that increases productivity and develops your company culture. So, stay tuned because we are close to releasing an updated version of Tok with these functionalities. If you haven’t tried Tok, stop overthinking and download it now in this link

Tok 30 day trial
Salesforce Direct Message API

Python and Salesforce

Today’s post is about, you guessed it, using Python and Salesforce together. Salesforce offers a few different REST API endpoints that allow us to interact with our org. They also offer a SOAP API, but we’re not going to use it today. In fact, we don’t need to worry about the endpoints at all. Thanks to a Python library called Simple-Salesforce.

 

We could do this all by hand with the built-in requests library. You would have to handle sessions, OAuth process and save tokens, deal with request headers, encoding and decoding JSON, creating configs to handle all the different endpoints, etc…

 

Simple-Salesforce Python Library

 

 

This is where the wonderful world of open source software comes to the rescue. A man named Nick Catalano created a library called simple-salesforce. From what I understand, he isn’t actively developing it anymore, but due to open source, the community has picked up adding features. It has about 50 contributors as of July 8, 2020. The lib is being actively developed, with new features added like bulk API support and formatted SOQL queries!

 

 

With a bit of the background out of the way, let’s start digging into the library and see what we can do with it. First, no better way to explain what simple-salesforce is than to quote the README itself:

 

Simple Salesforce is a basic Salesforce.com REST API client built for Python 3.3, 3.4, 3.5, and 3.6. The goal is to provide a very low-level interface to the REST Resource and APEX API, returning a dictionary of the API JSON response.

Simple Salesforce

 

In plain text this quote means Python 3.x is supported, REST requests are handled for us, and the data we want comes back as a native Python data type. Great! Just what we want.

 

Login Information

 

First up, we’ll need a few things from Salesforce. Three things to be exact. Our username (email), password, and security token. The username and password should be pretty easy to find in your profile settings in your Salesforce org, but where do we find the security token? We don’t really see it, rather we’ll need to reset it.

 

 

 

 

 

 

 

 

 

After clicking “Reset Security Token” , you should be sent an email containing your new token. Save this, we’ll need it in the next steps. That’s all we need from Salesforce to get up and running. Now that we have that, let’s start building our Python script and start playing with our org.

 

pip and pipenv

 

 

But first, a quick word about PIP. While working on this example, there was an update to simple-salesforce lib. Github has the current version and we need the format_soql method from it. But pip (PyPi) hasn’t been updated with the new version as of yet, July 2 2020. So, we’ll need to install it via it’s repo on Github.

 

pipenv install -e git+https://github.com/simple-salesforce/
simple-salesforce.git#egg=simple-salesforce

If you are using the demo repo I built, we won’t need to worry about the requirements or dependencies if using pipenv. The demo has a Pipfile that’s pulling from the repo already thanks to the magic of pipenv.

The code

Now, let’s write some code. First up, we’ll bring in the libs we’re going to use. The only one that is not part of the standard lib is simple-salesforce:

from simple_salesforce import Salesforce, format_soql
from pprint import pprint
import json

Simple enough, import simple-salesforce, pprint (pretty print), and json. pprint is only used to make the terminal output look better, so it’s not needed for the core examples. json is used to get the credentials from a .json file, which is what we’ll do next.

# open file holding our login information
# we have the login info in a separate file so we can
# add it to .gitignore to help prevent leaking the information
# environment variables could also work
with open("login.json", "r") as login_file:
    creds = json.load(login_file)

Keep credentials secret

If you were on a project working in a private repo and multiple people needed access to the login credentials, keeping login info in the script itself would be okay, not ideal but okay. The reason we’re doing it is because it’s good practice and it’s open to the public on Github. So hiding and not committing sensitive information is important. This goes for any language or code base.

With that disclaimer out of the way, I included an example login.json file called very creatively “EXAMPLE_login.json“. Let’s take a quick look at it.

{
    "login": {
        "username": "sfdemo@kbcarte.com",
        "password": "My-REALLY-amazing-password",
        "token": "kdjfghdgfFGJbDFgd36DFGHDfgh"
    }
}

Very simple json object only containing the three things we got from the last steps. You can just copy/paste the “EXAMPLE_login.json” and rename it to just “login.json“, then update it with your login information. You can do this in the file explorer or VSCode, but here’s a quick example to do it from the command line.

cp EXAMPLE_login.json login.json
vim login.json

Salesforce Object

With our new login information, we can create the salesforce object back in our python script.

sf = Salesforce(username=creds['login']['username'],
                password=creds['login']['password'],
                security_token=creds['login']['token'])

And that’s it! We now have an object that represents our org, and now we can start doing cool things like SOQL or DML. Next, since we have everything we need to start awesomeness, let’s try a simple SOQL query.

SOQL Query

# an example of running a simple SOQL query
SOQL = "SELECT Id, Email FROM Contact"
data = sf.query(SOQL)
for d in data['records']:
    pprint(f"{d['Id']} -- {d['Email']}")

We defined the query string to get the Id and Email from all the Contacts, called the query() method of our salesforce object, then looped through the returned records and display the results. A note to those new to Python, in the pprint() we use something called an f-string or format string. It makes it easier to embed variables in strings, much like the way Aura Components handle expressions with {!v.my_var}

SOQL is cool and all, but what about adding new data to our org? We can do that too, very easily. We’ll even try using the bulk api to insert 1,000 record. But first we need to create 1,000 records. This is going to be mock or fake data just for the sake of simplicity. We’ll also be testing on the Account object, so only thing required for new records is the Name field.

data = []
for i in range(0,1000):
    data.append({
        "Name": f"Bulk Test {i}"
    })

Now we have a list of dictionaries that represent our record data. Here we have a for loop filling a list with new items. We could also use list comprehension to replace these 5 lines of code with just one.

data = [{'Name': f"Bulk Test {i}"} for i in range(0, 1000)]

Bulk Insert

To bring these new records into Salesforce, we use the .insert() method for the object we want, coming from the salesforce object we created. Confused yet? Here’s the insert code, it should help make things more clear.

# insert the new account using the bulk api
x = sf.bulk.Account.insert(data, batch_size=10000, use_serial=True)
pprint(x)

Here, we’re telling our org we want to use the bulk api “sf.bulk“, then which record object we’re working with “.Account.“, and finally what we want to actually do “.insert()“. We could use any object too, doesn’t have to be just Account. Even custom objects work, so instead of where Account is, we can replace it with something like sf.bulk.MyCustomObj__c.insert(..... We can also specify the batch size, or to process in serial.

Bulk SOQL

If you visit your org and take a look at all Accounts, you should see 1,000 new accounts with names like “Bulk Test 42”. We can also try doing another SOQL query, this time we’ll use the bulk api for the query. We’ll also show how to use things such as “LIKE” in SOQL statements.

# now lets get those records so we can delete them
SOQL = format_soql("SELECT Id, Name FROM Account WHERE Name LIKE '{:like}%'", "Bulk Test")
the_accounts = sf.bulk.Account.query(SOQL)
pprint(the_accounts)

Simple-salesforce now comes with the handy little method called format_soql that allows us to do things such as LIKE. format_soql is also the reason we used the Github repo for pip instead of what’s on PyPi, the new method was just introduced in the last 2 weeks.

Now that we know we can insert and add new data and records to salesforce, let’s see about removing it. Looking at the README, seems like the delete() method needs a list of records containing the Id of the record to be deleted. The records need to be a key-value pairs or dictionary just like how the query was returned. We already have all the Id’s for our inserted record from the “bulk.query()

{'Id': '0013h00000EdP87AAF',
  'Name': 'Bulk Test 998',
  'attributes': {'type': 'Account',
                 'url': '/services/data/v42.0/sobjects/Account/0013h00000EdP87AAF'}}]

Looks like simple-salesforce also returns something called “attributes“. This just tells use which object we’re working with and which api endpoint we got the information from. For our example, and for the .delete() method, we only need the Ids. So let’s clean up and make a new list with only what we want.

account_ids = []
for a in the_accounts:
    account_ids.append({"Id": a["Id"]})
pprint(account_ids)

Here is another opportunity to practice list comprehension! See if you can get that for loop down to one line.

Bulk Delete

So now we have the list of Id’s, now we just simply call the delete() method and go refresh our org’s Account list.

data = sf.bulk.Account.delete(account_ids, batch_size=10000, use_serial=True)
pprint(data)

All the records we inserted are now gone!

Final Thoughts

In conclusion, let’s recap what we’ve learned. For one, Python is awesome. Second, integrating Salesforce in a Python project is very very simple. With only three pieces of information, we can create a native Python object representing our Salesforce org, do things with the object like SOQL and DML, and finally have access to multiple salesforce API such as bulk or search.

This is only scratching the surface. We can do much more and simple-salesforce also has methods for metadata and describe. From this basic example, we could bring in Salesforce data to Flask API’s we build or insert new data to Salesforce from a data scraping crawler we make in Python.

We can also harness the power of Python’s ecosystem of visualization and reporting such as Pandas or SciPy. Nothing stopping us from grabbing Salesforce data and running it through machine learning or neural networks using PyTorch or TensorFlow.

If you’ve made it this far, thanks for reading! Here I’ll link the demo repo containing all the code discussed in this post and a YouTube video of my presentation. Also, if you are interested in learning more about Python, you can check this article: How to do Time Series Analysis with Python & Pandas.

https://www.youtube.com/watch?v=rf1jx3jbL2M&feature=youtu.be

Heading to Dreamforce 2019

Members of our team have attended Dreamforce for years. We’re excited to host a booth once again at Dreamforce 2019.

This year, stop by the Trailhead Zone where the team will be ready to chat on Oktana and also answer technical questions about Salesforce integrations or building on the Heroku and Lightning platforms. 

MEET

You will have the opportunity to meet developers from our Montevideo, Uruguay and Asuncion, Paraguay offices:

  • Gaston Esmela
  • Giselle Ramirez
  • Iris Galeano
  • Jorge Sosa
  • Mathias Moller

When: Tuesday – Friday, 7.30 am – EOD

Where: Head to the back of the Trailhead Zone. We will be on the right in front of the Coastline Theater.

LEARN

We’ll also host a talk with Royal Caribbean International to share how, for luxury brand Celebrity Cruises, the team went from a manual collection of event leads to a custom app that enables them to make the most of events like Dreamforce. We’ll go over the business case, a quick demo and success metrics. 

Session: How Will Sales Manage All Those Dreamforce Leads? Case Study: Royal Caribbean
When: Thursday, November 21 at 11.15 am

Where: Trailhead Zone, Moscone West | Coastline Theater

Resourcing with Oktana

When you outsource development, nearshore or onshore, you probably wonder about resources and whether they’re going to work well with your internal team. At Oktana, we consider our team to be your development team. We take pride in working to get the right help for each project, whether it’s a designer, developer or a whole team. Many of our clients even choose to continue with the same team on multiple projects.

Let’s take a look at how resourcing works at Oktana.

Step 1. Gather data

First, we need a clear picture of your company and project. Your account manager will work with you to understand skill requirements, project scope and anything else you feel is essential. For example:

  • Will we work alongside your internal team? 
  • Will we need to integrate with existing systems? 
  • Are there preferred development platforms, frameworks or languages? 
  • Is business analysis, design or test automation part of the scope? 

We work with you to define “done” for the project. We are an Agile company, so this often means defining a minimum viable product, or MVP. These conversations help us determine a reasonable start and end date for the project.

Step 2. Select resources

Now that we have an idea of your needs, our resourcing team will build your development team. We want to ensure your team brings the skills to meet all of the technical requirements for your project. We also want to ensure they’re a good fit in terms of personality and experience.

Everyone should feel confident in their ability to work together.

Step 3. Review resources

As our resourcing team builds your development team, you have a few options depending on how involved you want to be in the process. You can let us handle the entire process, or you can be far more hands-on. 

If you want to be more hands-on, we’ll work with you to review a set of developer profiles. You can also conduct developer interviews to meet each team member before you sign-off on your development team.

What’s a developer profile?

Our resourcing team compiles a developer profile for each of our developers, which provides you with a good overview of their skillset, certifications and experience.

Step 4. Meet your development team

Our teams receive English tutoring and overlap with most of the US workday. Because of this, you are always able to chat or run planning sessions, review specs and do demos face-to-face by video. This is your development team. 

As your project grows, or requirements shift, your account manager will work with you and our resourcing team to adjust the team to meet those needs.

We hope all of this information helps you understand the resourcing process better and by extension how our teams work. Our team has worked with different organizations and their projects. We are Salesforce platform experts and offer custom development to help you build your platform and solve the right problems. If you want to know more about our work, go check out our latest success stories.

Take a Look at Tok

Are you a Salesforce user looking for a way to securely and efficiently stay in contact with everyone within your organization? Then it might be time to take a look at Tok. Tok is Oktana’s flagship Salesforce app designed to help keep everyone at your organization in close contact at all times. If your team’s been begging you to adopt Slack or another tool, but you’re concerned about security and safety, then Tok is what you need.

Built on Salesforce Chatter, Tok allows for instant messaging, team messaging, and groups to connect all within Salesforce. That way, you know your conversations are safe, secure, and archived within your Salesforce instance. Your team never has to leave Salesforce to talk and collaborate. To highlight how Tok can help your organization, we’re producing a series of videos to demonstrate Tok.

First, let’s take a look at some of the basic features of Tok. In this video, we walk through all the different chat options available to you in Tok and how they’re different from each other.

Next, notifications are essential to making sure everyone within your team stays on the same page. You need to know when new messages arrive so they can act on them immediately. That’s why we’re walking through how notifications work in Tok, so you know the team will always be ready.

And that’s it for the first in our series walking through all you can do with Tok. If you’re interested in learning more feel free to contact us here or you can get a 30 day free trial of Tok right now on the AppExchange.

Tok 30 day trial