It's almost like real tests.

This commit is contained in:
Ian Gulliver
2015-06-14 21:41:43 +00:00
parent 8581ba7672
commit e709514293

View File

@@ -1,3 +1,4 @@
#include <assert.h>
#include <unistd.h>
#include "cosmopolite.h"
@@ -9,8 +10,28 @@
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_RESET "\x1b[0m"
pthread_mutex_t message_lock;
pthread_cond_t message_cond;
const json_t *last_message;
void on_message(const json_t *message, void *passthrough) {
printf("new message: %lld\n", json_integer_value(json_object_get(message, "id")));
assert(!pthread_mutex_lock(&message_lock));
assert(!last_message);
last_message = message;
assert(!pthread_cond_signal(&message_cond));
assert(!pthread_mutex_unlock(&message_lock));
}
const json_t *wait_for_message() {
assert(!pthread_mutex_lock(&message_lock));
if (!last_message) {
assert(!pthread_cond_wait(&message_cond, &message_lock));
}
const json_t *ret = last_message;
last_message = NULL;
assert(!pthread_mutex_unlock(&message_lock));
return ret;
}
cosmo *create_client() {
@@ -32,6 +53,12 @@ json_t *random_subject(const char *readable_only_by, const char *writeable_only_
return cosmo_subject(name, readable_only_by, writeable_only_by);
}
json_t *random_message() {
char uuid[COSMO_UUID_SIZE];
cosmo_uuid(uuid);
return json_string(uuid);
}
void run_test(const char *func_name, bool (*test)(void)) {
fprintf(stderr, ANSI_COLOR_YELLOW "%50s" ANSI_COLOR_RESET ": ", func_name);
if (test()) {
@@ -47,19 +74,32 @@ bool test_create_destroy() {
return true;
}
bool message_round_trip() {
bool test_message_round_trip() {
cosmo *client = create_client();
json_t *subject = random_subject(NULL, NULL);
cosmo_subscribe(client, subject, -1, 0);
json_t *message_out = random_message();
cosmo_send_message(client, subject, message_out);
const json_t *message_in = wait_for_message();
assert(json_equal(message_out, json_object_get(message_in, "message")));
json_decref(subject);
json_decref(message_out);
cosmo_shutdown(client);
return true;
}
int main(int argc, char *argv[]) {
assert(!pthread_mutex_init(&message_lock, NULL));
assert(!pthread_cond_init(&message_cond, NULL));
RUN_TEST(test_create_destroy);
RUN_TEST(message_round_trip);
RUN_TEST(test_message_round_trip);
assert(!pthread_cond_destroy(&message_cond));
assert(!pthread_mutex_destroy(&message_lock));
return 0;
}