Practice 10

Modules, Crates and Tests

Read each program and pick an answer. Some programs do not compile, and that can be the right answer. Your choice is checked as soon as you pick it, and saved in this browser.Need a refresher? Read lesson 10.

Course

0 of 50 answered·0 correct

Modules and Paths

1.

What does this print?

mod garden {
    pub fn plant() {
        println!("seed planted");
    }
}

fn main() {
    garden::plant();
}
2.

What does this print?

mod garden {
    pub fn plant() {
        println!("seed planted");
    }

    pub fn water() {
        println!("garden watered");
    }
}

fn main() {
    garden::plant();
    garden::water();
}
3.

plant calls dig with no path at all. What does this print?

mod garden {
    fn dig() {
        println!("hole dug");
    }

    pub fn plant() {
        dig();
        println!("seed planted");
    }
}

fn main() {
    garden::plant();
}
4.

Does this compile?

mod garden {
    fn dig() {
        println!("hole dug");
    }
}

fn main() {
    garden::dig();
}
5.

What does this print?

mod restaurant {
    pub mod kitchen {
        pub fn bake_bread() {
            println!("bread is baking");
        }
    }

    pub mod service {
        use crate::restaurant::kitchen;

        pub fn serve() {
            kitchen::bake_bread();
            println!("bread is served");
        }
    }
}

fn main() {
    restaurant::service::serve();
}
6.

greet has no module around it, so it sits at the top of the program along with main. What does this print?

fn main() {
    crate::greet();
}

fn greet() {
    println!("hi");
}

Privacy Rules for Structs and Fields

7.

What does this print?

mod menu {
    pub struct Order {
        pub dish: String,
        price_cents: u32,
    }

    impl Order {
        pub fn new(dish: &str, price_cents: u32) -> Order {
            Order { dish: String::from(dish), price_cents }
        }

        pub fn price_cents(&self) -> u32 {
            self.price_cents
        }
    }
}

use menu::Order;

fn main() {
    let order = Order::new("soup", 450);
    println!("{} costs {}", order.dish, order.price_cents());
}
8.

dish is public here, but price_cents is not. Does this compile?

mod menu {
    pub struct Order {
        pub dish: String,
        price_cents: u32,
    }

    impl Order {
        pub fn new(dish: &str, price_cents: u32) -> Order {
            Order { dish: String::from(dish), price_cents }
        }
    }
}

use menu::Order;

fn main() {
    let order = Order::new("soup", 450);
    println!("{}", order.price_cents);
}
9.

Order has no pub on the struct itself, only on its dish field and its new function. Does this compile?

mod menu {
    struct Order {
        pub dish: String,
    }

    impl Order {
        pub fn new(dish: &str) -> Order {
            Order { dish: String::from(dish) }
        }
    }
}

fn main() {
    let order = menu::Order::new("soup");
    println!("{}", order.dish);
}
10.

What does this print?

mod account {
    pub struct Wallet {
        balance_cents: u32,
    }

    impl Wallet {
        pub fn new(balance_cents: u32) -> Wallet {
            Wallet { balance_cents }
        }

        pub fn balance_cents(&self) -> u32 {
            self.balance_cents
        }
    }
}

use account::Wallet;

fn main() {
    let w = Wallet::new(500);
    println!("{}", w.balance_cents());
}
11.

Does this compile?

mod account {
    pub struct Wallet {
        balance_cents: u32,
    }

    impl Wallet {
        pub fn new(balance_cents: u32) -> Wallet {
            Wallet { balance_cents }
        }
    }
}

use account::Wallet;

fn main() {
    let mut w = Wallet::new(500);
    w.balance_cents = 600;
    println!("{}", w.balance_cents);
}
12.

dish is public, but the struct literal below also sets price_cents, which is not. Does this compile?

mod menu {
    pub struct Order {
        pub dish: String,
        price_cents: u32,
    }
}

use menu::Order;

fn main() {
    let order = Order { dish: String::from("soup"), price_cents: 450 };
    println!("{}", order.dish);
}

Bringing Paths into Scope with use

13.

What does this print?

mod menu {
    pub struct Order {
        pub dish: String,
    }
}

use menu::Order;

fn main() {
    let order = Order { dish: String::from("tea") };
    println!("{}", order.dish);
}
14.

What does this print?

mod menu {
    pub struct Order {
        pub dish: String,
    }
}

use menu::Order as MenuItem;

fn main() {
    let order = MenuItem { dish: String::from("tea") };
    println!("{}", order.dish);
}
15.

This is the same program, except main still writes the struct's own name, Order. Does it compile?

