Blossom Logo Deploy your apps with Heroku-like simplicity using Blossom See Your Savings
BoltOps Logo
Quick AWS Lambda Testing If Main Script Trick: Ruby, Python, Node, Bash header image

Quick AWS Lambda Testing If Main Script Trick: Ruby, Python, Node, Bash

Tung Nguyen Tung Nguyen · September 17, 2018
3 min read

A quick way to test a Lambda function, is to add a little portion of code at the bottom of the script that tells it to run itself when it is the main script. The if statement means that the script will only run if it is ran directly vs being required as a library.

hi.rb:

if __FILE__ == $0
  puts "this script was ran directly"
end

So this will run the if statement:

$ ruby hi.rb # run directly
this script was ran directly
$

And this will not run the if statement:

myfile.rb:

require_relative "hi" # being required, so not ran directly
$ ruby myfile.rb # will not run script since `hi.rb` is being required
$

Always forget the way to do it between languages, so writing it down for posterity.

Here are different ways to check if the script is being ran directly in: Ruby, Python, Node and Bash.

Code Examples

Ruby

def handle(event:, context:)
  p event
end

if __FILE__ == $0
  event = {hi: "world"}
  handle(event: event, context: {})
end

Output:

{:hi=>"world"}

Python

def lambda_handler(event, context):
  print(event)

if __name__ == "__main__":
  event = {'hi': 'world'}
  lambda_handler(event, {})

Output:

$ python hi.py
{'hi': 'world'}

Node

const handler = function (event, context, callback) {
  console.log(event);
};

if (require.main === module) {
  var event = { hi: "world" };
  var context = { fake: "context" };
  exports.handler(event, context);
}

Output:

$ node hi.js
{ hi: 'world' }

Bash

function handler () {
  EVENT_DATA=$1
  echo "$EVENT_DATA" 1>&2;
  RESPONSE="Echoing request: '$EVENT_DATA'"

  echo $RESPONSE
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  handler '{"test": 1}'
  # handler "$@"
fi

Output:

$ node hi.js
{ hi: 'world' }
Blossom Logo
Deploy Your Apps with Ease

Blossom lets you deploy to your own servers with Heroku-like simplicity. Connect any cloud provider and we'll handle the rest. Save time and money with Blossom.

BoltOps Blog
Join a group of good-looking folks who get free email updates from BoltOps.