Doc Tests क्या हैं
In this page:
/// Description.
///
/// ```
/// let result = crate_name::function(arg);
/// assert_eq!(result, expected);
/// ```
fn function() {}
Writing a Doc Test
किसी function के ऊपर /// documentation comment के अंदर एक fenced code block अपने आप एक runnable example माना जाता है और cargo test से execute होता है।
उदाहरण: Writing a Doc Test
/// Adds one to the given number.
///
/// ```
/// let result = my_project::add_one(5);
/// assert_eq!(result, 6);
/// ```
pub fn add_one(n: i32) -> i32 {
n + 1
}
fn main() {
println!("add_one(5) = {}", add_one(5));
}
Login to try C/C++/Java/PHP code in the editor
Doc Tests Keep Examples Honest
चूंकि doc comment में example असल में compile और execute होता है, अगर function का behavior कभी ऐसे बदले जो example को तोड़ दे, cargo test fail हो जाएगा और आपको alert करेगा।
उदाहरण: Doc Tests Keep Examples Honest
/// Doubles the given number.
///
/// ```
/// assert_eq!(my_project::double(3), 6);
/// ```
pub fn double(n: i32) -> i32 {
n * 2
}
fn main() {
println!("double(3) = {}", double(3));
}
Login to try C/C++/Java/PHP code in the editor
Multiple Assertions in One Doc Test
एक single doc test के code block में कई statements और कई assertions हो सकते हैं, बिल्कुल एक ordinary test function की तरह, एक साथ कुछ related cases cover करने के लिए।
उदाहरण: Multiple Assertions in One Doc Test
/// Checks whether a number is positive.
///
/// ```
/// assert!(my_project::is_positive(5));
/// assert!(!my_project::is_positive(-3));
/// ```
pub fn is_positive(n: i32) -> bool {
n > 0
}
fn main() {
println!("is_positive(5) = {}", is_positive(5));
println!("is_positive(-3) = {}", is_positive(-3));
}
Login to try C/C++/Java/PHP code in the editor
Running Doc Tests
cargo test अपने आप unit और integration tests के साथ हर doc test discover और चलाता है, तीनों तरह के tests verify करने के लिए एक unified command देते हुए।
उदाहरण: Running Doc Tests
cargo test
⚠️ Run this in your own terminal or Node.js environment.
- doc comment में triple backticks में wrap किए बिना एक example लिखना, इसलिए
cargo testइसे कभी एक doc test के रूप में पहचानता नहीं। - function का behavior बदलने के बाद एक doc example को stale होने देना, जब
cargo testने mismatch अपने आप पकड़ लिया होता। - यह भूल जाना कि doc tests को असल में compile और सफलतापूर्वक चलना चाहिए, इनके अंदर रखी किसी भी
assert_eq!checks सहित।
- triple backticks से fenced, किसी
///doc comment के अंदर एक code block अपने आप compile और एक test के रूप में चलता है। - Doc tests documentation examples को accurate रखते हैं, क्योंकि एक टूटा example
cargo testको बिल्कुल एक normal test की तरह fail कराता है। assert_eq!और similar macros किसी doc test के code block के अंदर सीधे behavior verify करने के लिए उपयोग किए जा सकते हैं।- Doc tests
cargo testके हिस्से के रूप में चलते हैं, unit और integration tests के साथ।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: