{"id":2815,"date":"2022-06-12T07:54:01","date_gmt":"2022-06-12T12:54:01","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=2815"},"modified":"2022-07-19T20:39:43","modified_gmt":"2022-07-20T01:39:43","slug":"rust-println-doesnt-work-in-unit-tests-solved","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-println-doesnt-work-in-unit-tests-solved\/","title":{"rendered":"Rust | Println! Doesn&#8217;t Work in Unit Tests (Solved)"},"content":{"rendered":"\n<p>If you are new to Rust programming language, there is a chance you are experiencing a deep learning curve in understanding how the programming language works. On top of that, you start writing your first couple of unit tests and suddenly realize that the logs from using the <a href=\"https:\/\/doc.rust-lang.org\/std\/macro.print.html\" target=\"_blank\" rel=\"noopener\">print<\/a> or <a href=\"https:\/\/doc.rust-lang.org\/std\/macro.println.html\" target=\"_blank\" rel=\"noopener\">println!<\/a> macro are not displayed in the terminal. <\/p>\n\n\n\n<p><strong>To fix println! not showing logs when running succesful unit tests, pass the <code>--show-ouput<\/code> flag at the moment of executing the command to run tests <code>cargo test<\/code>. Hence, the new command to run tests and display logs generated from using the println macro is <code>cargo test -- --show-output<\/code>.<\/strong><\/p>\n\n\n\n<p><code>cargo test -- --show-output<\/code><\/p>\n\n\n\n<p>Let&#8217;s look at the following example. We have a simple <code>display_text<\/code> function that only displays a log of a &amp;str using println!, and returns a <code>&amp;\"Text displayed\"<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    \n    display_text(\"Hello World!\");\n\n}\n\nfn display_text(text: &amp;str) -&gt; &amp;str {\n    println!(\"Displaying Text {0}\", text);\n\n    &amp;\"Text displayed\"\n}\n\n#&#91;cfg(test)]\nmod test {\n    use super::*;\n\n    #&#91;test]\n    fn test_display_text() {\n        println!(\"Running test on display_text function\");\n        assert_eq!(display_text(\"Hello!\"), \"Text displayed\")\n    }\n}<\/code><\/pre>\n\n\n\n<p>Notice there is a test to test the <code>display_text<\/code> function that checks whether the returned <code>&amp;str<\/code> is &#8220;Text displayed&#8221;.<\/p>\n\n\n\n<p>Running the standard <code>cargo test<\/code> command will give us the following result.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>$ cargo test\n    Finished test &#91;unoptimized + debuginfo] target(s) in 0.23s\n     Running unittests (target\\debug\\deps\\rust_playground-afbcb92314fac06b.exe)\n\nrunning 1 test\ntest test::test_display_text ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.06s<\/code><\/pre>\n\n\n\n<p>Notice the logs that should have been generated from <code>println!(\"Displaying Text {0}\", text);<\/code> and <code>println!(\"Running test on display_text function\");<\/code> are not visible. Luckily, now that we know about the <code>--show-output<\/code> flag, we can get the outputs in the terminal similar to the following:<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>$ cargo test --  --show-output\n    Finished test &#91;unoptimized + debuginfo] target(s) in 0.24s\n     Running unittests (target\\debug\\deps\\rust_playground-afbcb92314fac06b.exe)\n\nrunning 1 test\ntest test::test_display_text ... ok\n\nsuccesses:\n\n---- test::test_display_text stdout ----\nRunning test on display_text function\nDisplaying Text Hello!\n\n\nsuccesses:\n    test::test_display_text\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.06s<\/code><\/pre>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-println-doesnt-work-in-unit-tests-solved\/#Another_way_to_discover_the_-show-output_flag\" >Another way to discover the --show-output flag<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-println-doesnt-work-in-unit-tests-solved\/#Why_does_Rust_not_show_the_output_by_default_when_executing_successful_unit_tests\" >Why does Rust not show the output by default when executing successful unit tests?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-println-doesnt-work-in-unit-tests-solved\/#Failing_tests_display_the_logs_from_println_macro_by_default\" >Failing tests display the logs from println! macro by default<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Another_way_to_discover_the_-show-output_flag\"><\/span>Another way to discover the <code>--show-output<\/code> flag<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>If this is not your first time seeing the <code>--show-output<\/code> flag, there is a probability you discovered it by using  the <code>--help<\/code>command to find out about all the different options available when running tests.<\/p>\n\n\n\n<p>Hence, if you run <code>cargo test -- --help<\/code>, the terminal will display all the options.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>Options:\n        --include-ignored \n                        Run ignored and not ignored tests\n        --ignored       Run only ignored tests\n        --force-run-in-process\n                        Forces tests to run in-process when panic=abort\n        --exclude-should-panic\n                        Excludes tests marked as should_panic\n        --test          Run tests and not benchmarks\n        --bench         Run benchmarks instead of tests\n        --list          List all tests and benchmarks\n    -h, --help          Display this message\n        --logfile PATH  Write logs to the specified file\n        --nocapture     don't capture stdout\/stderr of each task, allow\n                        printing directly\n        --test-threads n_threads\n                        Number of threads used for running tests in parallel\n        --skip FILTER   Skip tests whose names contain FILTER (this flag can\n                        be used multiple times)\n    -q, --quiet         Display one character per test instead of one line.\n                        Alias to --format=terse\n        --exact         Exactly match filters rather than by substring\n        --color auto|always|never\n                        Configure coloring of output:\n                        auto = colorize if stdout is a tty and tests are run\n                        on serially (default);\n                        always = always colorize output;\n                        never = never colorize output;\n        --format pretty|terse|json|junit\n                        Configure formatting of output:\n                        pretty = Print verbose output;\n                        terse = Display one character per test;\n                        json = Output a json document;\n                        junit = Output a JUnit document\n        --show-output   Show captured stdout of successful tests\n    -Z unstable-options Enable nightly-only flags:\n                        unstable-options = Allow use of experimental features\n        --report-time &#91;plain|colored]\n                        Show execution time of each test. Available values:\n                        plain = do not colorize the execution time (default);\n                        colored = colorize output according to the `color`\n                        parameter value;\n                        Threshold values for colorized output can be\n                        configured via\n                        `RUST_TEST_TIME_UNIT`, `RUST_TEST_TIME_INTEGRATION`\n                        and\n                        `RUST_TEST_TIME_DOCTEST` environment variables.\n                        Expected format of environment variable is\n                        `VARIABLE=WARN_TIME,CRITICAL_TIME`.\n                        Durations must be specified in milliseconds, e.g.\n                        `500,2000` means that the warn time\n                        is 0.5 seconds, and the critical time is 2 seconds.\n                        Not available for --format=terse\n        --ensure-time   Treat excess of the test execution time limit as\n                        error.\n                        Threshold values for this option can be configured via\n                        `RUST_TEST_TIME_UNIT`, `RUST_TEST_TIME_INTEGRATION`\n                        and\n                        `RUST_TEST_TIME_DOCTEST` environment variables.\n                        Expected format of environment variable is\n                        `VARIABLE=WARN_TIME,CRITICAL_TIME`.\n                        `CRITICAL_TIME` here means the limit that should not\n                        be exceeded by test.\n        --shuffle       Run tests in random order\n        --shuffle-seed SEED\n                        Run tests in random order; seed the random number\n                        generator with SEED<\/code><\/pre>\n\n\n\n<p>Notice option <code>--show-output<\/code> says <code><strong>Show captured stdout of successful tests<\/strong><\/code>. In other words, show logs in the terminal from executing succesful tests.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Why_does_Rust_not_show_the_output_by_default_when_executing_successful_unit_tests\"><\/span>Why does Rust not show the output by default when executing successful unit tests?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>While there isn&#8217;t an official statement from the Rust team, <strong>it is said among the community of Rust developers that Rust hides the logs generated when running unit tests to keep the final output clean to easily identify successful tests<\/strong>.<\/p>\n\n\n\n<p>This can be new for programmers coming from a different background such as JavaScript where no matter whether you are running a test, logging using <code>console.log<\/code> displays the output in the terminal without the need of passing a flag like <code>--show-output<\/code> in Rust.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Failing_tests_display_the_logs_from_println_macro_by_default\"><\/span>Failing tests display the logs from println! macro by default<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>If you haven&#8217;t noticed by now, we have been saying logs from println! macro doesn&#8217;t show by default when executing succesful tests. However, this is not the case when executing failing tests.<\/p>\n\n\n\n<p>If we add a test we know will fail such as the following<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>#&#91;cfg(test)]\nmod test {\n    use super::*;\n\n    #&#91;test]\n    fn gtest_display_text() {\n        println!(\"BAD\");\n        assert_eq!(display_text(\"Hello!\"), \"FAILING!\")\n    }\n}<\/code><\/pre>\n\n\n\n<p>and run <code>cargo test<\/code> you will see the log &#8220;BAD&#8221; is displayed in the terminal.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>$ cargo test\n   Compiling rust_playground v0.1.0 (C:\\Users\\andry\\Repos\\blog-articles\\rust_playground)\n    Finished test &#91;unoptimized + debuginfo] target(s) in 0.99s\n     Running unittests (target\\debug\\deps\\rust_playground-afbcb92314fac06b.exe)\n\nrunning 1 test\ntest test::gtest_display_text ... FAILED\n\nfailures:\n\n---- test::gtest_display_text stdout ----\nBAD\nDisplaying Text Hello!\nthread 'test::gtest_display_text' panicked at 'assertion failed: `(left == right)`\n  left: `\"Text displayed\"`,\n right: `\"FAILING!\"`', src\\main.rs:20:9\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n    test::gtest_display_text\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.06s\n\nerror: test failed, to rerun pass '--bin rust_playground'<\/code><\/pre>\n\n\n\n<p>This was confirmed by <a href=\"https:\/\/twitter.com\/m_ou_se\" target=\"_blank\" rel=\"noopener\">Mara Bos<\/a> who is part of the Rust team at the moment of writing this article.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/twitter.com\/m_ou_se\/status\/1535957171338465280\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>If you are new to Rust programming language, there is a chance you are experiencing a deep learning curve in understanding how the programming language works. On top of that, you start writing your first couple of unit tests and suddenly realize that the logs from using the print or println! macro are not displayed &#8230; <a title=\"Rust | Println! Doesn&#8217;t Work in Unit Tests (Solved)\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-println-doesnt-work-in-unit-tests-solved\/\" aria-label=\"More on Rust | Println! Doesn&#8217;t Work in Unit Tests (Solved)\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":2833,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[31],"tags":[],"class_list":["post-2815","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-rust","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2815","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=2815"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2815\/revisions"}],"predecessor-version":[{"id":3121,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2815\/revisions\/3121"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/2833"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2815"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2815"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2815"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}