0

I am writing a Groovy test to check a method's yaml output and I am having trouble comparing the expected yaml with the generated yaml. The expected yaml string is missing double quotes for values that require double quotes. I am using snakeYaml as my yaml parser.

Generated yaml output:

key_a: 3
key_b: "value_b"
key_c:
  key_c1: "value_c1"
  key_c2: "value_c2"
  key_c3: "value_c3"

Expected yaml output:

key_a: 3
key_b: value_b
key_c:
  key_c1: value_c1
  key_c2: value_c2
  key_c3: value_c3

In this case the generated yaml is correct but my test is failing as the expected yaml does not contain the required quotations.

Creating yaml string using yaml.dump:

def expected = yaml.dump(yaml.load("""
key_a: 3
key_b: "value_b"
key_c:
  key_c1: "value_c1"
  key_c2: "value_c2"
  key_c3: "value_c3"
"""))

How do I create the expected yaml string with the quotations?? Any suggestions on this will help. Thanks!!

1 Answers1

0

Your test should load the YAML and compare the values. This will work regardless of quotation.

SnakeYAML does allow you to control the quoting style, but it is not trivial – I don't know Groovy well enough to evaluate whether this can be translated to Groovy.

Generally though, YAML is not a format where you have complete control over representation. Therefore, you should never check for a specific representation (an implementation may change the way it represents things when updating), but instead load the YAML again and check the values.

Alternatively, in your test, load and dump your expected YAML before comparing so that it is in the same format as the generated YAML.

flyx
  • 35,506
  • 7
  • 89
  • 126
  • There is a simpler way to doublequote values: https://www.javadoc.io/doc/org.yaml/snakeyaml/1.19/org/yaml/snakeyaml/DumperOptions.html#getDefaultScalarStyle-- but in general I agree that better to compare parsed values... – daggett Oct 11 '22 at 11:27
  • [flyx](https://stackoverflow.com/users/347964/flyx) I have the Quoted String and Representer in play from the link you posted. Yet, the string comparison does not work. I will try comparing loaded values as you said. Thank you! – adityaViswanatham Oct 11 '22 at 18:09