padded_cell 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7d2b2f1c6d06b6cf4e72a67cfb6d511cc121fad2794d5fffc84bbf323c8431f1
4
- data.tar.gz: '08aacbd7f382259c1eee0b45e3508c7dba4522be0c6d57ba4ca13b496ba70a1b'
3
+ metadata.gz: 65b36985fd4aeb5bce28e8f3598aaedf6a2b426299bba5efe878fb29d73e7076
4
+ data.tar.gz: 621ee3f6059b676e22d5cd556ec175d4726eb0bef36e4a88a64984a021f18530
5
5
  SHA512:
6
- metadata.gz: d473da59b1f2de1ae4cee4d423c8361ffcf42060bd8b4fd264894a82c6d631cdddd8e8ee376716ae0d73db4ea4e3aefbf540fdbd42b20ed996ca024740448aba
7
- data.tar.gz: 4d7a2de1bad5aaf24df760011df2a9728193586640bb7f7f14a9dcd66d38750082995692736bdfc0a4ccb951fb174384d600ac723414a39e0c479d98203f2515
6
+ metadata.gz: 7aeb2739c07b7fd60a28c316c44aef13647eb96f51b77ff712d0ccbabb9690ed0d909811767f7071ae22abab6ccd8ddccd7e75c2b174d1493fd8cbeb2c1cbbc1
7
+ data.tar.gz: 6b4f4eabc20224e2f12dd6bb5824a21473b222ecf304297c2bd1d38fd873b8f10818c144742a4f875b4085d0fe7442663f85cbd629090d493575368422d8cdbb
data/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.0](https://github.com/seuros/padded_cell/compare/v0.4.0...v0.5.0) (2026-11-27)
4
+
5
+
6
+ ### Features
7
+
8
+ * honor Minitest 6.1's abstract_test_case! ([387ae4f](https://github.com/seuros/padded_cell/commit/387ae4f63d5816caed779fc6dcf667942683c4af))
9
+ * refuse to run after minitest/autorun installed its at_exit ([bd3e81d](https://github.com/seuros/padded_cell/commit/bd3e81d40940fe791f086601e69d1c0f4a7c57e9))
10
+
11
+ ## 0.4.0 (2026-11-08)
12
+
13
+ - `PADDED_CELL_ASYLUM`: retries failures from the environment. N retries,
14
+ or `true`/`yes`/`on` for the default 2; `0`, `false`, `no` and `off` leave
15
+ it off. `--asylum` still wins.
16
+ - `--coverage-map PATH` (or `PADDED_CELL_COVERAGE_MAP`): the lines each test
17
+ ran, as JSON lines (`{"id":…,"file":…,"line":…,"covers":{path => lines}}`),
18
+ for CI that reruns only the tests a diff touches. Turns on
19
+ `--coverage=lines,methods` when coverage is off; never changes the summed
20
+ report. Free with `--isolation test`; with `--isolation worker`, two
21
+ coverage copies per test.
22
+
3
23
  ## 0.3.0 (2026-11-08)
4
24
 
5
25
  - `--budget SECONDS`: a deadline for the whole run, loading included. Once
data/Cargo.lock CHANGED
@@ -226,7 +226,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
226
226
 
227
227
  [[package]]
228
228
  name = "padded_cell"
229
- version = "0.3.0"
229
+ version = "0.5.0"
230
230
  dependencies = [
231
231
  "ruby-prism",
232
232
  "supervisor-machines",
@@ -236,7 +236,7 @@ dependencies = [
236
236
 
237
237
  [[package]]
238
238
  name = "padded_cell_native"
239
- version = "0.3.0"
239
+ version = "0.5.0"
240
240
  dependencies = [
241
241
  "deadline-machines",
242
242
  "magnus",
data/README.md CHANGED
@@ -42,7 +42,7 @@ down. The other 44 never noticed.
42
42
 
43
43
  ## Installation
44
44
 
45
- Requires CRuby 4.0 or newer and Minitest 6, on Linux, macOS or FreeBSD.
45
+ Requires CRuby 4.0 or newer and Minitest 6.1+, on Linux, macOS or FreeBSD.
46
46
  padded_cell is built on `fork`: Windows, JRuby and TruffleRuby are not
47
47
  supported.
48
48
 
@@ -72,6 +72,7 @@ $ padded_cell --timeout 30 # kill and fail anything running 30s
72
72
  $ padded_cell --budget 600 # the whole run gets 10 minutes; what's left out fails it
73
73
  $ padded_cell --fail-fast
74
74
  $ padded_cell --asylum # retry failures; report the flaky ones (see below)
75
+ $ PADDED_CELL_ASYLUM=2 padded_cell # same, from a CI runner's env
75
76
  $ padded_cell --list # what would run, without loading anything
76
77
  $ padded_cell --shard 2/4 # CI: the second quarter of the classes
77
78
  $ padded_cell --junit tmp/junit.xml --json tmp/results.jsonl
@@ -103,6 +104,12 @@ errors, 3 when only coverage is below a threshold, 130 when interrupted.
103
104
  Loaded tests are the source of truth: inherited, `define_method` and other
104
105
  dynamic tests run even though static discovery cannot see them.
105
106
 
107
+ Minitest 6.1's `abstract_test_case!` is honored: a base class that calls it
108
+ runs its tests only in its subclasses, wherever it is defined (support files
109
+ included). padded_cell reads the call from the class body, so it has to be a
110
+ plain `abstract_test_case!` statement there, not one made from a block, a
111
+ method, an included module or for another class.
112
+
106
113
  ### Isolation
107
114
 
108
115
  `--isolation test` forks a cell per test. Forking a preloaded process is
@@ -271,6 +278,38 @@ The merge refuses files that differ between shards or from the checkout,
271
278
  and checks thresholds when every shard of the run is there. Lines that run
272
279
  while the suite loads count once per shard.
273
280
 
281
+ ### Coverage map
282
+
283
+ Which lines each test ran, so CI can rerun only the tests touching a diff:
284
+
285
+ ```console
286
+ $ padded_cell --coverage-map tmp/coverage_map.jsonl
287
+ $ PADDED_CELL_COVERAGE_MAP=tmp/coverage_map.jsonl padded_cell # same; the flag wins
288
+ ```
289
+
290
+ One JSON object per test, in id order, written at the end of the run:
291
+
292
+ ```json
293
+ {"id":"SignTest#test_zero","file":"test/calc_test.rb","line":28,"covers":{"lib/calc.rb":[[7,8],10,13]}}
294
+ ```
295
+
296
+ `covers` holds the files the coverage report shows (filters apply, `test/`
297
+ stays out), each with its line numbers ascending, `[first, last]` for a run
298
+ of consecutive ones. Lines a test runs while loading a file count for it.
299
+
300
+ Ruby's line coverage never sees a call to `def add(a, b) = a + b`: with
301
+ `methods` measured, every method a test called adds its def line. Without
302
+ `--coverage`, the map turns on `lines,methods`. With it, the map adds no
303
+ criterion, so the report is byte for byte the same as without the map:
304
+ include `methods`, or one-liners go unmapped.
305
+
306
+ First attempts only, like the report. A test whose cell or worker died is
307
+ left out: it was not measured, so a selector should run it anyway.
308
+
309
+ A cell's measure is already its test's: free under `--isolation test`. With
310
+ `--isolation worker`, Ruby copies the coverage of every loaded file twice per
311
+ test (about 24 ms with 800 files loaded, more in a big Rails app).
312
+
274
313
  ### Cost
275
314
 
276
315
  Measuring is opt-in: Ruby's instrumentation slows tests down. On a Rails
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "padded_cell"
3
- version = "0.3.0"
3
+ version = "0.5.0"
4
4
  description = "Static Minitest discovery and test scheduling for the padded_cell gem"
5
5
  publish = false
6
6
  edition.workspace = true
@@ -51,15 +51,24 @@ impl Source {
51
51
  /// The 1-based line and the 0-based byte column of `offset`.
52
52
  #[must_use]
53
53
  pub fn position(&self, offset: usize) -> (u32, u32) {
54
- let line = self.ends.partition_point(|&end| end <= offset);
54
+ let line = self.line_index(offset);
55
55
  let number = |value: usize| u32::try_from(value).unwrap_or(u32::MAX);
56
- (number(line.strict_add(1)), number(offset.strict_sub(self.line_start(offset))))
56
+ (number(line.strict_add(1)), number(offset.strict_sub(self.start_of(line))))
57
57
  }
58
58
 
59
59
  /// Where the line holding `offset` starts.
60
60
  #[must_use]
61
61
  pub fn line_start(&self, offset: usize) -> usize {
62
- let line = self.ends.partition_point(|&end| end <= offset);
62
+ self.start_of(self.line_index(offset))
63
+ }
64
+
65
+ /// The 0-based line holding `offset`.
66
+ fn line_index(&self, offset: usize) -> usize {
67
+ self.ends.partition_point(|&end| end <= offset)
68
+ }
69
+
70
+ /// Where the 0-based `line` starts.
71
+ fn start_of(&self, line: usize) -> usize {
63
72
  line.checked_sub(1).map_or(0, |previous| self.ends[previous])
64
73
  }
65
74
 
@@ -107,3 +107,49 @@ fn discover_files_reports_the_first_unreadable_file() {
107
107
  fn ids_of(discovery: &Discovery) -> Vec<String> {
108
108
  discovery.iter().map(|test| test.id()).collect()
109
109
  }
110
+
111
+ #[test]
112
+ fn abstract_test_cases_run_none_of_their_own_tests() {
113
+ let source = concat!(
114
+ "class ShapeTest < Minitest::Test\n",
115
+ " abstract_test_case!\n",
116
+ " def test_area; end\n",
117
+ "end\n",
118
+ "module Shapes\n",
119
+ " class SquareTest < ShapeTest\n def test_side; end\n end\n",
120
+ " class BaseTest < ActiveSupport::TestCase\n",
121
+ " test 'shared' do; end\n",
122
+ " abstract_test_case!(self)\n",
123
+ " end\n",
124
+ "end\n",
125
+ );
126
+ let found = discover(source.as_bytes());
127
+ assert_eq!(ids_of(&found), ["Shapes::SquareTest#test_side"]);
128
+ assert_eq!(found.abstract_classes(), ["ShapeTest", "Shapes::BaseTest"]);
129
+ }
130
+
131
+ #[test]
132
+ fn only_a_bare_statement_of_the_class_body_declares_it_abstract() {
133
+ let bodies = [
134
+ "def self.x = abstract_test_case!",
135
+ "included { abstract_test_case! }",
136
+ "abstract_test_case!(Other)",
137
+ "self.abstract_test_case!",
138
+ "class Inner\n abstract_test_case!\n end",
139
+ ];
140
+ for body in bodies {
141
+ let source = format!("class ATest < Minitest::Test\n {body}\n def test_a; end\nend");
142
+ let found = discover(source.as_bytes());
143
+ assert_eq!(ids_of(&found), ["ATest#test_a"], "source: {source:?}");
144
+ assert_eq!(found.abstract_classes(), [] as [&str; 0], "source: {source:?}");
145
+ }
146
+ }
147
+
148
+ #[test]
149
+ fn abstract_classes_need_a_known_name_and_a_test_superclass() {
150
+ let source = concat!(
151
+ "class Helper < Object\n abstract_test_case!\nend\n",
152
+ "class foo::DynamicTest < Minitest::Test\n abstract_test_case!\nend\n",
153
+ );
154
+ assert_eq!(discover(source.as_bytes()).abstract_classes(), [] as [&str; 0]);
155
+ }
@@ -3,14 +3,17 @@
3
3
  //! A test class is a class whose superclass constant ends in `Test` or
4
4
  //! `TestCase` (`Minitest::Test`, `ActiveSupport::TestCase`, an app's own
5
5
  //! `BaseTest`...). Its tests are `def test_*` methods and Rails'
6
- //! `test "name"` declarations. Nothing is evaluated.
6
+ //! `test "name"` declarations. A class that calls `abstract_test_case!`
7
+ //! in its body (Minitest 6.1+) runs none of its own tests: it is listed in
8
+ //! [`Discovery::abstract_classes`] instead. Nothing is evaluated.
7
9
 
8
10
  use std::iter::FusedIterator;
9
11
  use std::path::Path;
10
12
  use std::slice;
11
13
 
12
14
  use ruby_prism::{
13
- CallNode, ClassNode, DefNode, Location, ModuleNode, Node, SingletonClassNode, Visit,
15
+ CallNode, ClassNode, DefNode, Location, ModuleNode, Node, SingletonClassNode, StatementsNode,
16
+ Visit,
14
17
  };
15
18
 
16
19
  use crate::FileError;
@@ -25,6 +28,7 @@ mod tests;
25
28
  pub struct Discovery {
26
29
  classes: Vec<String>,
27
30
  tests: Vec<Entry>,
31
+ abstract_classes: Vec<String>,
28
32
  }
29
33
 
30
34
  #[derive(Debug, Clone, PartialEq, Eq)]
@@ -65,6 +69,13 @@ impl Discovery {
65
69
  &self.classes
66
70
  }
67
71
 
72
+ /// Names of the test classes declared `abstract_test_case!`, in order of
73
+ /// appearance. Their own tests are not in [`Discovery::iter`].
74
+ #[must_use]
75
+ pub fn abstract_classes(&self) -> &[String] {
76
+ &self.abstract_classes
77
+ }
78
+
68
79
  /// Number of tests.
69
80
  #[must_use]
70
81
  pub const fn len(&self) -> usize {
@@ -226,17 +237,28 @@ impl<'pr> Visitor<'pr> {
226
237
  scope_start: 0,
227
238
  dynamic: false,
228
239
  test_class: TestClass::Outside,
229
- discovery: Discovery { classes: Vec::new(), tests: Vec::new() },
240
+ discovery: Discovery {
241
+ classes: Vec::new(),
242
+ tests: Vec::new(),
243
+ abstract_classes: Vec::new(),
244
+ },
230
245
  }
231
246
  }
232
247
 
233
- fn within(&mut self, path: &Node<'pr>, test: bool, visit: impl FnOnce(&mut Self)) {
248
+ fn within(&mut self, path: &Node<'pr>, kind: Kind, visit: impl FnOnce(&mut Self)) {
234
249
  let (depth, scope_start, dynamic, test_class) =
235
250
  (self.scope.len(), self.scope_start, self.dynamic, self.test_class);
236
251
  let constant = self.push_constant(path).is_some();
237
252
  self.dynamic |= !constant;
238
- self.test_class =
239
- if test && !self.dynamic { TestClass::Pending } else { TestClass::Outside };
253
+ self.test_class = match kind {
254
+ Kind::Test if !self.dynamic => TestClass::Pending,
255
+ Kind::Abstract if !self.dynamic => {
256
+ let name = self.class_name();
257
+ self.discovery.abstract_classes.push(name);
258
+ TestClass::Outside
259
+ }
260
+ _ => TestClass::Outside,
261
+ };
240
262
  visit(self);
241
263
  self.scope.truncate(depth);
242
264
  (self.scope_start, self.dynamic, self.test_class) = (scope_start, dynamic, test_class);
@@ -255,8 +277,15 @@ impl<'pr> Visitor<'pr> {
255
277
  Some(())
256
278
  }
257
279
 
258
- /// Stores the current namespace as a class name, joined once.
280
+ /// Stores the current namespace as a class name.
259
281
  fn add_class(&mut self) -> usize {
282
+ let class = self.class_name();
283
+ self.discovery.classes.push(class);
284
+ self.discovery.classes.len() - 1
285
+ }
286
+
287
+ /// The current namespace, joined once.
288
+ fn class_name(&self) -> String {
260
289
  let names = &self.scope[self.scope_start..];
261
290
  let length =
262
291
  names.iter().map(|name| name.len()).sum::<usize>() + 2 * names.len().saturating_sub(1);
@@ -267,8 +296,7 @@ impl<'pr> Visitor<'pr> {
267
296
  }
268
297
  class.push_str(name);
269
298
  }
270
- self.discovery.classes.push(class);
271
- self.discovery.classes.len() - 1
299
+ class
272
300
  }
273
301
 
274
302
  const fn in_test_class(&self) -> bool {
@@ -297,14 +325,24 @@ impl<'pr> Visitor<'pr> {
297
325
 
298
326
  impl<'pr> Visit<'pr> for Visitor<'pr> {
299
327
  fn visit_module_node(&mut self, node: &ModuleNode<'pr>) {
300
- self.within(&node.constant_path(), false, |visitor| {
328
+ self.within(&node.constant_path(), Kind::Plain, |visitor| {
301
329
  ruby_prism::visit_module_node(visitor, node);
302
330
  });
303
331
  }
304
332
 
305
333
  fn visit_class_node(&mut self, node: &ClassNode<'pr>) {
306
- let test = node.superclass().is_some_and(|superclass| test_superclass(&superclass));
307
- self.within(&node.constant_path(), test, |visitor| {
334
+ let kind = if !node.superclass().is_some_and(|superclass| test_superclass(&superclass)) {
335
+ Kind::Plain
336
+ } else if node
337
+ .body()
338
+ .and_then(|body| body.as_statements_node())
339
+ .is_some_and(|body| abstract_body(&body))
340
+ {
341
+ Kind::Abstract
342
+ } else {
343
+ Kind::Test
344
+ };
345
+ self.within(&node.constant_path(), kind, |visitor| {
308
346
  ruby_prism::visit_class_node(visitor, node);
309
347
  });
310
348
  }
@@ -340,6 +378,36 @@ impl<'pr> Visit<'pr> for Visitor<'pr> {
340
378
  }
341
379
  }
342
380
 
381
+ /// What a namespace being entered is.
382
+ #[derive(Debug, Clone, Copy)]
383
+ enum Kind {
384
+ /// A module, or a class that is not a test class.
385
+ Plain,
386
+ /// A test class.
387
+ Test,
388
+ /// A test class declared `abstract_test_case!`: its tests run only in
389
+ /// its subclasses.
390
+ Abstract,
391
+ }
392
+
393
+ /// Whether a class body calls `abstract_test_case!` (or
394
+ /// `abstract_test_case!(self)`) as one of its own statements. A call inside
395
+ /// a block or a method may run for another class, or never.
396
+ fn abstract_body(body: &StatementsNode<'_>) -> bool {
397
+ body.body().iter().any(|statement| {
398
+ statement.as_call_node().is_some_and(|call| {
399
+ call.receiver().is_none()
400
+ && call.block().is_none()
401
+ && call.name().as_slice() == b"abstract_test_case!"
402
+ && call.arguments().is_none_or(|arguments| {
403
+ let arguments = arguments.arguments();
404
+ arguments.len() == 1
405
+ && arguments.iter().all(|argument| argument.as_self_node().is_some())
406
+ })
407
+ })
408
+ })
409
+ }
410
+
343
411
  /// Whether a superclass is a constant path ending in `Test` or `TestCase`.
344
412
  fn test_superclass(node: &Node<'_>) -> bool {
345
413
  constant_tail(node).is_some_and(|name| name.ends_with("Test") || name.ends_with("TestCase"))
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "padded_cell_native"
3
- version = "0.3.0"
3
+ version = "0.5.0"
4
4
  description = "Ruby bindings for the padded_cell crate"
5
5
  publish = false
6
6
  edition.workspace = true
@@ -86,13 +86,17 @@ fn discover(ruby: &Ruby, source: RString) -> Result<RArray, Error> {
86
86
 
87
87
  /// Reads and parses on scoped threads: none is left running when Ruby forks
88
88
  /// next.
89
- fn discover_files(ruby: &Ruby, paths: RArray) -> Result<RArray, Error> {
90
- let found = with_bytes(&strings(paths)?, |paths| {
89
+ fn discoveries(ruby: &Ruby, paths: RArray) -> Result<Vec<Discovery>, Error> {
90
+ with_bytes(&strings(paths)?, |paths| {
91
91
  let paths: Vec<&Path> =
92
92
  paths.iter().map(|path| Path::new(OsStr::from_bytes(path))).collect();
93
93
  padded_cell::discover_files(&paths)
94
94
  })
95
- .map_err(|error| file_error(ruby, &error))?;
95
+ .map_err(|error| file_error(ruby, &error))
96
+ }
97
+
98
+ fn discover_files(ruby: &Ruby, paths: RArray) -> Result<RArray, Error> {
99
+ let found = discoveries(ruby, paths)?;
96
100
  let files = ruby.ary_new_capa(found.len());
97
101
  for discovery in &found {
98
102
  files.push(rows(ruby, discovery)?)?;
@@ -100,6 +104,13 @@ fn discover_files(ruby: &Ruby, paths: RArray) -> Result<RArray, Error> {
100
104
  Ok(files)
101
105
  }
102
106
 
107
+ /// Names of the classes declared `abstract_test_case!` in the files, in file
108
+ /// order: the runner drops their own tests after loading.
109
+ fn abstract_classes(ruby: &Ruby, paths: RArray) -> Result<Vec<String>, Error> {
110
+ let found = discoveries(ruby, paths)?;
111
+ Ok(found.iter().flat_map(|discovery| discovery.abstract_classes().iter().cloned()).collect())
112
+ }
113
+
103
114
  fn plan(
104
115
  classes: RArray,
105
116
  durations: Vec<f64>,
@@ -118,6 +129,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
118
129
  module.define_module_function("version", function!(version, 0))?;
119
130
  module.define_module_function("discover", function!(discover, 1))?;
120
131
  module.define_module_function("discover_files", function!(discover_files, 1))?;
132
+ module.define_module_function("abstract_classes", function!(abstract_classes, 1))?;
121
133
  module.define_module_function("plan", function!(plan, 5))?;
122
134
  module.define_module_function("chart_report", function!(chart::chart_report, 3))?;
123
135
  limits::define(ruby, module)?;
@@ -24,7 +24,7 @@ module PaddedCell
24
24
  pid = fork_cell(klass, name, seed, reader, writer, close, probe)
25
25
  writer.close
26
26
  delta, result = collect(pid, reader, klass, name, started, deadline) { limits.message(deadline) }
27
- delta ? probe.absorb(delta) : probe&.lost
27
+ delta ? probe.absorb(delta, result) : probe&.lost
28
28
  result
29
29
  ensure
30
30
  reader&.close
@@ -13,11 +13,14 @@ module PaddedCell
13
13
  attr_reader :criteria
14
14
 
15
15
  # criteria: what Ruby's Coverage measures, :lines always among them
16
- def initialize(criteria)
16
+ # map: each test's lines go on its result too (--coverage-map)
17
+ def initialize(criteria, map: false)
17
18
  @criteria = criteria
19
+ @map = map
18
20
  @root = File.realpath(Dir.pwd)
19
21
  @roots = [Dir.pwd, @root].uniq.map { "#{it}/" }
20
22
  @kept = {}
23
+ @names = {}
21
24
  @lost = 0
22
25
  @known = Set.new
23
26
  end
@@ -39,7 +42,16 @@ module PaddedCell
39
42
  # For a worker, right after its fork.
40
43
  def probe
41
44
  Probe.new(file: File.join(@frames, "#{Process.pid}.cov"), known: @known, keep: method(:keep?),
42
- methods: @criteria.include?(:methods), interval: Chart.config.interval)
45
+ methods: @criteria.include?(:methods), interval: Chart.config.interval, map: @map)
46
+ end
47
+
48
+ # A measured file's name in the report, or nil for a file the report
49
+ # leaves out (filtered, outside the root, deleted).
50
+ def project_file(path)
51
+ @names.fetch(path) do
52
+ name = relative(path)
53
+ @names[path] = (name if name && !Chart.config.skipped?(path, name))
54
+ end
43
55
  end
44
56
 
45
57
  # A worker died: what it measured since its last flush is gone.
@@ -85,19 +97,25 @@ module PaddedCell
85
97
  end
86
98
  end
87
99
 
88
- # Keys by real path relative to the root: a file required through a
89
- # symlink and through its real path is one file. A file deleted during
90
- # the run is not reported.
100
+ # Keys by real path relative to the root.
91
101
  def normalize(total)
92
102
  total.each_with_object({}) do |(path, entry), files|
93
- relative = File.realpath(path).delete_prefix("#{@root}/")
94
- next if relative.start_with?('/')
103
+ relative = relative(path)
104
+ next unless relative
95
105
 
96
106
  files[relative] ? Delta.merge!(files, { relative => entry }) : files[relative] = entry
97
- rescue SystemCallError
98
- next
99
107
  end
100
108
  end
109
+
110
+ # By real path: a file required through a symlink and through its real
111
+ # path is one file. nil outside the root, or for a file deleted during
112
+ # the run.
113
+ def relative(path)
114
+ relative = File.realpath(path).delete_prefix("#{@root}/")
115
+ relative unless relative.start_with?('/')
116
+ rescue SystemCallError
117
+ nil
118
+ end
101
119
  end
102
120
  end
103
121
  end
@@ -65,6 +65,12 @@ module PaddedCell
65
65
  end
66
66
  alias filter skip
67
67
 
68
+ # Whether a filter leaves the file out (path absolute, name relative).
69
+ def skipped?(path, name)
70
+ file = SourceFile.new(path, name)
71
+ @filters.any? { it.call(file) }
72
+ end
73
+
68
74
  # Removes every filter, the defaults included.
69
75
  def clear_filters = @filters.clear
70
76
 
@@ -51,6 +51,19 @@ module PaddedCell
51
51
  total
52
52
  end
53
53
 
54
+ # {path => [line number, ...]}: the lines that ran, ascending, by file.
55
+ # A call to `def add(a, b) = a + b` runs no line Ruby sees: methods,
56
+ # when measured, add the first line of every method that ran.
57
+ def ran(delta)
58
+ delta.each_with_object({}) do |(path, entry), ran|
59
+ lines = entry[:lines]
60
+ indices = lines.is_a?(Hash) ? lines.keys : lines.each_index.select { lines[it]&.positive? }
61
+ numbers = indices.map { it + 1 }
62
+ entry[:methods]&.each { |(_, first), (_, hits)| numbers << first if hits.positive? }
63
+ ran[path] = numbers.uniq.sort unless numbers.empty?
64
+ end
65
+ end
66
+
54
67
  # Coverage's arrays are frozen.
55
68
  def dense(data)
56
69
  {
@@ -16,15 +16,22 @@ module PaddedCell
16
16
  # A flush copies the coverage of every file Ruby loaded, gems included: a
17
17
  # few milliseconds in a small app, a few hundred in a big Rails one. The
18
18
  # interval stretches to keep flushes under 1% of a worker's time.
19
+ #
20
+ # With the map on (--coverage-map), each test's result also carries the
21
+ # lines it ran, in its metadata under :covers. A cell's delta is already
22
+ # its test's; a worker running tests itself clears Coverage around each
23
+ # one, two more copies per test. What it clears goes into its measure, so
24
+ # the sum does not change.
19
25
  class Probe
20
26
  INTERVAL = 10.0
21
27
  BUDGET = 100
22
28
 
23
- def initialize(file:, known:, keep:, methods:, interval: INTERVAL)
29
+ def initialize(file:, known:, keep:, methods:, interval: INTERVAL, map: false)
24
30
  @file = file
25
31
  @known = known
26
32
  @keep = keep
27
33
  @methods = methods
34
+ @map = map
28
35
  @interval = interval
29
36
  @wait = interval
30
37
  @pending = {}
@@ -40,8 +47,22 @@ module PaddedCell
40
47
  # The delta of a cell, at its end.
41
48
  def capture = Delta.capture(::Coverage.peek_result, @known, @keep)
42
49
 
43
- # A cell's delta, in its worker.
44
- def absorb(delta) = Delta.merge!(@pending, delta)
50
+ # A cell's delta, in its worker; with the map on, result gets the lines
51
+ # its test ran.
52
+ def absorb(delta, result = nil)
53
+ result.metadata[:covers] = Delta.ran(delta) if @map && result
54
+ Delta.merge!(@pending, delta)
55
+ end
56
+
57
+ # Runs a test in the worker (isolation :worker), which yields its result.
58
+ def measure
59
+ return yield unless @map
60
+
61
+ absorb(clear)
62
+ result = yield
63
+ absorb(clear, result)
64
+ result
65
+ end
45
66
 
46
67
  # A cell that died before reporting.
47
68
  def lost = @lost += 1
@@ -53,7 +74,7 @@ module PaddedCell
53
74
 
54
75
  def flush
55
76
  started = Minitest.clock_time
56
- delta = Delta.merge!(Delta.capture(::Coverage.result(stop: false, clear: true), @known, @keep), @pending)
77
+ delta = Delta.merge!(clear, @pending)
57
78
  frame = Marshal.dump({ delta:, lost: @lost })
58
79
  File.open(@file, 'ab') { it.write([frame.bytesize].pack('N') + frame) }
59
80
  # Dense entries brought their structure to the runner: from now on,
@@ -65,6 +86,11 @@ module PaddedCell
65
86
  # 0: after every test, whatever it costs.
66
87
  @wait = @interval.zero? ? 0 : [@interval, (@flushed - started) * BUDGET].max
67
88
  end
89
+
90
+ private
91
+
92
+ # What ran since the last clear, taken out of Coverage.
93
+ def clear = Delta.capture(::Coverage.result(stop: false, clear: true), @known, @keep)
68
94
  end
69
95
  end
70
96
  end
@@ -19,7 +19,7 @@ module PaddedCell
19
19
  loaded = loaded_features
20
20
  never, @unmeasured = tracked(files).partition { !loaded.include?(File.join(root, it)) }
21
21
  @rows = (files.map { |name, entry| row(name, entry) } + stubs(never))
22
- .reject { |path, name| skipped?(path, name) }
22
+ .reject { |path, name| @config.skipped?(path, name) }
23
23
  .sort_by { it[1] }
24
24
  end
25
25
 
@@ -72,11 +72,6 @@ module PaddedCell
72
72
  end
73
73
  end
74
74
 
75
- def skipped?(path, name)
76
- file = SourceFile.new(path, name)
77
- @config.filters.any? { it.call(file) }
78
- end
79
-
80
75
  # Required files, also under the root's real path.
81
76
  def loaded_features
82
77
  pwd = "#{Dir.pwd}/"
@@ -22,7 +22,8 @@ module PaddedCell
22
22
  # Exit status: 0 passed, 1 failed, 2 usage or load error, 3 coverage below
23
23
  # a minimum, 130 interrupted.
24
24
  def start(argv, io: $stdout)
25
- options = { io:, coverage: coverage_criteria(ENV.fetch('PADDED_CELL_COVERAGE', nil)), **report_paths }
25
+ options = { io:, coverage: coverage_criteria(ENV.fetch('PADDED_CELL_COVERAGE', nil)), **report_paths,
26
+ **asylum_from_env }
26
27
  parser(options).parse!(argv)
27
28
  return merge(options) if options[:coverage_merge]
28
29
 
@@ -34,12 +35,22 @@ module PaddedCell
34
35
  end
35
36
 
36
37
  # Report paths a CI runner can set without touching the command line;
37
- # --json and --junit still win.
38
+ # --json, --junit and --coverage-map still win.
38
39
  def report_paths
39
- { json: ENV.fetch('PADDED_CELL_JSON', nil), junit: ENV.fetch('PADDED_CELL_JUNIT', nil) }
40
+ { json: ENV.fetch('PADDED_CELL_JSON', nil), junit: ENV.fetch('PADDED_CELL_JUNIT', nil),
41
+ coverage_map: ENV.fetch('PADDED_CELL_COVERAGE_MAP', nil) }
40
42
  .reject { |_, path| path.nil? || path.empty? }
41
43
  end
42
44
 
45
+ # PADDED_CELL_ASYLUM=N, or 1/true for the default 2 retries; --asylum wins.
46
+ def asylum_from_env
47
+ value = ENV.fetch('PADDED_CELL_ASYLUM', '').strip
48
+ return {} if value.empty? || %w[0 false no off].include?(value.downcase)
49
+ return { asylum: 2 } if %w[true yes on].include?(value.downcase)
50
+
51
+ { asylum: positive(Integer(value, 10)) }
52
+ end
53
+
43
54
  def parser(options)
44
55
  OptionParser.new do |opts|
45
56
  opts.banner = BANNER
@@ -98,6 +109,10 @@ module PaddedCell
98
109
  opts.on('--coverage-dir DIR', 'Write coverage reports to DIR (default: coverage, or the test helper\'s)') do
99
110
  options[:coverage_dir] = it
100
111
  end
112
+ opts.on('--coverage-map PATH', 'Write the lines each test ran to PATH, as JSON lines (measures ' \
113
+ 'lines,methods if coverage is off; or $PADDED_CELL_COVERAGE_MAP)') do
114
+ options[:coverage_map] = it
115
+ end
101
116
  opts.on('--coverage-merge DIR,DIR', Array, 'Merge the coverage of shards (their --coverage-dir) ' \
102
117
  'into one report; runs no test') do
103
118
  options[:coverage_merge] = it
@@ -20,5 +20,8 @@ module PaddedCell
20
20
  def source(source, file: '(source)') = refs(PaddedCellNative.discover(source), file)
21
21
 
22
22
  def refs(rows, file) = rows.map { TestRef.new(file, *it) }
23
+
24
+ # Names of the classes declared `abstract_test_case!` in files.
25
+ def abstract_classes(files) = PaddedCellNative.abstract_classes(files)
23
26
  end
24
27
  end
@@ -16,6 +16,12 @@ module PaddedCell
16
16
  module_function
17
17
 
18
18
  def call(files, seed:)
19
+ # An at_exit cannot be taken back: refuse rather than run twice.
20
+ if Minitest.installed_at_exit?
21
+ raise LoadFailure, 'minitest/autorun was required before padded_cell loaded the suite: its at_exit ' \
22
+ 'would run every test again, unisolated. Drop it from RUBYOPT, or require ' \
23
+ "'minitest' instead where it runs before padded_cell"
24
+ end
19
25
  Minitest.singleton_class.prepend(NoAutorun)
20
26
  Minitest.seed = seed
21
27
  # What `rake test` and `rails test` put on the load path.
@@ -34,12 +40,24 @@ module PaddedCell
34
40
 
35
41
  # [klass, method_name] for every loaded test, the way Minitest finds them.
36
42
  def tests
37
- Minitest::Runnable.runnables.flat_map do |klass|
43
+ runnables = Minitest::Runnable.runnables
44
+ abstract = abstract_classes(runnables)
45
+ runnables.flat_map do |klass|
46
+ next [] if abstract.include?(klass.name)
47
+
38
48
  klass.runnable_methods.map { [klass, it] }
39
49
  rescue NotImplementedError
40
50
  []
41
51
  end
42
52
  end
53
+
54
+ # Minitest's abstract_test_case! guards the class-level run, which cells
55
+ # never call: the declaration is read from the files the classes were
56
+ # defined in instead, test helpers and support files included.
57
+ def abstract_classes(runnables)
58
+ files = runnables.filter_map { (name = it.name) && Object.const_source_location(name)&.first }
59
+ Discovery.abstract_classes(files.uniq.select { File.file?(it) }).to_set
60
+ end
43
61
  end
44
62
 
45
63
  # Which loaded tests run: Minitest's --include/--exclude, plus file:line.
@@ -103,6 +103,52 @@ module PaddedCell
103
103
  def escape(text) = text.to_s.scrub.gsub(INVALID, '').gsub(/[&<>"']/, ESCAPES)
104
104
  end
105
105
 
106
+ # --coverage-map: per test, the lines of the project it ran, one JSON
107
+ # object per line, in id order:
108
+ #
109
+ # {"id":"SignTest#test_zero","file":"test/calc_test.rb","line":28,
110
+ # "covers":{"lib/calc.rb":[[7,8],10,13]}}
111
+ #
112
+ # Line numbers ascend; [first, last] stands for a run of consecutive
113
+ # ones. Files are those the coverage report would show. A test that was
114
+ # not measured (its cell or worker died) is left out.
115
+ class CoverageMap < FileReporter
116
+ # coverage: the run's Chart::Accumulator
117
+ def initialize(path, coverage:)
118
+ super(path)
119
+ @coverage = coverage
120
+ end
121
+
122
+ # A first attempt, as it arrives: what it ran comes off its metadata.
123
+ def record(result)
124
+ covers = result.metadata? && result.metadata.delete(:covers)
125
+ @results << entry(result, covers) if covers
126
+ end
127
+
128
+ private
129
+
130
+ def render(entries) = entries.sort_by { it[:id] }.map { "#{JSON.generate(it)}\n" }.join
131
+
132
+ def entry(result, covers)
133
+ file, line = file_and_line(result)
134
+ { id: "#{result.klass}##{result.name}", file:, line:, covers: files(covers) }
135
+ end
136
+
137
+ # Two paths can name one file (a symlink): their lines are merged.
138
+ def files(covers)
139
+ files = Hash.new { |hash, name| hash[name] = [] }
140
+ covers.each do |path, lines|
141
+ name = @coverage.project_file(path)
142
+ files[name].concat(lines) if name
143
+ end
144
+ files.sort.to_h { |name, lines| [name, ranges(lines.uniq.sort)] }
145
+ end
146
+
147
+ def ranges(lines)
148
+ lines.slice_when { |previous, line| line != previous + 1 }.map { it.size == 1 ? it[0] : [it[0], it[-1]] }
149
+ end
150
+ end
151
+
106
152
  # One JSON object per test, one per line.
107
153
  class JSONLines < FileReporter
108
154
  private
@@ -88,12 +88,13 @@ module PaddedCell
88
88
  end
89
89
 
90
90
  # Marshal.dump, after replacing failures that cannot cross a pipe (an
91
- # exception holding a Proc, an IO...) with plain copies.
91
+ # exception holding a Proc, an IO...) with plain copies. Of the metadata,
92
+ # only the coverage map's plain data survives.
92
93
  def dump(result)
93
94
  Marshal.dump(result)
94
95
  rescue TypeError, ArgumentError
95
96
  result.failures = result.failures.map { portable(it) }
96
- result.metadata = {} if result.metadata?
97
+ result.metadata = result.metadata.slice(:covers) if result.metadata?
97
98
  Marshal.dump(result)
98
99
  end
99
100
 
@@ -23,7 +23,7 @@ module PaddedCell
23
23
  paths: [], jobs: Etc.nprocessors, seed: nil, include: nil, exclude: nil, shard: [0, 1],
24
24
  isolation: nil, timeout: nil, budget: nil, asylum: nil, fail_fast: false, verbose: false, show_skips: false,
25
25
  list: false, junit: nil, json: nil, timings: 'tmp/padded_cell/timings.tsv', coverage: nil,
26
- coverage_dir: nil, io: $stdout
26
+ coverage_dir: nil, coverage_map: nil, io: $stdout
27
27
  }.freeze
28
28
 
29
29
  attr_reader :options
@@ -31,6 +31,9 @@ module PaddedCell
31
31
  def initialize(**options)
32
32
  @options = DEFAULTS.merge(options)
33
33
  @options[:seed] ||= (ENV['SEED'] || Random.new_seed).to_i % 0xFFFF
34
+ # The map is made of lines, and of methods: a call to a one-line
35
+ # method runs no line Ruby sees.
36
+ @options[:coverage] ||= %i[lines methods] if @options[:coverage_map]
34
37
  end
35
38
 
36
39
  # Exit status: 0 when everything passed, 1 otherwise, 3 when only
@@ -62,7 +65,7 @@ module PaddedCell
62
65
  # Before the suite loads: nothing loaded earlier is measured.
63
66
  def start_coverage
64
67
  require_relative 'chart'
65
- Chart::Accumulator.new(options[:coverage]).start
68
+ Chart::Accumulator.new(options[:coverage], map: !options[:coverage_map].nil?).start
66
69
  end
67
70
 
68
71
  # Two tools cannot share Ruby's Coverage.
@@ -97,10 +100,16 @@ module PaddedCell
97
100
  nothing_ran = batches.empty?
98
101
  reporter = build_reporter
99
102
  reporter.start
103
+ # First attempts only, as with the coverage it is made of.
104
+ map = Reporters::CoverageMap.new(options[:coverage_map], coverage: @coverage) if options[:coverage_map]
100
105
  retried = []
101
106
  @coverage&.snapshot
102
- status = dispatch(tests, batches, reporter, retried) { |index, result| timings[ids[index]] = result.time }
107
+ status = dispatch(tests, batches, reporter, retried) do |index, result|
108
+ timings[ids[index]] = result.time
109
+ map&.record(result)
110
+ end
103
111
  reporter.report
112
+ map&.report
104
113
  report_asylum(retried)
105
114
  covered = @coverage ? report_coverage(status, reporter) : true
106
115
  Timings.save(options[:timings], timings)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PaddedCell
4
- VERSION = '0.3.0'
4
+ VERSION = '0.5.0'
5
5
  end
@@ -55,6 +55,8 @@ module PaddedCell
55
55
  Results.crashed(klass, name, "after_fork hook failed: #{setup_error.class}: #{setup_error.message}")
56
56
  elsif @isolation == :test
57
57
  Cell.run(klass, name, seed: @seed, limits: @limits, close: [socket], probe: @probe)
58
+ elsif @probe
59
+ @probe.measure { Cell.execute(klass, name) }
58
60
  else
59
61
  Cell.execute(klass, name)
60
62
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: padded_cell
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - "~>"
17
17
  - !ruby/object:Gem::Version
18
- version: '6.0'
18
+ version: '6.1'
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - "~>"
24
24
  - !ruby/object:Gem::Version
25
- version: '6.0'
25
+ version: '6.1'
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: rb_sys
28
28
  requirement: !ruby/object:Gem::Requirement