Thursday, July 21, 2011

Yaml as config file

One of the best options to specify a config file for java based selenium project is by using a yaml file. In the yaml file the commonly changing config values or values which are used in all tests can be given. There are number of parsers available. I am using snakeyaml.

Jar File

snakeyaml-1.6.jar

Sample yaml file

base: &base                                  # defines anchor label base
  location_username: 'xpath'
  location_password: 'xpath'
  location_submit: 'xpath'
  page: 'http://xxxxxxxxxxx'

test:
  <<: *base                                 #  merges key : value from base anchor
  username: 'testtest'
  password: '123456'
  page: 'http://xxxxxxxxxxx'

prod:
  <<: *base
  username: 'testprod'
  password: '123456'
  page: 'http://xxxxxxxxxxx'

I have saved the above as sample.yaml in my config folder. The use of  "*" and "&" is the inherit the values defined in "base" to "test" and "prod"

Sample java program

import org.yaml.snakeyaml.Yaml;

public class xxx{
 protected Map<String, Map<String,Object>> fullConf;
 protected Map<String,Object> conf;

             Yaml yaml = new Yaml();
             InputStream input = new FileInputStream(new File(System.getProperty("user.dir") + "/config/sample.yaml"));
                this.fullConf = ((Map<String, Map<String,Object>>) yaml.load(input));
                System.out.println("values of fullConf "+fullConf);
                if (fullConf.containsKey("test")) {
                    this.conf = fullConf.get("test");
                    System.out.println("values of test env "+conf);
                    System.out.println("Username "+conf.get("username"));
                    System.out.println("Passowrd "+conf.get("password"));
                    System.out.println("Page "+conf.get("page"));
                    System.out.println("location_username "+fullConf.get("location_username"));
                    System.out.println("location_password "+fullConf.get("location_password"));
                }

}

This program prints the contents of yaml. The variable "fullConf " contains all data of the yaml file as a "key, Map". The variable "conf " will have data of any specific node.


Project home
   src
      test.com
  one/two/three
      config/config.yaml


         InputStream in = this.getClass().getClassLoader().getResourceAsStream("config/config.yaml");
        System.out.println("Hello1 : "+in);

        in = this.getClass().getResourceAsStream("/config/config.yaml");
        System.out.println("Hello3 : "+in);

http://viralpatel.net/blogs/2009/10/loading-java-properties-files.html

No comments:

Post a Comment