void
test_client_install (TestSuite *suite)
{
    bool local;

    gTestUri = bson_strdup_printf("mongodb://%s/", MONGOC_TEST_HOST);
    gTestUriWithBadPassword = bson_strdup_printf("mongodb://*****:*****@%s/test", MONGOC_TEST_HOST);

    local = !getenv ("MONGOC_DISABLE_MOCK_SERVER");

    if (!local) {
        TestSuite_Add (suite, "/Client/wire_version", test_wire_version);
        TestSuite_Add (suite, "/Client/read_prefs", test_mongoc_client_read_prefs);
    }
    if (getenv ("MONGOC_CHECK_IPV6")) {
        /* try to validate ipv6 too */
        TestSuite_Add (suite, "/Client/ipv6", test_mongoc_client_ipv6);
    }
    TestSuite_Add (suite, "/Client/authenticate", test_mongoc_client_authenticate);
    TestSuite_Add (suite, "/Client/authenticate_failure", test_mongoc_client_authenticate_failure);
    TestSuite_Add (suite, "/Client/command", test_mongoc_client_command);
    TestSuite_Add (suite, "/Client/command_secondary", test_mongoc_client_command_secondary);
    TestSuite_Add (suite, "/Client/preselect", test_mongoc_client_preselect);
    TestSuite_Add (suite, "/Client/exhaust_cursor", test_exhaust_cursor);
    TestSuite_Add (suite, "/Client/server_status", test_server_status);

    atexit (cleanup_globals);
}
static void
multi_download_setup (perf_test_t *test)
{
   multi_download_test_t *download_test;
   multi_download_thread_context_t *ctx;
   mongoc_uri_t *uri;
   int i;

   _setup_load_gridfs_files ();
   perf_test_setup (test);

   download_test = (multi_download_test_t *) test;
   uri = mongoc_uri_new (NULL);
   download_test->pool = mongoc_client_pool_new (uri);

   download_test->cnt = 50; /* DANGER!: assumes test corpus won't change */
   download_test->contexts = (multi_download_thread_context_t *) bson_malloc0 (
      download_test->cnt * sizeof (multi_download_thread_context_t));

   for (i = 0; i < download_test->cnt; i++) {
      ctx = &download_test->contexts[i];
      ctx->filename = bson_strdup_printf ("file%d.txt", i);
      ctx->path = bson_strdup_printf ("%s/%s", test->data_path, ctx->filename);
   }

   mongoc_uri_destroy (uri);
}
int
main (int   argc,   /* IN */
      char *argv[]) /* IN */
{
   char *cwd;
   char buf[1024];

   if (argc <= 1 || !!strcmp (argv[1], "-v")) {
      mongoc_log_set_handler (log_handler, NULL);
   }

   mongoc_init ();

   cwd = getcwd(buf, sizeof(buf));
   assert(cwd);

   gTestCAFile = bson_strdup_printf("%s/" CAFILE, cwd);
   gTestPEMFileLocalhost = bson_strdup_printf("%s/" PEMFILE_LOCALHOST, cwd);

   run_test("/ReplicaSet/ssl/client", &test_replica_set_ssl_client);

   bson_free(gTestCAFile);
   bson_free(gTestPEMFileLocalhost);

   mongoc_cleanup();

   return 0;
}
static void
multi_upload_setup (perf_test_t *test)
{
   multi_upload_test_t *upload_test;
   multi_upload_thread_context_t *ctx;
   mongoc_uri_t *uri;
   char *data_dir;
   DIR *dirp;
   struct dirent *dp;
   int i;

   perf_test_setup (test);

   upload_test = (multi_upload_test_t *) test;

   uri = mongoc_uri_new (NULL);
   upload_test->pool = mongoc_client_pool_new (uri);

   data_dir = bson_strdup_printf ("%s/%s", g_test_dir, test->data_path);
   dirp = opendir(data_dir);
   if (!dirp) {
      perror ("opening data path");
      abort ();
   }

   i = 0;

   while ((dp = readdir(dirp)) != NULL) {
      if (!strcmp (get_ext (dp->d_name), "txt")) {
         ++i;
      }
   }

   upload_test->cnt = i;
   upload_test->contexts = (multi_upload_thread_context_t *) bson_malloc0 (
      i * sizeof (multi_upload_thread_context_t));

   rewinddir (dirp);
   i = 0;

   while ((dp = readdir (dirp)) != NULL) {
      if (!strcmp (get_ext (dp->d_name), "txt")) {
         ctx = &upload_test->contexts[i];
         ctx->filename = bson_strdup (dp->d_name);
         ctx->path = bson_strdup_printf (
            "%s/%s/%s", g_test_dir, test->data_path, dp->d_name);

         ++i;
      }
   }

   assert (i == upload_test->cnt);

   closedir (dirp);
   bson_free (data_dir);
   mongoc_uri_destroy (uri);
}
Example #5
0
static void
test_query_flags (void)
{
   int i;
   char *opts;
   char *find_cmd;
   test_collection_find_with_opts_t test_data = { 0 };

   typedef struct
   {
      mongoc_query_flags_t  flag;
      const char           *json_fragment;
   } flag_and_name_t;

   /* slaveok is not supported as an option, exhaust is tested separately */
   flag_and_name_t flags_and_frags[] = {
      {
         MONGOC_QUERY_TAILABLE_CURSOR,
         "'tailable': true"
      },
      {
         MONGOC_QUERY_OPLOG_REPLAY,
         "'oplogReplay': true"
      },
      {
         MONGOC_QUERY_NO_CURSOR_TIMEOUT,
         "'noCursorTimeout': true"
      },
      {
         MONGOC_QUERY_PARTIAL,
         "'allowPartialResults': true"
      },
      {
         MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA,
         "'tailable': true, 'awaitData': true"
      },
   };

   for (i = 0; i < (sizeof flags_and_frags) / (sizeof (flag_and_name_t)); i++) {
      opts = bson_strdup_printf ("{%s}", flags_and_frags[i].json_fragment);
      find_cmd = bson_strdup_printf (
         "{'find': 'collection', 'filter': {}, %s}",
         flags_and_frags[i].json_fragment);

      test_data.opts = opts;
      test_data.expected_flags = flags_and_frags[i].flag;
      test_data.expected_find_command = find_cmd;

      _test_collection_find_with_opts (&test_data);

      bson_free (find_cmd);
      bson_free (opts);
   }
}
static char *
gen_test_user (void)
{
    return bson_strdup_printf ("testuser_%u_%u",
                               (unsigned)time(NULL),
                               (unsigned)gettestpid());
}
/*
 * free (*s) and make *s point to *s concated with suffix.
 * If *s is NULL it's treated like it's an empty string.
 * If suffix is NULL, nothing happens.
 */
