mercredi 29 juillet 2020

Connection error in tests when using MongoDB driver in Rust

I am testing a function that should return entries for a given date. For that, I am calling a function that should populate the database with some entries using the official MongoDB driver.

// Setup DB for tests
async fn setup_db() -> Result<String> {
    let client = Client::with_uri_str("mongodb://root:root@mongodb:27017/").await?;
    let db = client.database("logs");
    let time = build_date();
    let coll = db.collection(&time);
    let mut insertion = coll
        .insert_one(
            doc! {"message": "test message 1", "user": "test_user1", "timestamp" : "01-01-20" },
            None,
        )
        .await?;
    insertion = coll
        .insert_one(
            doc! {"message": "test message 2", "user": "test_user2", "timestamp" : "01-01-20" },
            None,
        )
        .await?;
    insertion = coll
        .insert_one(
            doc! {"message": "test message 3", "user": "test_user3", "timestamp" : "01-01-20" },
            None,
        )
        .await?;
    insertion = coll
        .insert_one(
            doc! {"message": "test message 4", "user": "test_user1", "timestamp" : "01-01-20" },
            None,
        )
        .await?;
    return Ok("Ok".to_owned());
}

When I execute the setup function in main, everything works as expected. When it is run as a test:

#[tokio::test]
async fn reading_db_entries() {
    let res = setup_db().await;
    println!("setup complete, Result was: {:#?}", res);
    assert_ne!(check(res), false)
}

I get the following result:

setup complete, Result was: Err(
    Error {
        kind: ServerSelectionError {
            message: "Server selection timeout: No available servers. Topology: { Type: Unknown, Servers: [ { Address: mongodb:27017, Type: Unknown, Error: failed to lookup address information: Name or service not known }, ] }",
        },
    },
)

MongoDB is running as a Docker container. How can I get this to work?

Aucun commentaire:

Enregistrer un commentaire