Search code examples
pythonpython-2.7yamlrobotframeworkpyyaml

How to write a yaml in python for multiple test cases?


I am learning Robot framework using python. I am looking for ways to pass data to two different test cases. In java, this was easy. I made a class for yaml and gave the data for two separate test cases in the yaml file. How can I have such an architecture in Python? When I try to give the data in yaml file, I am getting duplicate key error. Can someone tell me what I am doing wrong, and also suggest ways to give data to multiple test cases using single yaml? Java_yaml Python_yaml


Solution

  • Are you sure you are getting a duplicate key error? Because with the input you present you'll get a mapping values are not allowed here error:

    import sys
    import ruamel.yaml
    
    yaml_str = """\
    Get_Request
      alias : 'amway1'
      session_url : 'url2'
    
    Post_Request
        alias : 'amway2'
        session_url : 'url2'
    """
    
    yaml = ruamel.yaml.YAML()
    try:
        data = yaml.load(yaml_str)
    except Exception as e:
        print(e)
    

    which gives:

    mapping values are not allowed here
      in "<unicode string>", line 2, column 9:
          alias : 'amway1'
                ^ (line: 2)
    

    This is because you try to use a multi-line plain scalar as the key at the start of that YAML, and those are not allowed (they have to be simple, not multi-line). You probably forgot to insert a colon (:) after the Get_Request and Post_Request.

    Get_Request:
      alias : 'amway1'
      session_url : 'url2'
    
    Post_Request:
      alias : 'amway2'
      session_url : 'url2'
    

    (You should also consistently indent your YAML, with the same amount of spaces before the keys, now you have 2 and 4 positions. That is not necessary to make valid YAML, and the parser will accept it, but it is to properly see the structure when humans inspect your input).