static void
_append_and_truncate (char       **s,
                      const char  *suffix,
                      int          max_len)
{
   char *old_str = *s;
   char *prefix;
   const int delim_len = strlen (" / ");
   int space_for_suffix;

   BSON_ASSERT (s);

   prefix = old_str ? old_str : "";

   if (!suffix) {
      return;
   }

   space_for_suffix = max_len - strlen (prefix) - delim_len;
   BSON_ASSERT (space_for_suffix >= 0);

   *s = bson_strdup_printf ("%s / %.*s", prefix, space_for_suffix, suffix);
   BSON_ASSERT (strlen (*s) <= max_len);

   bson_free (old_str);
}
Example #8
0
bool
_mongoc_host_list_from_string (mongoc_host_list_t *host_list,
                               const char         *host_and_port)
{
   bool rval = false;
   char *uri_str = NULL;
   mongoc_uri_t *uri = NULL;
   const mongoc_host_list_t *uri_hl;

   BSON_ASSERT (host_list);
   BSON_ASSERT (host_and_port);

   uri_str = bson_strdup_printf("mongodb://%s/", host_and_port);
   if (! uri_str) goto CLEANUP;

   uri = mongoc_uri_new(uri_str);
   if (! uri) goto CLEANUP;

   uri_hl = mongoc_uri_get_hosts(uri);
   if (uri_hl->next) goto CLEANUP;

   memcpy(host_list, uri_hl, sizeof(*uri_hl));

   rval = true;

CLEANUP:

   bson_free(uri_str);
   if (uri) mongoc_uri_destroy(uri);

   return rval;
}
static char *
gen_good_uri (const char *username)
{
    return bson_strdup_printf("mongodb://%s:testpass@%s/test",
                              username,
                              MONGOC_TEST_HOST);
}
/*
 * free (*s) and make *s point to *s concated with suffix.
 * If *s is NULL it's treated like it's an empty string.
 * If suffix is NULL, nothing happens.
 */
