testc_helpers.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /** @file testc_helpers.c
  2. * @brief Testc helper functions
  3. *
  4. * This file implements helpers for writing tests for 'testc' utility.
  5. */
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <assert.h>
  9. #include <stdio.h>
  10. #include <stdarg.h>
  11. #include <errno.h>
  12. #include "faux/ctype.h"
  13. #include "faux/str.h"
  14. #include "faux/file.h"
  15. #include "faux/testc_helpers.h"
  16. ssize_t faux_testc_file_deploy(const char *fn, const char *str) {
  17. faux_file_t *f = NULL;
  18. ssize_t bytes_written = 0;
  19. assert(fn);
  20. assert(str);
  21. if (!fn || !str)
  22. return -1;
  23. f = faux_file_open(fn, O_WRONLY | O_CREAT | O_TRUNC, 00644);
  24. if (!f)
  25. return -1;
  26. bytes_written = faux_file_write_block(f, str, strlen(str));
  27. faux_file_close(f);
  28. if (bytes_written < 0)
  29. return -1;
  30. return bytes_written;
  31. }
  32. char *faux_testc_tmpfile_deploy(const char *str) {
  33. char *template = NULL;
  34. int fd = -1;
  35. faux_file_t *f = NULL;
  36. ssize_t bytes_written = 0;
  37. char *env_tmpdir = NULL;
  38. assert(str);
  39. if (!str)
  40. return NULL;
  41. env_tmpdir = getenv(FAUX_TESTC_TMPDIR_ENV);
  42. if (env_tmpdir)
  43. template = faux_str_sprintf("%s/tmpfile-XXXXXX", env_tmpdir);
  44. else
  45. template = faux_str_sprintf("/tmp/testc-tmpfile-XXXXXX");
  46. assert(template);
  47. if (!template)
  48. return NULL;
  49. fd = mkstemp(template);
  50. if (fd < 0)
  51. return NULL;
  52. f = faux_file_fdopen(fd);
  53. if (!f)
  54. return NULL;
  55. bytes_written = faux_file_write_block(f, str, strlen(str));
  56. faux_file_close(f);
  57. if (bytes_written < 0)
  58. return NULL;
  59. return template;
  60. }