How to check if a file was created by a test?

Say I have an executable that creates a file. What’s the best way to write a test to verify the existence of the file.

# Assume the file is created in the same directory as the executable
add_test(NAME create_json_file COMMAND json_creator --name "foobar.json")

Currently the best idea I have is to write a 2nd test, that depends on the prior test.
I used the builtin cat command since it fails when the file doesn’t exist.

add_test(NAME check_json_exists
    COMMAND ${CMAKE_COMMAND} -E cat $<TARGET_FILE_DIR:json_creator>/foobar.json
)
set_tests_properties(check_json_exists PROPERTIES DEPENDS create_json_file)

Is there a more idiomatic way? I think this is pretty clean, but I’m curious.

I would create a wrapper script that executes your program and then exits with a failure code if the file does not exist. Then register that wrapper script as the actual test.

The wrapper script could easily be written in cmake itself.

You also want to remove the file at the start of the test so that previously passing runs don’t mask new failures.

1 Like