OXYGENHUB
# 8aafd2023dec oxygenhub / crates / hub / src / coverage.rs
19.9 KiB · Rust · last changed A coverage check, and rules for it 1 month ago source blame history raw
1
//! Coverage reports (oxygenhub#113): Coveralls built into the hub. An
2
//! OxygenFlow job that declares an artifact named `coverage` in LCOV
3
//! format (what `cargo llvm-cov --lcov`, Istanbul, coverage.py and
4
//! gcov/lcov write) has it parsed when it is uploaded. The totals and each
5
//! file's counts are kept per run; the per-line counts are read again from
6
//! the artifact's blob for the file view. Paths are taken relative to the
7
//! job's workspace (`/src`), and only files of the run's state are kept.
8
9
use crate::db::{now_ms, Pool};
10
use crate::Shared;
11
use std::collections::{BTreeMap, HashSet};
12
use std::sync::Mutex;
13
14
/// The artifact name a pipeline gives its report.
15
pub const ARTIFACT: &str = "coverage";
16
/// The largest report parsed.
17
pub const MAX_REPORT: usize = 64 << 20;
18
19
/// One file's coverage, from a report.
20
#[derive(Clone, Debug, Default, PartialEq, Eq)]
21
pub struct FileCoverage {
22
    /// Relative to the repository's root.
23
    pub path: String,
24
    /// Each instrumented line and how often it ran, by line number.
25
    pub lines: BTreeMap<u32, u64>,
26
    pub functions_found: u64,
27
    pub functions_hit: u64,
28
    pub branches_found: u64,
29
    pub branches_hit: u64,
30
    /// The file's own `LF`/`LH` totals, when it had one record: the tool's
31
    /// own count, which can name lines the `DA` lines leave out (llvm-cov
32
    /// does), so the hub agrees with what the tool printed.
33
    pub declared_lines: Option<(u64, u64)>,
34
}
35
36
impl FileCoverage {
37
    pub fn lines_found(&self) -> u64 {
38
        self.declared_lines.map(|d| d.0).unwrap_or(self.lines.len() as u64)
39
    }
40
41
    pub fn lines_hit(&self) -> u64 {
42
        self.declared_lines.map(|d| d.1).unwrap_or_else(|| self.lines.values().filter(|n| **n > 0).count() as u64)
43
    }
44
45
    /// Every run of every line, added up.
46
    pub fn hits(&self) -> u64 {
47
        self.lines.values().fold(0u64, |a, n| a.saturating_add(*n))
48
    }
49
}
50
51
/// A path as a report names it, relative to the repository: the Flow
52
/// workspace's `/src/` and a leading `./` taken off. `None` for a path
53
/// outside the repository.
54
pub fn relative(path: &str) -> Option<String> {
55
    let p = path.trim();
56
    let p = p.strip_prefix("/src/").unwrap_or(p);
57
    let p = p.strip_prefix("./").unwrap_or(p);
58
    if p.is_empty() || p.starts_with('/') || p.contains('\\') || p.split('/').any(|s| s.is_empty() || s == "." || s == "..") {
59
        return None;
60
    }
61
    Some(p.to_string())
62
}
63
64
#[derive(Default)]
65
struct Acc {
66
    lines: BTreeMap<u32, u64>,
67
    functions: BTreeMap<String, u64>,
68
    branches: BTreeMap<(u32, String, String), u64>,
69
    declared_fn: (u64, u64),
70
    declared_br: (u64, u64),
71
    declared_lines: (Option<u64>, Option<u64>),
72
    records: u32,
73
}
74
75
/// Parse an LCOV report into each file's coverage, records for the same
76
/// file (from several test binaries) added together. Files whose paths
77
/// are outside the repository are counted in the second value.
78
pub fn parse_lcov(text: &str) -> Result<(Vec<FileCoverage>, usize), String> {
79
    let mut files: BTreeMap<String, Acc> = BTreeMap::new();
80
    let mut current: Option<Option<String>> = None;
81
    let mut outside = HashSet::new();
82
    let mut records = 0usize;
83
    // A new SF: record has begun and not yet been counted for its file.
84
    let mut started = false;
85
    let num = |s: &str| s.trim().parse::<u64>().unwrap_or(0);
86
    for line in text.lines() {
87
        let line = line.trim();
88
        if let Some(path) = line.strip_prefix("SF:") {
89
            records += 1;
90
            let rel = relative(path);
91
            if rel.is_none() {
92
                outside.insert(path.to_string());
93
            }
94
            current = Some(rel);
95
            started = true;
96
            continue;
97
        }
98
        if line == "end_of_record" {
99
            current = None;
100
            continue;
101
        }
102
        let Some(Some(path)) = &current else { continue };
103
        let acc = files.entry(path.clone()).or_default();
104
        if line == "TN:" || line.starts_with("TN:") {
105
            continue;
106
        }
107
        if std::mem::take(&mut started) {
108
            acc.records += 1;
109
        }
110
        if let Some(n) = line.strip_prefix("LF:") {
111
            acc.declared_lines.0 = Some(num(n));
112
        } else if let Some(n) = line.strip_prefix("LH:") {
113
            acc.declared_lines.1 = Some(num(n));
114
        } else if let Some(rest) = line.strip_prefix("DA:") {
115
            let mut parts = rest.split(',');
116
            if let (Some(l), Some(n)) = (parts.next(), parts.next()) {
117
                if let Ok(l) = l.trim().parse::<u32>() {
118
                    *acc.lines.entry(l).or_default() += num(n);
119
                }
120
            }
121
        } else if let Some(rest) = line.strip_prefix("FN:") {
122
            if let Some((_, name)) = rest.split_once(',') {
123
                acc.functions.entry(name.to_string()).or_default();
124
            }
125
        } else if let Some(rest) = line.strip_prefix("FNDA:") {
126
            if let Some((n, name)) = rest.split_once(',') {
127
                *acc.functions.entry(name.to_string()).or_default() += num(n);
128
            }
129
        } else if let Some(rest) = line.strip_prefix("BRDA:") {
130
            let parts: Vec<&str> = rest.split(',').collect();
131
            if let [l, block, branch, taken] = parts[..] {
132
                if let Ok(l) = l.trim().parse::<u32>() {
133
                    let taken = if taken.trim() == "-" { 0 } else { num(taken) };
134
                    *acc.branches.entry((l, block.to_string(), branch.to_string())).or_default() += taken;
135
                }
136
            }
137
        } else if let Some(n) = line.strip_prefix("FNF:") {
138
            acc.declared_fn.0 = acc.declared_fn.0.max(num(n));
139
        } else if let Some(n) = line.strip_prefix("FNH:") {
140
            acc.declared_fn.1 = acc.declared_fn.1.max(num(n));
141
        } else if let Some(n) = line.strip_prefix("BRF:") {
142
            acc.declared_br.0 = acc.declared_br.0.max(num(n));
143
        } else if let Some(n) = line.strip_prefix("BRH:") {
144
            acc.declared_br.1 = acc.declared_br.1.max(num(n));
145
        }
146
    }
147
    if records == 0 {
148
        return Err("this is not an LCOV report: it names no source file (no SF: line)".into());
149
    }
150
    let out = files
151
        .into_iter()
152
        .map(|(path, a)| {
153
            let (functions_found, functions_hit) = if a.functions.is_empty() {
154
                a.declared_fn
155
            } else {
156
                (a.functions.len() as u64, a.functions.values().filter(|n| **n > 0).count() as u64)
157
            };
158
            let (branches_found, branches_hit) = if a.branches.is_empty() {
159
                a.declared_br
160
            } else {
161
                (a.branches.len() as u64, a.branches.values().filter(|n| **n > 0).count() as u64)
162
            };
163
            let declared_lines = match (a.records, a.declared_lines) {
164
                (1, (Some(f), Some(h))) if h <= f && f >= a.lines.len() as u64 => Some((f, h)),
165
                _ => None,
166
            };
167
            FileCoverage { path, lines: a.lines, functions_found, functions_hit, branches_found, branches_hit, declared_lines }
168
        })
169
        .collect();
170
    Ok((out, outside.len()))
171
}
172
173
/// A percentage to one decimal place, or none when nothing was counted.
174
pub fn percent(hit: i64, found: i64) -> Option<f64> {
175
    (found > 0).then(|| (hit as f64 * 1000.0 / found as f64).round() / 10.0)
176
}
177
178
#[derive(Clone, Debug, sqlx::FromRow)]
179
pub struct Report {
180
    pub id: i64,
181
    pub repo_id: i64,
182
    pub run_id: i64,
183
    pub job_id: i64,
184
    pub job: String,
185
    pub run_number: i64,
186
    pub bookmark: String,
187
    pub state: String,
188
    pub heads: String,
189
    pub blob: String,
190
    pub format: String,
191
    pub lines_found: i64,
192
    pub lines_hit: i64,
193
    pub functions_found: i64,
194
    pub functions_hit: i64,
195
    pub branches_found: i64,
196
    pub branches_hit: i64,
197
    pub hits: i64,
198
    pub files: i64,
199
    pub dropped: i64,
200
    pub created_ms: i64,
201
}
202
203
impl Report {
204
    /// How often an instrumented line ran, on average.
205
    pub fn hits_per_line(&self) -> Option<f64> {
206
        (self.lines_found > 0).then(|| self.hits as f64 / self.lines_found as f64)
207
    }
208
209
    pub fn percent(&self) -> Option<f64> {
210
        percent(self.lines_hit, self.lines_found)
211
    }
212
213
    pub fn functions_percent(&self) -> Option<f64> {
214
        percent(self.functions_hit, self.functions_found)
215
    }
216
217
    pub fn branches_percent(&self) -> Option<f64> {
218
        percent(self.branches_hit, self.branches_found)
219
    }
220
221
    pub fn head_list(&self) -> Vec<&str> {
222
        self.heads.split(',').filter(|h| !h.is_empty()).collect()
223
    }
224
}
225
226
#[derive(Clone, Debug, sqlx::FromRow)]
227
pub struct FileRow {
228
    pub report_id: i64,
229
    pub path: String,
230
    pub lines_found: i64,
231
    pub lines_hit: i64,
232
    pub functions_found: i64,
233
    pub functions_hit: i64,
234
    pub branches_found: i64,
235
    pub branches_hit: i64,
236
}
237
238
impl FileRow {
239
    pub fn percent(&self) -> Option<f64> {
240
        percent(self.lines_hit, self.lines_found)
241
    }
242
243
    pub fn missed(&self) -> i64 {
244
        self.lines_found - self.lines_hit
245
    }
246
}
247
248
/// Repositories with a report, so their pages show the Coverage tab:
249
/// keyed by the hub's repository root and the id, unique even between
250
/// hubs in one process.
251
static HAS: Mutex<Option<HashSet<String>>> = Mutex::new(None);
252
253
fn key(app: &Shared, repo_id: i64) -> String {
254
    format!("{}#{repo_id}", app.repos.root().display())
255
}
256
257
pub fn has_reports(app: &Shared, repo_id: i64) -> bool {
258
    HAS.lock().unwrap_or_else(|p| p.into_inner()).as_ref().is_some_and(|s| s.contains(&key(app, repo_id)))
259
}
260
261
fn mark(app: &Shared, repo_id: i64) {
262
    HAS.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(HashSet::new).insert(key(app, repo_id));
263
}
264
265
/// At start: which repositories have reports.
266
pub async fn load(app: &Shared) -> sqlx::Result<()> {
267
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT DISTINCT repo_id FROM coverage_reports").fetch_all(&app.db).await?;
268
    for (id,) in ids {
269
        mark(app, id);
270
    }
271
    Ok(())
272
}
273
274
/// What a run's report is kept with.
275
pub struct Origin<'a> {
276
    pub repo_id: i64,