mod menu {
    pub struct Order {
        pub dish: String,
    }
}

use menu::Order as MenuItem;

fn main() {
    let order = Order { dish: String::from("tea") };
    println!("{}", order.dish);
}
16.

What does this print?

mod kitchen {
    pub fn bake_bread() {
        println!("bread is baking");
    }
}

use kitchen::bake_bread;

fn main() {
    bake_bread();
}
17.

What does this print?

mod kitchen {
    pub fn bake_bread() {
        println!("bread is baking");
    }
}

use kitchen::bake_bread;

fn main() {
    bake_bread();
    kitchen::bake_bread();
}
18.

What does this print?

mod cafe {
    pub struct Drink {
        pub name: String,
    }
}

mod diner {
    pub struct Drink {
        pub name: String,
    }
}

use cafe::Drink as CafeDrink;
use diner::Drink as DinerDrink;

fn main() {
    let a = CafeDrink { name: String::from("tea") };
    let b = DinerDrink { name: String::from("soda") };
    println!("{} {}", a.name, b.name);
}

Nested Modules and crate Paths

19.

This calls bake_bread once by a relative path and once by an absolute one. What does it print?

mod restaurant {
    pub mod kitchen {
        pub fn bake_bread() {
            println!("bread is baking");
        }
    }
}

fn main() {
    restaurant::kitchen::bake_bread();
    crate::restaurant::kitchen::bake_bread();
}
20.

kitchen is marked pub, but bake_bread inside it is not. Does this compile?

mod restaurant {
    pub mod kitchen {
        fn bake_bread() {
            println!("bread is baking");
        }
    }
}

fn main() {
    restaurant::kitchen::bake_bread();
}
21.

This time bake_bread is marked pub, but kitchen itself is not. Does this compile?

mod restaurant {
    mod kitchen {
        pub fn bake_bread() {
            println!("bread is baking");
        }
    }
}

fn main() {
    restaurant::kitchen::bake_bread();
}
22.

front_desk reaches into kitchen the same way the lesson's example does, but bake_bread here has no pub. Does this compile?

mod restaurant {
    pub mod kitchen {
        fn bake_bread() {
            println!("bread is baking");
        }
    }

    pub mod front_desk {
        use crate::restaurant::kitchen;

        pub fn serve_bread() {
            kitchen::bake_bread();
            println!("bread is served");
        }
    }
}

fn main() {
    restaurant::front_desk::serve_bread();
}
23.

What does this print?

mod restaurant {
    pub mod front {
        pub mod desk {
            pub fn greet() {
                println!("welcome");
            }
        }
    }
}

fn main() {
    crate::restaurant::front::desk::greet();
}

Crates, Packages and Workspaces

24.

A package has both src/main.rs and src/lib.rs. How many crates does cargo build build from it, and what kind is each one?

25.

True or false: a crate can be a library crate with no main function.

26.

What is the difference between a binary crate and a library crate?

27.

Running cargo new on its own builds a package with how many crates?

28.

Building this workspace with cargo build makes how many target folders?

[workspace]
resolver = "3"
members = ["kitchen", "server"]
29.

What does cargo run print for server?

// kitchen/src/lib.rs
pub fn bake_bread() -> String {
    String::from("bread")
}
// server/src/main.rs
fn main() {
    println!("serving {}", kitchen::bake_bread());
}
30.

True or false: two packages in the same workspace can each build a different version of the same shared dependency.

Writing Tests with assert Macros

31.

Does cargo test pass or fail?

fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_two_numbers() {
        assert_eq!(add(2, 2), 4);
    }
}
32.

Does cargo test pass or fail? If it fails, what does the failure message show?

fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_two_numbers() {
        assert_eq!(add(2, 2), 5);
    }
}
33.

Does cargo test pass or fail?

fn square(n: i32) -> i32 {
    n * n
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn square_changes_value() {
        assert_ne!(square(3), 3);
    }
}
34.

assert_ne! fails the test when its two arguments are equal. Does cargo test pass or fail here?

fn identity(n: i32) -> i32 {
    n
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn identity_changes_value() {
        assert_ne!(identity(5), 5);
    }
}
35.

Does cargo test pass or fail?

fn is_even(n: i32) -> bool {
    n % 2 == 0
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn four_is_even() {
        assert!(is_even(4));
    }
}
36.

Does cargo test pass or fail?

fn is_even(n: i32) -> bool {
    n % 2 == 0
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn three_is_even() {
        assert!(is_even(3));
    }
}
37.

How many tests pass, and how many fail?