static void
_append_and_truncate (char **s, const char *suffix, int max_len)
{
   char *old_str = *s;
   char *prefix;
   const int delim_len = (int) strlen (" / ");
   int space_for_suffix;

   BSON_ASSERT (s);

   prefix = old_str ? old_str : "";

   if (!suffix) {
      return;
   }

   space_for_suffix = max_len - (int) strlen (prefix) - delim_len;

   if (space_for_suffix <= 0) {
      /* the old string already takes the whole allotted space */
      return;
   }

   *s = bson_strdup_printf ("%s / %.*s", prefix, space_for_suffix, suffix);
   BSON_ASSERT (strlen (*s) <= max_len);

   bson_free (old_str);
}
void
test_write_command_install (TestSuite *suite)
{
   gTestUri = bson_strdup_printf("mongodb://%s/", MONGOC_TEST_HOST);

   TestSuite_Add (suite, "/WriteCommand/split_insert", test_split_insert);

   atexit (cleanup_globals);
}
char *
gen_collection_name (const char *str)
{
   return bson_strdup_printf ("%s_%u_%u",
                              str,
                              (unsigned)time(NULL),
                              (unsigned)gettestpid());

}
Example #13
0
void
test_bulk_install (TestSuite *suite)
{
   gTestUri = bson_strdup_printf("mongodb://%s/", MONGOC_TEST_HOST);

   TestSuite_Add (suite, "/BulkOperation/basic", test_bulk);
   TestSuite_Add (suite, "/BulkOperation/update_upserted", test_update_upserted);
   TestSuite_Add (suite, "/BulkOperation/index_offset", test_index_offset);

   atexit (cleanup_globals);
}
void
_mongoc_handshake_append_sasl_supported_mechs (const mongoc_uri_t *uri,
                                               bson_t *cmd)
{
   const char *username;
   char *db_user;
   username = mongoc_uri_get_username (uri);
   db_user =
      bson_strdup_printf ("%s.%s", mongoc_uri_get_auth_source (uri), username);
   bson_append_utf8 (cmd, "saslSupportedMechs", 18, db_user, -1);
   bson_free (db_user);
}
Example #15
0
static void
ha_config_add_shard (ha_node_t        *node,
                     ha_replica_set_t *replica_set)
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_string_t *shardstr;
   bson_error_t error;
   bson_bool_t r;
   bson_t reply;
   bson_t cmd = BSON_INITIALIZER;
   char *uristr;

   uristr = bson_strdup_printf ("mongodb://127.0.0.1:%hu/", node->port);
   client = mongoc_client_new (uristr);
   collection = mongoc_client_get_collection (client, "admin", "fake");

   shardstr = bson_string_new (NULL);
   bson_string_append_printf (shardstr, "%s/127.0.0.1:%hu",
                              replica_set->name,
                              replica_set->nodes->port);

   bson_append_utf8 (&cmd, "addShard", -1, shardstr->str, shardstr->len);

   bson_string_free (shardstr, TRUE);

again:
   sleep (1);

   r = mongoc_collection_command_simple (collection, &cmd, NULL, &reply, &error);

   if (!r) {
      fprintf (stderr, "%s\n", error.message);
      goto again;
   }

#if 1
   {
      char *str;

      str = bson_as_json (&reply, NULL);
      printf ("%s\n", str);
      bson_free (str);
   }