277
    pub run_id: i64,
278
    pub run_number: i64,
279
    pub job_id: i64,
280
    pub job: &'a str,
281
    pub bookmark: &'a str,
282
    pub state: &'a str,
283
    pub heads: &'a [String],
284
    pub blob: &'a str,
285
}
286
287
/// Keep a parsed report: the files outside `in_state` are dropped and
288
/// counted. Replaces an earlier report of the same job.
289
pub async fn keep(app: &Shared, o: &Origin<'_>, files: Vec<FileCoverage>, outside: usize, in_state: &HashSet<String>) -> sqlx::Result<i64> {
290
    let (kept, missing): (Vec<FileCoverage>, Vec<FileCoverage>) = files.into_iter().partition(|f| in_state.contains(&f.path));
291
    let sum = |f: &dyn Fn(&FileCoverage) -> u64| kept.iter().map(f).sum::<u64>() as i64;
292
    let mut tx = crate::db::begin_write(&app.db).await?;
293
    sqlx::query("DELETE FROM coverage_reports WHERE job_id = ?").bind(o.job_id).execute(&mut *tx).await?;
294
    let id: i64 = sqlx::query_scalar(
295
        "INSERT INTO coverage_reports (repo_id, run_id, job_id, job, run_number, bookmark, state, heads, blob, format, \
296
         lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit, hits, files, dropped, created_ms) \
297
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'lcov', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
298
    )
