/* MCP client unit tests: pic_mcp_configs closes every /dev/fd handle, even when an earlier
* entry fails. */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "mcp.h"
#include "pic.h"
static int failures;
static void expect(int ok, const char *what) {
if (!ok) {
fprintf(stderr, "FAIL: %s\n", what);
failures++;
}
}
static int make_text_fd(const char *text) {
FILE *f = tmpfile();
size_t n = strlen(text);
int fd = -1;
if (!f) {
return -1;
}
if (fwrite(text, 1, n, f) == n && fflush(f) == 0 && (fd = dup(fileno(f))) >= 0 && lseek(fd, 0, SEEK_SET) != 0) {
close(fd);
fd = -1;
}
(void)fclose(f);
return fd;
}
static int fd_is_closed(int fd) {
errno = 0;
return fcntl(fd, F_GETFD) == -1 && errno == EBADF;
}
int main(void) {
const char *tmp = getenv("TMPDIR");
char dir[512], home[600], fd_path[32], err[PIC_ERR_CAP];
int fd1, fd2, fd3;
const char *vals[2];
(void)snprintf(dir, sizeof dir, "%s/pic-test-mcp.XXXXXX", tmp && *tmp ? tmp : "/tmp");
if (!mkdtemp(dir)) {
perror("mkdtemp");
return 1;
}
(void)snprintf(home, sizeof home, "%s/home", dir);
(void)mkdir(home, 0700);
(void)setenv("HOME", home, 1);
/* Case 1: missing first file must still close a later /dev/fd handle. */
fd1 = make_text_fd("{\"mcpServers\":{}}");
expect(fd1 > 2, "fd1 opened");
(void)snprintf(fd_path, sizeof fd_path, "/dev/fd/%d", fd1);
vals[0] = "/no/such/pic-mcp-config-file.json";
vals[1] = fd_path;
err[0] = '\0';
expect(pic_mcp_configs(vals, 2, 0, err, sizeof err) == -1, "missing first config fails");
expect(fd_is_closed(fd1), "missing first config still closes later /dev/fd");
if (!fd_is_closed(fd1)) {
close(fd1);
}
/* Case 2: invalid JSON in first entry must still close a later /dev/fd handle. */
fd2 = make_text_fd("{\"mcpServers\":{}}");
expect(fd2 > 2, "fd2 opened");
(void)snprintf(fd_path, sizeof fd_path, "/dev/fd/%d", fd2);
vals[0] = "{\"mcpServers\":";
vals[1] = fd_path;
err[0] = '\0';
expect(pic_mcp_configs(vals, 2, 0, err, sizeof err) == -1, "broken JSON first config fails");
expect(fd_is_closed(fd2), "broken JSON first config still closes later /dev/fd");
if (!fd_is_closed(fd2)) {
close(fd2);
}
/* Case 3: valid /dev/fd entry succeeds and closes its descriptor. */
fd3 = make_text_fd("{\"mcpServers\":{}}");
expect(fd3 > 2, "fd3 opened");
(void)snprintf(fd_path, sizeof fd_path, "/dev/fd/%d", fd3);
vals[0] = fd_path;
err[0] = '\0';
expect(pic_mcp_configs(vals, 1, 0, err, sizeof err) == 0, "valid /dev/fd config succeeds");
expect(fd_is_closed(fd3), "valid /dev/fd config closes its descriptor");
if (!fd_is_closed(fd3)) {
close(fd3);
}
(void)rmdir(home);
(void)rmdir(dir);
if (failures == 0) {
puts("PASS: pic_mcp_configs closes /dev/fd handles on both success and error");
}
return failures != 0;
}