#endif

   bson_destroy (&reply);
   bson_destroy (&cmd);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
   bson_free (uristr);
}
void
test_client_install (TestSuite *suite)
{
   bool local;

   gTestUri = bson_strdup_printf("mongodb://%s:27017/", MONGOC_TEST_HOST);
   gTestUriWithPassword = bson_strdup_printf("mongodb://*****:*****@%s:27017/test", MONGOC_TEST_HOST);
   gTestUriWithBadPassword = bson_strdup_printf("mongodb://*****:*****@%s:27017/test", MONGOC_TEST_HOST);

   local = !getenv ("MONGOC_DISABLE_MOCK_SERVER");

   if (!local) {
      TestSuite_Add (suite, "/Client/wire_version", test_wire_version);
      TestSuite_Add (suite, "/Client/read_prefs", test_mongoc_client_read_prefs);
   }
   TestSuite_Add (suite, "/Client/authenticate", test_mongoc_client_authenticate);
   TestSuite_Add (suite, "/Client/authenticate_failure", test_mongoc_client_authenticate_failure);
   TestSuite_Add (suite, "/Client/command", test_mongoc_client_command);
   TestSuite_Add (suite, "/Client/exhaust_cursor", test_exhaust_cursor);

   atexit (cleanup_globals);
}
static void
test_wire_version (void)
{
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;
    mongoc_client_t *client;
    mock_server_t *server;
    uint16_t port;
    const bson_t *doc;
    bson_error_t error;
    bool r;
    bson_t q = BSON_INITIALIZER;
    char *uristr;

    port = 20000 + (rand () % 1000);

    server = mock_server_new ("127.0.0.1", port, NULL, NULL);
    mock_server_set_wire_version (server, 10, 11);
    mock_server_run_in_thread (server);

    usleep (5000);

    uristr = bson_strdup_printf ("mongodb://127.0.0.1:%hu/", port);
    client = mongoc_client_new (uristr);

    collection = mongoc_client_get_collection (client, "test", "test");

    cursor = mongoc_collection_find (collection,
                                     MONGOC_QUERY_NONE,
                                     0,
                                     1,
                                     0,
                                     &q,
                                     NULL,
                                     NULL);

    r = mongoc_cursor_next (cursor, &doc);
    assert (!r);

    r = mongoc_cursor_error (cursor, &error);
    assert (r);

    assert (error.domain == MONGOC_ERROR_PROTOCOL);
    assert (error.code == MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION);

    mongoc_cursor_destroy (cursor);
    mongoc_collection_destroy (collection);
    mock_server_quit (server, 0);
    mongoc_client_destroy (client);
    bson_free (uristr);
}
/** run as a child thread by test_mongoc_tls_handshake_stall
 *
 * It:
 *    1. spins up
 *    2. waits on a condvar until the server is up
 *    3. connects to the server's port
 *    4. attempts handshake
 *    5. confirms that it times out
 *    6. shuts down
 */
static void *
handshake_stall_client (void *ptr)
{
   ssl_test_data_t *data = (ssl_test_data_t *)ptr;
   char *uri_str;
   mongoc_client_t *client;
   bson_t reply;
   bson_error_t error;
   int64_t connect_timeout_ms = data->handshake_stall_ms - 100;
   int64_t duration_ms;

   int64_t start_time;

   mongoc_mutex_lock (&data->cond_mutex);
   while (!data->server_port) {
      mongoc_cond_wait (&data->cond, &data->cond_mutex);
   }
   mongoc_mutex_unlock (&data->cond_mutex);

   uri_str = bson_strdup_printf (
      "mongodb://localhost:%u/?ssl=true&serverselectiontimeoutms=200&connecttimeoutms=%" PRId64,
      data->server_port, connect_timeout_ms);

   client = mongoc_client_new (uri_str);

   /* we should time out after about 200ms */
   start_time = bson_get_monotonic_time ();
   mongoc_client_get_server_status (client,
                                    NULL,
                                    &reply,
                                    &error);

   /* time is in microseconds */
   duration_ms = (bson_get_monotonic_time () - start_time) / 1000;

   if (llabs(duration_ms - connect_timeout_ms) > 100) {
      fprintf (stderr,
               "expected timeout after about 200ms, not %" PRId64 "\n",
               duration_ms);
      abort ();
   }

   data->client_result->result = SSL_TEST_SUCCESS;

   bson_destroy (&reply);
   mongoc_client_destroy (client);
   bson_free (uri_str);

   return NULL;
}
Example #19
0
/*
 * Connect to MongoDB server using Host/ip and Port number.
 */