299
    .bind(o.repo_id)
300
    .bind(o.run_id)
301
    .bind(o.job_id)
302
    .bind(o.job)
303
    .bind(o.run_number)
304
    .bind(o.bookmark)
305
    .bind(o.state)
306
    .bind(o.heads.join(","))
307
    .bind(o.blob)
308
    .bind(sum(&|f| f.lines_found()))
309
    .bind(sum(&|f| f.lines_hit()))
310
    .bind(sum(&|f| f.functions_found))
311
    .bind(sum(&|f| f.functions_hit))
312
    .bind(sum(&|f| f.branches_found))
313
    .bind(sum(&|f| f.branches_hit))
314
    .bind(kept.iter().fold(0u64, |a, f| a.saturating_add(f.hits())).min(i64::MAX as u64) as i64)
315
    .bind(kept.len() as i64)
316
    .bind((missing.len() + outside) as i64)
317
    .bind(now_ms())
318
    .fetch_one(&mut *tx)
319
    .await?;
320
    for f in &kept {
321
        sqlx::query(
322
            "INSERT INTO coverage_files (report_id, path, lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit) \
323
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
324
        )
325
        .bind(id)
326
        .bind(&f.path)
327
        .bind(f.lines_found() as i64)
328
        .bind(f.lines_hit() as i64)
329
        .bind(f.functions_found as i64)
330
        .bind(f.functions_hit as i64)
331
        .bind(f.branches_found as i64)
332
        .bind(f.branches_hit as i64)
333
        .execute(&mut *tx)
334
        .await?;
335
    }
