Monday, April 27, 2009

Ruby CLI Example

This took me awhile to go through and write but this is the main class I am using for my test Harness command line argument parser.

class TestCLI
    # This is the main CLI for the Test Harness, all
    # test options should be listed here
    OPTIONS ={
        :agent  => ['-ag', '--agent'],
        :driver => ['-dri', '--driver'],
        :help   => ['-h', '--help'],
    }
    USAGE =<    This program understands the following options:
      -ag, --agent      : Run agent based tests
      -dri, --driver    : Run driver based tests
      -h, --help        : Displays a message with usage instructions

    With no command line flags, this message is displayed.
END_OF_USAGE
    def parse_opts(args)
        return option_by_args(args[0]) if understand_args?(args)
        # options are not understandable, so display Usage
        puts "Options are not understandable."
        display(USAGE)
    end
    def display(content)
        puts content
    end
    def do_default()
        puts "This is the default section."
    end
    def option_by_args(arg)
        return agent_tests      if OPTIONS[:agent].include?(arg)
        return driver_tests     if OPTIONS[:driver].include?(arg)
        return display(USAGE)   if OPTIONS[:help].include?(arg)
        do_default()
    end
    def understand_args?(args)
        OPTIONS.keys.any? { |key| OPTIONS[key].include?(args[0]) }
    end
    def agent_tests
        agt = system("rutemax -c conf\\agent.rutema all >> logs\\agent_tst.log")
        puts "Ran agent tests.\n#{agt}"
    end
    def driver_tests
        # Probably need something like this
        #   rutemax -c conf\driver.rutema all
        drt = system("rutemax -c conf\\driver.rutema all >> logs\\drv_tst.log")
        puts "Ran driver tests.\n#{drt}"
    end
end

I am running two major test types right now, for the Agent that we produce and the filter driver that is mainly what I test, I utilize Rutema, an open source test execution and management tool to run my scripted tests.  I am using HEREDOC to get the options text out because its multi-line, something I need to convert in another script due to its use of multiple puts lines.  Basically this class parses through each option and then goes to the appropriate function when it finds one it uses, the de_default is a placeholder until I figure out what I want to have there.

All in all I think its pretty good, considering I have only been doing stuff in Ruby for a few months and basically jumped into doing this project to rewrite our Test Harness into something with more reporting and stability.  I'm also not a trained programmer, so if I can do it, so can you.

No comments: