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' }