|
2 | 2 | # SPDX-License-Identifier: Apache-2.0 |
3 | 3 | """Tests enforcing code coverage for production code.""" |
4 | 4 |
|
5 | | - |
6 | | -import os |
7 | | -import platform |
8 | | -import re |
9 | | -import shutil |
10 | 5 | import pytest |
11 | 6 |
|
12 | 7 | from framework import utils |
13 | | -import host_tools.cargo_build as host # pylint: disable=import-error |
14 | 8 | from host_tools import proc |
15 | 9 |
|
16 | 10 | # We have different coverages based on the host kernel version. This is |
|
29 | 23 |
|
30 | 24 | PROC_MODEL = proc.proc_type() |
31 | 25 |
|
32 | | -COVERAGE_MAX_DELTA = 0.05 |
33 | | - |
34 | | -CARGO_KCOV_REL_PATH = os.path.join(host.CARGO_BUILD_REL_PATH, "kcov") |
35 | | - |
36 | | -KCOV_COVERAGE_FILE = "index.js" |
37 | | -"""kcov will aggregate coverage data in this file.""" |
| 26 | +# Toolchain target architecture. |
| 27 | +if ("Intel" in PROC_MODEL) or ("AMD" in PROC_MODEL): |
| 28 | + ARCH = "x86_64" |
| 29 | +elif "ARM" in PROC_MODEL: |
| 30 | + ARCH = "aarch64" |
| 31 | +else: |
| 32 | + raise Exception(f"Unsupported processor model ({PROC_MODEL})") |
38 | 33 |
|
39 | | -KCOV_COVERED_LINES_REGEX = r'"covered_lines":"(\d+)"' |
40 | | -"""Regex for extracting number of total covered lines found by kcov.""" |
| 34 | +# Toolchain target. |
| 35 | +# Currently profiling with `aarch64-unknown-linux-musl` is unsupported (see |
| 36 | +# https://github.com/rust-lang/rustup/issues/3095#issuecomment-1280705619) therefore we profile and |
| 37 | +# run coverage with the `gnu` toolchains and run unit tests with the `musl` toolchains. |
| 38 | +TARGET = f"{ARCH}-unknown-linux-gnu" |
41 | 39 |
|
42 | | -KCOV_TOTAL_LINES_REGEX = r'"total_lines" : "(\d+)"' |
43 | | -"""Regex for extracting number of total executable lines found by kcov.""" |
| 40 | +# We allow coverage to have a max difference of `COVERAGE_MAX_DELTA` as percentage before failing |
| 41 | +# the test. |
| 42 | +COVERAGE_MAX_DELTA = 0.05 |
44 | 43 |
|
45 | | -SECCOMPILER_BUILD_DIR = "../build/seccompiler" |
| 44 | +# grcov 0.8.* requires GLIBC >2.27, this is not present in ubuntu 18.04, when we update the docker |
| 45 | +# container with a newer version of ubuntu we can also update this. |
| 46 | +GRCOV_VERSION = "0.7.1" |
46 | 47 |
|
47 | 48 |
|
48 | 49 | @pytest.mark.timeout(400) |
49 | | -def test_coverage(test_fc_session_root_path, test_session_tmp_path, record_property): |
50 | | - """Test line coverage for rust tests is within bounds. |
51 | | -
|
52 | | - The result is extracted from the $KCOV_COVERAGE_FILE file created by kcov |
53 | | - after a coverage run. |
| 50 | +def test_coverage(monkeypatch): |
| 51 | + """Test code coverage |
54 | 52 |
|
55 | 53 | @type: build |
56 | 54 | """ |
57 | | - proc_model = [item for item in COVERAGE_DICT if item in PROC_MODEL] |
58 | | - assert len(proc_model) == 1, "Could not get processor model!" |
59 | | - coverage_target_pct = COVERAGE_DICT[proc_model[0]] |
60 | | - exclude_pattern = ( |
61 | | - "${CARGO_HOME:-$HOME/.cargo/}," |
62 | | - "build/," |
63 | | - "tests/," |
64 | | - "usr/lib/gcc," |
65 | | - "lib/x86_64-linux-gnu/," |
66 | | - "test_utils.rs," |
67 | | - # The following files/directories are auto-generated |
68 | | - "bootparam.rs," |
69 | | - "elf.rs," |
70 | | - "mpspec.rs," |
71 | | - "msr_index.rs," |
72 | | - "bindings.rs," |
73 | | - "_gen" |
74 | | - ) |
75 | | - exclude_region = "'mod tests {'" |
76 | | - target = "{}-unknown-linux-musl".format(platform.machine()) |
77 | | - |
78 | | - cmd = ( |
79 | | - 'CARGO_WRAPPER="kcov" RUSTFLAGS="{}" CARGO_TARGET_DIR={} ' |
80 | | - "cargo kcov --all " |
81 | | - "--target {} --output {} -- " |
82 | | - "--exclude-pattern={} " |
83 | | - "--exclude-region={} --verify" |
84 | | - ).format( |
85 | | - host.get_rustflags(), |
86 | | - os.path.join(test_fc_session_root_path, CARGO_KCOV_REL_PATH), |
87 | | - target, |
88 | | - test_session_tmp_path, |
89 | | - exclude_pattern, |
90 | | - exclude_region, |
91 | | - ) |
92 | | - # We remove the seccompiler custom build directory, created by the |
93 | | - # vmm-level `build.rs`. |
94 | | - # If we don't delete it before and after running the kcov command, we will |
95 | | - # run into linker errors. |
96 | | - shutil.rmtree(SECCOMPILER_BUILD_DIR, ignore_errors=True) |
97 | | - # By default, `cargo kcov` passes `--exclude-pattern=$CARGO_HOME --verify` |
98 | | - # to kcov. To pass others arguments, we need to include the defaults. |
99 | | - utils.run_cmd(cmd) |
100 | | - |
101 | | - shutil.rmtree(SECCOMPILER_BUILD_DIR) |
102 | | - |
103 | | - coverage_file = os.path.join(test_session_tmp_path, KCOV_COVERAGE_FILE) |
104 | | - with open(coverage_file, encoding="utf-8") as cov_output: |
105 | | - contents = cov_output.read() |
106 | | - covered_lines = int(re.findall(KCOV_COVERED_LINES_REGEX, contents)[0]) |
107 | | - total_lines = int(re.findall(KCOV_TOTAL_LINES_REGEX, contents)[0]) |
108 | | - coverage = covered_lines / total_lines * 100 |
109 | | - print("Number of executable lines: {}".format(total_lines)) |
110 | | - print("Number of covered lines: {}".format(covered_lines)) |
111 | | - print("Thus, coverage is: {:.2f}%".format(coverage)) |
112 | | - |
113 | | - coverage_low_msg = ( |
114 | | - "Current code coverage ({:.2f}%) is >{:.2f}% below the target ({}%).".format( |
115 | | - coverage, COVERAGE_MAX_DELTA, coverage_target_pct |
116 | | - ) |
| 55 | + # Get coverage target. |
| 56 | + processor_model = [item for item in COVERAGE_DICT if item in PROC_MODEL] |
| 57 | + assert len(processor_model) == 1, "Could not get processor model!" |
| 58 | + coverage_target = COVERAGE_DICT[processor_model[0]] |
| 59 | + |
| 60 | + # Re-direct to repository root. |
| 61 | + monkeypatch.chdir("..") |
| 62 | + |
| 63 | + # Generate test profiles. |
| 64 | + utils.run_cmd( |
| 65 | + f'\ |
| 66 | + env RUSTFLAGS="-Cinstrument-coverage" \ |
| 67 | + LLVM_PROFILE_FILE="coverage-%p-%m.profraw" \ |
| 68 | + cargo test --all --target={TARGET} -- --test-threads=1 \ |
| 69 | + ' |
117 | 70 | ) |
118 | 71 |
|
119 | | - assert coverage >= coverage_target_pct - COVERAGE_MAX_DELTA, coverage_low_msg |
120 | | - |
121 | | - # Get the name of the variable that needs updating. |
122 | | - namespace = globals() |
123 | | - cov_target_name = [name for name in namespace if namespace[name] is COVERAGE_DICT][ |
124 | | - 0 |
125 | | - ] |
126 | | - |
127 | | - coverage_high_msg = ( |
128 | | - "Current code coverage ({:.2f}%) is >{:.2f}% above the target ({}%).\n" |
129 | | - "Please update the value of {}.".format( |
130 | | - coverage, COVERAGE_MAX_DELTA, coverage_target_pct, cov_target_name |
131 | | - ) |
| 72 | + # Generate coverage report. |
| 73 | + utils.run_cmd( |
| 74 | + f'\ |
| 75 | + cargo install --version {GRCOV_VERSION} grcov \ |
| 76 | + && grcov . \ |
| 77 | + -s . \ |
| 78 | + --binary-path ./build/cargo_target/{TARGET}/debug/ \ |
| 79 | + --excl-start "mod tests" \ |
| 80 | + --ignore "build/*" \ |
| 81 | + -t html \ |
| 82 | + --branch \ |
| 83 | + --ignore-not-existing \ |
| 84 | + -o ./build/cargo_target/{TARGET}/debug/coverage \ |
| 85 | + ' |
132 | 86 | ) |
133 | 87 |
|
134 | | - record_property( |
135 | | - "coverage", f"{coverage}% {coverage_target_pct}% ±{COVERAGE_MAX_DELTA:.2}%" |
| 88 | + # Extract coverage from html report. |
| 89 | + # |
| 90 | + # The line looks like `<abbr title="44724 / 49237">90.83 %</abbr></p>` and is the first |
| 91 | + # occurrence of the `<abbr>` element in the file. |
| 92 | + # |
| 93 | + # When we update grcov to 0.8.* we can update this to pull the coverage from a generated .json |
| 94 | + # file. |
| 95 | + index = open( |
| 96 | + f"./build/cargo_target/{TARGET}/debug/coverage/index.html", encoding="utf-8" |
136 | 97 | ) |
137 | | - assert coverage <= coverage_target_pct + COVERAGE_MAX_DELTA, coverage_high_msg |
| 98 | + index_contents = index.read() |
| 99 | + end = index_contents.find(" %</abbr></p>") |
| 100 | + start = index_contents[:end].rfind(">") |
| 101 | + coverage_str = index_contents[start + 1 : end] |
| 102 | + coverage = float(coverage_str) |
| 103 | + |
| 104 | + # Compare coverage. |
| 105 | + high = coverage_target * (1.0 + COVERAGE_MAX_DELTA) |
| 106 | + low = coverage_target * (1.0 - COVERAGE_MAX_DELTA) |
| 107 | + assert ( |
| 108 | + coverage >= low |
| 109 | + ), f"Current code coverage ({coverage:.2f}%) is more than {COVERAGE_MAX_DELTA:.2f}% below \ |
| 110 | + the target ({coverage_target:.2f}%)" |
| 111 | + assert ( |
| 112 | + coverage <= high |
| 113 | + ), f"Current code coverage ({coverage:.2f}%) is more than {COVERAGE_MAX_DELTA:.2f}% above \ |
| 114 | + the target ({coverage_target:.2f}%)" |
0 commit comments