fn double(n: i32) -> i32 {
    n * 2
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn doubles_two() {
        assert_eq!(double(2), 4);
    }

    #[test]
    fn doubles_three() {
        assert_eq!(double(3), 5);
    }
}
38.

helper has no pub. Does this compile, and does the test pass?

fn helper(n: i32) -> i32 {
    n + 1
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn helper_adds_one() {
        assert_eq!(helper(1), 2);
    }
}

should_panic and Test Rules

39.

Does cargo test pass or fail?

pub fn greet(name: &str) -> String {
    if name.is_empty() {
        panic!("name must not be empty");
    }
    format!("hello, {name}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic]
    fn empty_name_panics() {
        greet("");
    }
}
40.

Does cargo test pass or fail?

pub fn greet(name: &str) -> String {
    if name.is_empty() {
        panic!("name must not be empty");
    }
    format!("hello, {name}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic]
    fn asha_panics() {
        greet("Asha");
    }
}
41.

How many tests pass, and how many fail?

pub fn greet(name: &str) -> String {
    if name.is_empty() {
        panic!("name must not be empty");
    }
    format!("hello, {name}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn greets_by_name() {
        assert_eq!(greet("Asha"), "hello, Asha");
    }

    #[test]
    #[should_panic]
    fn empty_name_panics() {
        greet("");
    }
}
42.

You build this with plain cargo build, not cargo test. Does the tests module get built into the program?

fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_two_numbers() {
        assert_eq!(add(2, 2), 4);
    }
}
43.

check takes a parameter. Does cargo test compile this?

#[cfg(test)]
mod tests {
    #[test]
    fn check(n: i32) {
        assert_eq!(n, 4);
    }
}

Unit Tests and Integration Tests

44.

True or false: an integration test, one in the tests folder, can call a private function of the library crate it is testing.

45.

The package greeter has this library crate and this integration test. Does cargo test pass or fail?

// greeter/src/lib.rs
pub fn greet(name: &str) -> String {
    format!("hello, {name}")
}
// greeter/tests/greet_tests.rs
use greeter::greet;

#[test]
fn greets_asha() {
    assert_eq!(greet("Asha"), "hello, Asha");
}
46.

shout has no pub. Does this compile?

// greeter/src/lib.rs
fn shout(name: &str) -> String {
    format!("HELLO, {}", name.to_uppercase())
}

pub fn greet(name: &str) -> String {
    shout(name)
}
// greeter/tests/greet_tests.rs
use greeter::shout;

#[test]
fn shout_tests() {
    assert_eq!(shout("Asha"), "HELLO, ASHA");
}
47.

Where does a unit test go, and where does an integration test go?

Everything Together

48.

What does main print, and does the test pass?

mod till {
    pub struct Sale {
        pub item: String,
        price_cents: u32,
    }

    impl Sale {
        pub fn new(item: &str, price_cents: u32) -> Sale {
            Sale { item: String::from(item), price_cents }
        }

        pub fn total_with_tax(&self) -> u32 {
            add_tax(self.price_cents)
        }
    }

    fn add_tax(price_cents: u32) -> u32 {
        price_cents + price_cents / 10
    }
}

use till::Sale;

fn main() {
    let sale = Sale::new("cake", 300);
    println!("{} costs {} cents with tax", sale.item, sale.total_with_tax());
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_ten_percent_tax() {
        let sale = Sale::new("cake", 300);
        assert_eq!(sale.total_with_tax(), 330);
    }
}
49.

till and counter are both modules inside shop, the same way kitchen and front_desk are both inside restaurant in the lesson. Does this compile?

mod shop {
    pub mod till {
        fn add_tax(price_cents: u32) -> u32 {
            price_cents + price_cents / 10
        }

        pub fn total(price_cents: u32) -> u32 {
            add_tax(price_cents)
        }
    }

    pub mod counter {
        use crate::shop::till;

        pub fn charge(price_cents: u32) -> u32 {
            till::add_tax(price_cents)
        }
    }
}

fn main() {
    println!("{}", shop::counter::charge(300));
}
50.

sum is private to stats, and average calls it. What does main print, and does the test pass?

mod stats {
    pub fn average(values: &[i32]) -> i32 {
        sum(values) / values.len() as i32
    }

    fn sum(values: &[i32]) -> i32 {
        values.iter().sum()
    }
}

use stats::average;

fn main() {
    let scores = [70, 80, 90];
    println!("{}", average(&scores));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn averages_three_scores() {
        assert_eq!(average(&[70, 80, 90]), 80);
    }
}