summaryrefslogtreecommitdiffstats
path: root/test/utils.c
blob: 60665b8ed7a2c8122843c2bcc2c81670aef77911 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// SPDX-License-Identifier: LGPL-2.1-or-later
/*
 * This file is part of libnvme.
 *
 * Common test utilities.
 *
 * Copyright (c) 2022 Code Construct
 */

#include <err.h>
#include <stdlib.h>
#include <unistd.h>

#include "utils.h"

FILE *test_setup_log(void)
{
	FILE *fd;

	fd = tmpfile();
	if (!fd)
		err(EXIT_FAILURE, "can't create temporary file for log buf");

	return fd;
}

void test_close_log(FILE *fd)
{
	fclose(fd);
}

void test_print_log_buf(FILE *logfd)
{
	char buf[4096];
	int rc;

	if (!ftell(logfd))
		return;

	rewind(logfd);

	printf("--- begin test output\n");

	while (!feof(logfd) && !ferror(logfd)) {
		size_t rlen, wlen, wpos;

		rlen = fread(buf, 1, sizeof(buf), logfd);
		if (rlen <= 0)
			break;

		for (wpos = 0; wpos < rlen;) {
			wlen = fwrite(buf + wpos, 1, rlen - wpos, stdout);
			if (wlen == 0)
				break;
			wpos += wlen;
		}

		if (feof(logfd) || ferror((logfd)))
			break;
	}

	printf("--- end test output\n");
	rewind(logfd);
	rc = ftruncate(fileno(logfd), 0);
	if (rc)
		printf("failed to truncate log buf; further output may be invalid\n");
}