MONGO_CONN*
MongoConnect(const char* host, const unsigned short port, char* databaseName, char *user, char *password, char *readPreference, bool ssl, char *pem_file,
	char *pem_pwd, char *ca_file, char *ca_dir, char *crl_file, bool weak_cert_validation)
{
	MONGO_CONN *client = NULL;
	char* uri = NULL;

	if (user && password && readPreference)
		uri = bson_strdup_printf ("mongodb://%s:%s@%s:%hu/%s?readPreference=%s&ssl=%s", user, password, host, port, databaseName, readPreference, ssl ? "true" : "false");
	else if (user && password)
		uri = bson_strdup_printf ("mongodb://%s:%s@%s:%hu/%s?ssl=%s", user, password, host, port, databaseName,  ssl ? "true" : "false");
	else if (readPreference)
		uri = bson_strdup_printf ("mongodb://%s:%hu/%s?readPreference=%s&ssl=%s", host, port, databaseName, readPreference, ssl ? "true" : "false");
	else
		uri = bson_strdup_printf ("mongodb://%s:%hu/%s?ssl=%s", host, port, databaseName, ssl ? "true" : "false");

	client = mongoc_client_new(uri);

	if (ssl) {
		mongoc_ssl_opt_t *ssl_opts = (mongoc_ssl_opt_t*) malloc(sizeof(mongoc_ssl_opt_t));
		ssl_opts->pem_file = pem_file;
		ssl_opts->pem_pwd = pem_pwd;
		ssl_opts->ca_file = ca_file;
		ssl_opts->ca_dir = ca_dir;
		ssl_opts->crl_file = crl_file;
		ssl_opts->weak_cert_validation = weak_cert_validation;
		mongoc_client_set_ssl_opts (client, ssl_opts);
		free(ssl_opts);
	}

	bson_free(uri);

	if (client == NULL)
		ereport(ERROR, (errmsg("could not connect to %s:%d", host, port),
						errhint("Mongo driver connection error")));
	return client;
}
Example #20
0
static int
TestSuite_RunFuncInChild (TestSuite *suite, /* IN */
                          Test *test)       /* IN */
{
   STARTUPINFO si;
   PROCESS_INFORMATION pi;
   char *cmdline;
   DWORD exit_code = -1;

   ZeroMemory (&si, sizeof (si));
   si.cb = sizeof (si);
   ZeroMemory (&pi, sizeof (pi));

   cmdline = bson_strdup_printf ("%s --silent --no-fork -l %s",
                                 suite->prgname, test->name);

   if (!CreateProcess (NULL,
                       cmdline,
                       NULL,    /* Process handle not inheritable  */
                       NULL,    /* Thread handle not inheritable   */
                       FALSE,   /* Set handle inheritance to FALSE */
                       0,       /* No creation flags               */
                       NULL,    /* Use parent's environment block  */
                       NULL,    /* Use parent's starting directory */
                       &si,
                       &pi)) {
      _Print_StdErr ("CreateProcess failed (%d).\n", GetLastError ());
      bson_free (cmdline);

      return -1;
   }

   if (WaitForSingleObject (pi.hProcess, INFINITE) != WAIT_OBJECT_0) {
      _print_getlasterror_win ("Couldn't await process");
      goto done;
   }

   if (!GetExitCodeProcess (pi.hProcess, &exit_code)) {
      _print_getlasterror_win ("Couldn't get exit code");
      goto done;
   }

done:
   CloseHandle (pi.hProcess);
   CloseHandle (pi.hThread);
   bson_free (cmdline);

   return exit_code;
}
Example #21
0
static bson_bool_t
ha_replica_set_get_status (ha_replica_set_t *replica_set,
                           bson_t           *status)
{
   mongoc_database_t *db;
   mongoc_client_t *client;
   mongoc_cursor_t *cursor;
   const bson_t *doc;
   bson_bool_t ret = FALSE;
   ha_node_t *node;
   bson_t cmd;
   char *uristr;

   bson_init(&cmd);
   bson_append_int32(&cmd, "replSetGetStatus", -1, 1);

   for (node = replica_set->nodes; !ret && node; node = node->next) {
      uristr = bson_strdup_printf("mongodb://127.0.0.1:%hu/?slaveOk=true",
                                  node->port);
      client = mongoc_client_new(uristr);
#ifdef MONGOC_ENABLE_SSL
      if (replica_set->ssl_opt) {
         mongoc_client_set_ssl_opts(client, replica_set->ssl_opt);
      }
#endif
      bson_free(uristr);

      db = mongoc_client_get_database(client, "admin");

      if ((cursor = mongoc_database_command(db,
                                            MONGOC_QUERY_SLAVE_OK,
                                            0,
                                            1,
                                            &cmd,
                                            NULL,
                                            NULL))) {
         if (mongoc_cursor_next(cursor, &doc)) {
            bson_copy_to(doc, status);
            ret = TRUE;
         }
         mongoc_cursor_destroy(cursor);
      }

      mongoc_database_destroy(db);
      mongoc_client_destroy(client);
   }

   return ret;
}
Example #22
0
/*
 * Connect to MongoDB server using Host/ip and Port number.
 */
