Camel/examples/units.c

112 lines
3.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define YAML_IMPLEMENTATION
#include "../include/cyaml.h"
int main(void) {
int fail_count = 0;
// --- Unit Test 1: Building and Emitting a YAML Document ---
printf("Unit Test 1: Document creation and emission\n");
// Create a new document with a mapping as the root.
YAMLDoc *doc = (YAMLDoc*)malloc(sizeof(YAMLDoc));
if (!doc) {
fprintf(stderr, "Memory allocation failure.\n");
return EXIT_FAILURE;
}
doc->root = yaml_new_map();
if (!doc->root) {
fprintf(stderr, "Failed to create root node.\n");
free(doc);
return EXIT_FAILURE;
}
// Set "name" to a scalar value.
if (yaml_map_set(doc->root, "name", yaml_new_str("Alice")) != 0) {
fprintf(stderr, "Error setting key 'name'.\n");
yaml_doc_destroy(doc);
return EXIT_FAILURE;
}
// Create a sequence for "skills".
YAMLNode *skills = yaml_new_seq();
if (!skills) {
fprintf(stderr, "Failed to create skills sequence.\n");
yaml_doc_destroy(doc);
return EXIT_FAILURE;
}
yaml_seq_append(skills, yaml_new_str("C"));
yaml_seq_append(skills, yaml_new_str("Python"));
if (yaml_map_set(doc->root, "skills", skills) != 0) {
fprintf(stderr, "Error setting key 'skills'.\n");
yaml_doc_destroy(doc);
return EXIT_FAILURE;
}
// Emit the document.
YAMLEmitter *emitter = yaml_emitter_create();
if (!emitter) {
fprintf(stderr, "Failed to create emitter.\n");
yaml_doc_destroy(doc);
return EXIT_FAILURE;
}
if (yaml_emit(emitter, doc) != 0) {
fprintf(stderr, "Error emitting YAML document.\n");
yaml_emitter_destroy(emitter);
yaml_doc_destroy(doc);
return EXIT_FAILURE;
}
char *output = yaml_emit_to_str(emitter);
if (!output) {
fprintf(stderr, "Failed to retrieve emitter string.\n");
yaml_emitter_destroy(emitter);
yaml_doc_destroy(doc);
return EXIT_FAILURE;
}
printf("Emitted YAML:\n%s\n", output);
// Check expected content.
if (strstr(output, "Alice") == NULL ||
strstr(output, "skills") == NULL ||
strstr(output, "- Python") == NULL)
{
printf("Unit Test 1 Failed: Emitted YAML output is missing expected content.\n");
fail_count++;
} else {
printf("Unit Test 1 Passed.\n");
}
free(output);
yaml_emitter_destroy(emitter);
yaml_doc_destroy(doc);
// --- Unit Test 2: Loading a YAML Document from a String ---
printf("\nUnit Test 2: YAML load from string\n");
const char *yaml_input = "Hello YAML!\nThis is a test.";
YAMLDoc *doc2 = yaml_load_str(yaml_input);
if (!doc2) {
fprintf(stderr, "Error loading YAML from string.\n");
return EXIT_FAILURE;
}
const YAMLNode *root2 = yaml_doc_root(doc2);
if (!root2 || strcmp(yaml_as_str(root2), yaml_input) != 0) {
printf("Unit Test 2 Failed: Loaded YAML does not match input string.\n");
fail_count++;
} else {
printf("Unit Test 2 Passed.\n");
}
yaml_doc_destroy(doc2);
// --- Finalize Unit Tests ---
if (fail_count == 0) {
printf("\nAll unit tests passed successfully.\n");
return EXIT_SUCCESS;
} else {
printf("\n%d unit test(s) failed.\n", fail_count);
return EXIT_FAILURE;
}
}