/* * splinter -- gateway bits that can be tested without Telegram. * * The token must come from a file (0600) or the environment, never from an * argument, so both paths are checked here. The network loop is not tested * against api.telegram.org: it is a loop over one HTTP call, and a test that * needs the internet fails for reasons that have nothing to do with the code. */ #include #include #include #include #include #include "splinter.h" static int failures; #define CHECK(cond) do { \ if (!(cond)) { \ fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ failures++; \ } \ } while (0) int main(void) { char dir[512], path[600], buf[256]; const char *tmp = getenv("TMPDIR"); FILE *f; if (tmp == NULL || *tmp == '\0') tmp = "/var/tmp"; snprintf(dir, sizeof(dir), "%s/splinter-tg-XXXXXX", tmp); CHECK(mkdtemp(dir) != NULL); snprintf(path, sizeof(path), "%s/telegram.token", dir); /* no file, no environment: refuse instead of using an empty token */ unsetenv("SPLINTER_TELEGRAM_TOKEN"); CHECK(sp_telegram_token(buf, sizeof(buf), path) != 0); /* the file wins, trailing newline stripped */ f = fopen(path, "w"); CHECK(f != NULL); if (f != NULL) { fputs("123:abc\n", f); fclose(f); } CHECK(sp_telegram_token(buf, sizeof(buf), path) == 0); CHECK(strcmp(buf, "123:abc") == 0); /* environment is the fallback when there is no file */ CHECK(sp_telegram_token(buf, sizeof(buf), "/nonexistent/token") != 0); CHECK(setenv("SPLINTER_TELEGRAM_TOKEN", "456:def", 1) == 0); CHECK(sp_telegram_token(buf, sizeof(buf), "/nonexistent/token") == 0); CHECK(strcmp(buf, "456:def") == 0); /* an empty file is not a token */ f = fopen(path, "w"); CHECK(f != NULL); if (f != NULL) fclose(f); unsetenv("SPLINTER_TELEGRAM_TOKEN"); CHECK(sp_telegram_token(buf, sizeof(buf), path) != 0); { char cmd[600]; snprintf(cmd, sizeof(cmd), "rm -rf '%s'", dir); if (system(cmd) != 0) fprintf(stderr, "cleanup failed\n"); } if (failures == 0) printf("test_telegram: ok\n"); return failures == 0 ? 0 : 1; }