336
    tx.commit().await?;
337
    mark(app, o.repo_id);
338
    Ok(id)
339
}
340
341
pub async fn report(pool: &Pool, repo_id: i64, id: i64) -> sqlx::Result<Option<Report>> {
342
    sqlx::query_as("SELECT * FROM coverage_reports WHERE id = ? AND repo_id = ?").bind(id).bind(repo_id).fetch_optional(pool).await
343
}
344
345
/// The newest reports on a bookmark, newest first.
346
pub async fn on_bookmark(pool: &Pool, repo_id: i64, bookmark: &str, limit: i64) -> sqlx::Result<Vec<Report>> {
347
    sqlx::query_as("SELECT * FROM coverage_reports WHERE repo_id = ? AND bookmark = ? ORDER BY created_ms DESC, id DESC LIMIT ?")
348
        .bind(repo_id)
349
        .bind(bookmark)
350
        .bind(limit)
351
        .fetch_all(pool)
352
        .await
353
}
354
355
/// When the repository's first report on any bookmark was kept.
356
pub async fn first_ms(pool: &Pool, repo_id: i64) -> sqlx::Result<Option<i64>> {
357
    sqlx::query_scalar("SELECT MIN(created_ms) FROM coverage_reports WHERE repo_id = ?").bind(repo_id).fetch_one(pool).await
358
}
359
360
/// The bookmarks with reports, the most recent first.
361
pub async fn bookmarks(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
362
    sqlx::query_scalar("SELECT bookmark FROM coverage_reports WHERE repo_id = ? GROUP BY bookmark ORDER BY MAX(created_ms) DESC")
363
        .bind(repo_id)
364
        .fetch_all(pool)
365
        .await
366
}
367
368
/// A repository's coverage rules.
369
#[derive(Clone, Copy, Debug, Default, PartialEq)]
370
pub struct Rules {
371
    /// The check fails below this percentage.
372
    pub min: Option<f64>,
373
    /// The check fails when coverage falls more than this many points.
374
    pub max_drop: Option<f64>,
375
}
376
377
pub async fn rules(pool: &Pool, repo_id: i64) -> sqlx::Result<Rules> {
378
    let row: Option<(Option<f64>, Option<f64>)> =
379
        sqlx::query_as("SELECT min, max_drop FROM coverage_settings WHERE repo_id = ?").bind(repo_id).fetch_optional(pool).await?;
380
    Ok(row.map(|(min, max_drop)| Rules { min, max_drop }).unwrap_or_default())
381
}
382
383
pub async fn set_rules(pool: &Pool, repo_id: i64, r: Rules) -> sqlx::Result<()> {
384
    sqlx::query(
385
        "INSERT INTO coverage_settings (repo_id, min, max_drop) VALUES (?, ?, ?) \
386
         ON CONFLICT (repo_id) DO UPDATE SET min = excluded.min, max_drop = excluded.max_drop",
387
    )
388
    .bind(repo_id)
389
    .bind(r.min)
390
    .bind(r.max_drop)
391
    .execute(pool)
392
    .await?;
393
    Ok(())
394
}
395
396
/// What a report is measured against: on the default bookmark, the report
397
/// before it there; on any other, the default bookmark's latest before it.
398
pub async fn baseline(pool: &Pool, r: &Report, default_bookmark: &str) -> sqlx::Result<Option<Report>> {
399
    sqlx::query_as(
400
        "SELECT * FROM coverage_reports WHERE repo_id = ? AND bookmark = ? AND id <> ? AND (created_ms < ? OR (created_ms = ? AND id < ?)) \
401
         ORDER BY created_ms DESC, id DESC LIMIT 1",
402
    )
403
    .bind(r.repo_id)
404
    .bind(default_bookmark)
405
    .bind(r.id)
406
    .bind(r.created_ms)
407
    .bind(r.created_ms)
408
    .bind(r.id)
409
    .fetch_optional(pool)
410
    .await
411
}
412
413
/// The `coverage` check for a report: passed or failed, and what to say.
414
pub fn verdict(r: &Report, base: Option<&Report>, base_name: &str, rules: Rules) -> (&'static str, String) {
415
    let Some(p) = r.percent() else { return ("passed", "no instrumented lines".into()) };
416
    let delta = base.and_then(|b| Some(p - b.percent()?));
417
    let against = match delta {
418
        Some(d) if d.abs() < 0.05 => format!(", unchanged against {base_name}"),
419
        Some(d) => format!(" ({d:+.1} against {base_name})"),
420
        None => String::new(),
421
    };
422
    if let Some(min) = rules.min.filter(|m| p < *m) {
423
        return ("failed", format!("{p:.1}%{against}: below the minimum of {min}%"));
424
    }
425
    if let (Some(max), Some(d)) = (rules.max_drop, delta) {
426
        if d < -max {
427
            return ("failed", format!("{p:.1}%{against}: falls more than the {max} points allowed"));
428
        }
429
    }
430
    ("passed", format!("{p:.1}%{against}"))
431
}
432
433
pub async fn for_run(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Report>> {
434
    sqlx::query_as("SELECT * FROM coverage_reports WHERE run_id = ? ORDER BY job").bind(run_id).fetch_all(pool).await
435
}
436
437
pub async fn files(pool: &Pool, report_id: i64) -> sqlx::Result<Vec<FileRow>> {
438
    sqlx::query_as("SELECT * FROM coverage_files WHERE report_id = ? ORDER BY path").bind(report_id).fetch_all(pool).await
439
}
440
441
#[cfg(test)]
442
mod tests {
443
    use super::*;
444
445
    const LCOV: &str = "TN:\nSF:/src/crates/a/src/lib.rs\nFN:3,alpha\nFN:9,beta\nFNDA:4,alpha\nFNDA:0,beta\nFNF:2\nFNH:1\n\
446
DA:3,4\nDA:4,4\nDA:9,0\nDA:10,0\nBRDA:4,0,0,3\nBRDA:4,0,1,-\nBRF:2\nBRH:1\nLF:4\nLH:2\nend_of_record\n\
447
SF:/src/crates/a/src/lib.rs\nDA:9,1\nend_of_record\n\
448
SF:./README.md\nDA:1,1\nend_of_record\n\
449
SF:/home/runner/.cargo/registry/src/dep/lib.rs\nDA:1,1\nend_of_record\n";
450
451
    #[test]
452
    fn lcov_reports_are_read_and_merged() {
453
        let (files, outside) = parse_lcov(LCOV).unwrap();
454
        assert_eq!(outside, 1, "the dependency outside the workspace");
455
        assert_eq!(files.len(), 2);
456
        let lib = &files[1];
457
        assert_eq!(lib.path, "crates/a/src/lib.rs");
458
        assert_eq!(lib.lines, [(3, 4), (4, 4), (9, 1), (10, 0)].into_iter().collect());
459
        assert_eq!((lib.lines_found(), lib.lines_hit()), (4, 3), "the second record ran line 9");
460
        assert_eq!((lib.functions_found, lib.functions_hit), (2, 1));
461
        assert_eq!((lib.branches_found, lib.branches_hit), (2, 1));
462
        assert_eq!(files[0].path, "README.md");
463
        assert_eq!(lib.declared_lines, None, "two records: counted from the lines");
464
        // One record whose totals name lines its DA lines leave out, as llvm-cov writes.
465
        let (one, _) = parse_lcov("SF:/src/a.rs\nDA:1,1\nDA:2,0\nLF:5\nLH:3\nend_of_record\n").unwrap();
466
        assert_eq!((one[0].lines_found(), one[0].lines_hit()), (5, 3));
467
        assert!(parse_lcov("not a report\n").unwrap_err().contains("not an LCOV report"));
468
    }
469
470
    #[test]
471
    fn the_check_follows_the_rules() {
472
        let report = |pct_hit: i64| Report {
473
            id: 2,
474
            repo_id: 1,
475
            run_id: 1,
476
            job_id: 1,
477
            job: "test".into(),
478
            run_number: 1,
479
            bookmark: "feature".into(),
480
            state: String::new(),
481
            heads: String::new(),
482
            blob: String::new(),
483
            format: "lcov".into(),
484
            lines_found: 1000,
485
            lines_hit: pct_hit,
486
            functions_found: 0,
487
            functions_hit: 0,
488
            branches_found: 0,
489
            branches_hit: 0,
490
            hits: 0,
491
            files: 1,
492
            dropped: 0,
493
            created_ms: 0,
494
        };
495
        let (now, before) = (report(819), report(822));
496
        let none = Rules::default();
497
        assert_eq!(verdict(&now, Some(&before), "main", none), ("passed", "81.9% (-0.3 against main)".to_string()));
498
        assert_eq!(verdict(&now, None, "main", none), ("passed", "81.9%".to_string()));
499
        assert_eq!(verdict(&now, Some(&now), "main", none).1, "81.9%, unchanged against main");
500
        let strict = Rules { min: Some(85.0), max_drop: None };
501
        assert_eq!(
502
            verdict(&now, Some(&before), "main", strict),
503
            ("failed", "81.9% (-0.3 against main): below the minimum of 85%".to_string())
504
        );
505
        let drop = Rules { min: None, max_drop: Some(0.2) };
506
        assert_eq!(verdict(&now, Some(&before), "main", drop).0, "failed");
507
        assert_eq!(verdict(&now, Some(&before), "main", Rules { min: None, max_drop: Some(0.5) }).0, "passed");
508
    }
509
510
    #[test]
511
    fn paths_are_taken_relative_to_the_workspace() {
512
        assert_eq!(relative("/src/a/b.rs").as_deref(), Some("a/b.rs"));
513
        assert_eq!(relative("./a/b.rs").as_deref(), Some("a/b.rs"));
514
        assert_eq!(relative("a/b.rs").as_deref(), Some("a/b.rs"));
515
        for bad in ["/etc/passwd", "a/../b", "", "/src/", "a//b", "C:\\x\\y.rs"] {
516
            assert_eq!(relative(bad), None, "{bad}");
517
        }
518
        assert_eq!(percent(1, 3), Some(33.3));
519
        assert_eq!(percent(0, 0), None);
520
    }
521
}