MONGO_CONN*
MongoConnect(const char* host, const unsigned short port, char* databaseName, char *user, char *password, char *readPreference)
{
	MONGO_CONN *client = NULL;
	char* uri = NULL;

	if (user && password && readPreference)
		uri = bson_strdup_printf ("mongodb://%s:%s@%s:%hu/%s?readPreference=%s", user, password, host, port, databaseName, readPreference);
	else if (user && password)
		uri = bson_strdup_printf ("mongodb://%s:%s@%s:%hu/%s", user, password, host, port, databaseName);
	else if (readPreference)
		uri = bson_strdup_printf ("mongodb://%s:%hu/%s?readPreference=%s", host, port, databaseName, readPreference);
	else
		uri = bson_strdup_printf ("mongodb://%s:%hu/%s", host, port, databaseName);

	client = mongoc_client_new(uri);

	bson_free(uri);

	if (client == NULL)
		ereport(ERROR, (errmsg("could not connect to %s:%d", host, port),
						errhint("Mongo driver connection error")));
	return client;
}
Example #23
0
static void
test_index_spec_modifiers (void)
{
   const char *modifiers[] = {
      "hint",
      "min",
      "max",
   };

   const char *mod;
   size_t i;
   char *opts;
   char *query;
   char *find_command;
   test_collection_find_with_opts_t test_data = { 0 };

   for (i = 0; i < sizeof (modifiers) / sizeof (const char *); i++) {
      mod = modifiers[i];
      opts = bson_strdup_printf ("{'%s': {'_id': 1}}", mod);
      /* OP_QUERY modifiers use $-prefix: $hint, $min, $max */
      query = bson_strdup_printf ("{'$query': {}, '$%s': {'_id': 1}}", mod);

      /* find command options have no $-prefix: hint, min, max */
      find_command = bson_strdup_printf (
         "{'find': 'collection', 'filter': {}, '%s': {'_id': 1}}", mod);

      test_data.opts = opts;
      test_data.expected_op_query = query;
      test_data.expected_find_command = find_command;
      _test_collection_find_with_opts (&test_data);

      bson_free (opts);
      bson_free (query);
      bson_free (find_command);
   }
}
Example #24
0
static void
test_int_modifiers (void)
{
   const char *modifiers[] = {
      "maxScan",
      "maxTimeMS",
   };

   const char *mod;
   size_t i;
   char *opts;
   char *query;
   char *find_command;
   test_collection_find_with_opts_t test_data = { 0 };

   for (i = 0; i < sizeof (modifiers) / sizeof (const char *); i++) {
      mod = modifiers[i];
      opts = bson_strdup_printf ("{'%s': {'$numberLong': '9999'}}", mod);
      query = bson_strdup_printf ("{'$query': {},"
                                  " '$%s': {'$numberLong': '9999'}}", mod);

      /* find command has same modifier, without the $-prefix */
      find_command = bson_strdup_printf (
         "{'find': 'collection', 'filter': {},"
         " '%s': {'$numberLong': '9999'}}", mod);

      test_data.opts = opts;
      test_data.expected_op_query = query;
      test_data.expected_find_command = find_command;
      _test_collection_find_with_opts (&test_data);

      bson_free (opts);
      bson_free (query);
      bson_free (find_command);
   }
}
Example #25
0
void
mock_server_replies_to_find (request_t           *request,
                             mongoc_query_flags_t flags,
                             int64_t              cursor_id,
                             int32_t              number_returned,
                             const char          *ns,
                             const char          *reply_json,
                             bool                 is_command)
{
   char *find_reply;
   char db[MONGOC_NAMESPACE_MAX];

   _mongoc_get_db_name (ns, db);

   /* minimal validation, we're not testing query / find cmd here */
   if (request->is_command && !is_command) {
      MONGOC_ERROR ("expected query, got command");
      abort ();
   }

   if (!request->is_command && is_command) {
      MONGOC_ERROR ("expected command, got query");
      abort ();
   }

   if (!request_matches_flags (request, flags)) {
      abort ();
   }

   if (is_command) {
      find_reply = bson_strdup_printf (
         "{'ok': 1,"
            " 'cursor': {"
            "    'id': {'$numberLong': '%" PRId64 "'},"
            "    'ns': '%s',"
            "    'firstBatch': [%s]}}",
         cursor_id,
         ns,
         reply_json);

      mock_server_replies_simple (request, find_reply);
      bson_free (find_reply);
   } else {
      mock_server_replies (request, MONGOC_REPLY_NONE, cursor_id, 0,
                           number_returned, reply_json);

   }
}
void
test_database_install (TestSuite *suite)
{
   gTestUri = bson_strdup_printf ("mongodb://%s/", MONGOC_TEST_HOST);

   TestSuite_Add (suite, "/Database/has_collection", test_has_collection);
   TestSuite_Add (suite, "/Database/command", test_command);
   TestSuite_Add (suite, "/Database/drop", test_drop);
   TestSuite_Add (suite, "/Database/create_collection", test_create_collection);
   TestSuite_Add (suite, "/Database/get_collection_info",
                  test_get_collection_info);
   TestSuite_Add (suite, "/Database/get_collection_names",
                  test_get_collection_names);

   atexit (cleanup_globals);
}
mongoc_uri_t *
mongoc_uri_new_for_host_port (const char *hostname,
                              uint16_t    port)
{
   mongoc_uri_t *uri;
   char *str;

   bson_return_val_if_fail(hostname, NULL);
   bson_return_val_if_fail(port, NULL);

   str = bson_strdup_printf("mongodb://%s:%hu/", hostname, port);
   uri = mongoc_uri_new(str);
   bson_free(str);

   return uri;
}
void
test_gridfs_install (TestSuite *suite)
{
   gTestUri = bson_strdup_printf ("mongodb://%s/", MONGOC_TEST_HOST);

   TestSuite_Add (suite, "/GridFS/create", test_create);
   TestSuite_Add (suite, "/GridFS/create_from_stream", test_create_from_stream);
   TestSuite_Add (suite, "/GridFS/list", test_list);
   TestSuite_Add (suite, "/GridFS/read", test_read);
   TestSuite_Add (suite, "/GridFS/stream", test_stream);
   TestSuite_Add (suite, "/GridFS/remove", test_remove);
   TestSuite_Add (suite, "/GridFS/write", test_write);
   TestSuite_Add (suite, "/GridFS/remove_by_filename", test_remove_by_filename);

   atexit (cleanup_globals);
}
Example #29
0
mongoc_uri_t *
mongoc_uri_new_for_host_port (const char *hostname,
                              uint16_t    port)
{
   mongoc_uri_t *uri;
   char *str;

   BSON_ASSERT (hostname);
   BSON_ASSERT (port);

   str = bson_strdup_printf("mongodb://%s:%hu/", hostname, port);
   uri = mongoc_uri_new(str);
   bson_free(str);

   return uri;
}
int
main (int   argc,
      char *argv[])
{
   mongoc_database_t *database;
   mongoc_cursor_t *cursor;
   mongoc_client_t *client;
   const bson_t *reply;
   bson_uint16_t port;
   bson_error_t error;
   bson_t ping;
   char *host_and_port;
   char *str;

   if (argc < 2 || argc > 3) {
      fprintf(stderr, "usage: %s HOSTNAME [PORT]\n", argv[0]);
      return 1;
   }

   port = (argc == 3) ? atoi(argv[2]) : 27017;
   host_and_port = bson_strdup_printf("mongodb://%s:%hu", argv[1], port);
   client = mongoc_client_new(host_and_port);
   if (!client) {
      fprintf(stderr, "Invalid hostname or port: %s\n", host_and_port);
      return 2;
   }

   bson_init(&ping);
   bson_append_int32(&ping, "ping", 4, 1);
   database = mongoc_client_get_database(client, "test");
   cursor = mongoc_database_command(database, 0, 0, 1, 0, &ping, NULL, NULL);
   if (mongoc_cursor_next(cursor, &reply)) {
      str = bson_as_json(reply, NULL);
      fprintf(stdout, "%s\n", str);
      bson_free(str);
   } else if (mongoc_cursor_error(cursor, &error)) {
      fprintf(stderr, "Ping failure: %s\n", error.message);
      return 3;
   }

   mongoc_cursor_destroy(cursor);
   bson_destroy(&ping);
   mongoc_client_destroy(client);
   bson_free(host_and_port);

   return 0;
}