Skip to content

SnakeYAML LoaderOptions.setAllowDuplicateKeys(false) should fail on duplicate keys. #413

@nielsbasjes

Description

@nielsbasjes

When creating a YAMLFactory we can specify the SnakeYAML LoaderOptions.

One of the settings in there is to make the load fail if a duplicate key is found in the parsed yaml.

This feature does not work when using Jackson.

To demonstrate (I'm donating these tests to your project) two ways of parsing the same document

  • the first test (using the SnakeYaml code) passes (i.e. throws a DuplicateKeyException)
  • the second test (using the Jackson code) fails (i.e. does NOT throw a DuplicateKeyException)
String yamlDocument = "key1: a\nkey1: b";

@Test
void loadingDuplicateKeysShouldFailIfNotAllowedSnakeYaml() {
    LoaderOptions yamlLoaderOptions = new LoaderOptions();
    yamlLoaderOptions.setAllowDuplicateKeys(false);

    Yaml yaml = new Yaml(yamlLoaderOptions);
    assertThrows(DuplicateKeyException.class, () -> {
        yaml.load(yamlDocument);
    });
}

@Test
void loadingDuplicateKeysShouldFailIfNotAllowedJackson() throws IOException {
    LoaderOptions yamlLoaderOptions = new LoaderOptions();
    yamlLoaderOptions.setAllowDuplicateKeys(false);

    YAMLFactory yamlFactory = YAMLFactory.builder().loaderOptions(yamlLoaderOptions).build();

    try(YAMLParser yamlParser = yamlFactory.createParser(yamlDocument)) {
        assertThrows(DuplicateKeyException.class, () -> {
            new ObjectMapper().readTree(yamlParser);
        });
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    yamlIssue related to YAML format backend

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions