test_budget 0.0.0 → 0.2.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.
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "yaml"
5
+
6
+ module TestBudget
7
+ class Budget < Data.define(:path, :timings_path, :suite, :per_test_case, :allowlist)
8
+ DEFAULT_EXPIRATION_DAYS = 60
9
+
10
+ Suite = Data.define(:max_duration)
11
+ PerTestCase = Data.define(:default, :types)
12
+
13
+ def self.estimate(...) = Estimate.new(...).generate
14
+
15
+ def self.load(path)
16
+ config = YAML.safe_load_file(path) || {}
17
+ suite_config = config["suite"] || {}
18
+ per_test_case_config = config["per_test_case"] || {}
19
+ types = per_test_case_config.except("default").transform_keys(&:to_sym)
20
+
21
+ budget = new(
22
+ path: path,
23
+ timings_path: config["timings_path"],
24
+ suite: Suite.new(max_duration: suite_config["max_duration"]),
25
+ per_test_case: PerTestCase.new(
26
+ default: per_test_case_config["default"],
27
+ types: types
28
+ ),
29
+ allowlist: Allowlist.new(config["allowlist"] || [])
30
+ )
31
+
32
+ raise TestBudget::Error, "timings_path is required in budget file" unless budget.timings_path
33
+ raise TestBudget::Error, "No limits configured. Set suite.max_duration or per_test_case limits" unless budget.limits_set?
34
+
35
+ budget
36
+ rescue Errno::ENOENT
37
+ raise TestBudget::Error, "Budget file not found: #{path}"
38
+ end
39
+
40
+ def exempt?(test_case)
41
+ entry = allowlist.allowed?(test_case.key)
42
+
43
+ entry && !entry.expired?
44
+ end
45
+
46
+ def limit_for(test_case)
47
+ per_test_case.types[test_case.type] || per_test_case.default
48
+ end
49
+
50
+ def add_to_allowlist(locator, reason:)
51
+ test_run = Parser::Rspec.parse(timings_path)
52
+ test_case = TestCase.find_by_location!(test_run.test_cases, locator)
53
+
54
+ allowlist.add(test_case.key, reason: reason, expires_on: Date.today + DEFAULT_EXPIRATION_DAYS).tap { save }
55
+ end
56
+
57
+ def prune_allowlist
58
+ test_run = Parser::Rspec.parse(timings_path)
59
+ removed = allowlist.prune(test_run, self)
60
+ save if removed.any?
61
+ removed
62
+ end
63
+
64
+ def inflate_by(percent)
65
+ factor = 1 + percent
66
+
67
+ with(
68
+ suite: Suite.new(max_duration: suite.max_duration&.*(factor)),
69
+ per_test_case: PerTestCase.new(
70
+ default: per_test_case.default&.*(factor),
71
+ types: per_test_case.types.transform_values { |v| v * factor }
72
+ )
73
+ )
74
+ end
75
+
76
+ def limits_set?
77
+ suite.max_duration || per_test_case.default || per_test_case.types.any?
78
+ end
79
+
80
+ def save
81
+ File.write(path, YAML.dump(to_h))
82
+ end
83
+
84
+ private
85
+
86
+ def to_h
87
+ deep_compact_blank(
88
+ "timings_path" => timings_path,
89
+ "suite" => {"max_duration" => suite.max_duration},
90
+ "per_test_case" => {
91
+ "default" => per_test_case.default,
92
+ **per_test_case.types.transform_keys(&:to_s)
93
+ },
94
+ "allowlist" => allowlist.to_a.map(&:to_h)
95
+ )
96
+ end
97
+
98
+ def deep_compact_blank(hash)
99
+ hash.each_with_object({}) do |(key, value), result|
100
+ value = deep_compact_blank(value) if value.is_a?(Hash)
101
+ next if value.nil?
102
+ next if value.respond_to?(:empty?) && value.empty?
103
+ result[key] = value
104
+ end
105
+ end
106
+ end
107
+ end
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "argument_parser"
5
+
6
+ module TestBudget
7
+ class CLI
8
+ def call(argv)
9
+ args = argv.dup
10
+
11
+ return print_help if args.empty? || (args & %w[--help -h]).any?
12
+ return print_version if (args & %w[--version -v]).any?
13
+
14
+ parsed = command_parser.parse!(args)
15
+
16
+ case parsed[:command]
17
+ in "audit" then run_audit(args)
18
+ in "allowlist" then run_allowlist(args)
19
+ in "prune" then run_prune(args)
20
+ in "init" | "estimate" then run_init(args)
21
+ in "breakdown" then run_breakdown(args)
22
+ in "diff" then run_diff(args)
23
+ in "help" then print_help
24
+ end
25
+ rescue ArgumentParser::ParseError, TestBudget::Error, OptionParser::MissingArgument, OptionParser::InvalidArgument => e
26
+ warn e.message
27
+ 1
28
+ end
29
+
30
+ private
31
+
32
+ def command_parser
33
+ ArgumentParser.build do
34
+ required :command, pattern: ["audit", "allowlist", "prune", "init", "estimate", "breakdown", "diff", "help"]
35
+ end
36
+ end
37
+
38
+ def print_help
39
+ puts help_text
40
+ 0
41
+ end
42
+
43
+ def print_version
44
+ puts "test_budget #{TestBudget::VERSION}"
45
+ 0
46
+ end
47
+
48
+ def help_text
49
+ <<~HELP
50
+ Usage: test_budget <command> [options]
51
+
52
+ Commands:
53
+ audit Check test results against budget
54
+ allowlist Exclude a test from budget checks
55
+ prune Remove obsolete allowlist entries
56
+ init Generate starter .test_budget.yml config
57
+ estimate Alias for init
58
+ breakdown Show time distribution across test types
59
+ diff Compare two test runs
60
+ help Show this help message
61
+
62
+ Options:
63
+ -h, --help Show this help message
64
+ -v, --version Show version
65
+ HELP
66
+ end
67
+
68
+ def run_audit(args)
69
+ budget_path = DEFAULT_BUDGET_PATH
70
+ tolerant = false
71
+
72
+ OptionParser.new do |opts|
73
+ opts.banner = "Usage: test_budget audit [options]"
74
+ opts.on("--budget PATH", "Path to budget file") { |path| budget_path = path }
75
+ opts.on("--tolerant", "Apply 10% tolerance to limits") { tolerant = true }
76
+ end.parse!(args)
77
+
78
+ result = Audit.new(budget_path: budget_path, tolerant: tolerant).perform
79
+
80
+ result.passed? ? 0 : 1
81
+ end
82
+
83
+ def run_allowlist(args)
84
+ budget_path = DEFAULT_BUDGET_PATH
85
+ reason = nil
86
+
87
+ OptionParser.new do |opts|
88
+ opts.banner = "Usage: test_budget allowlist FILE:LINE --reason REASON [options]"
89
+ opts.on("--budget PATH", "Path to budget file") { |path| budget_path = path }
90
+ opts.on("--reason REASON", "Reason for allowlisting") { |r| reason = r }
91
+ end.parse!(args)
92
+
93
+ locator = args.shift
94
+ raise Error, "--reason is required for allowlist" unless reason
95
+ raise Error, "locator (e.g., spec/file_spec.rb:10) is required" unless locator
96
+
97
+ entry = Budget.load(budget_path).add_to_allowlist(locator, reason: reason)
98
+ puts "Allowlisted: #{entry.test_case_key}"
99
+
100
+ 0
101
+ end
102
+
103
+ def run_prune(args)
104
+ budget_path = DEFAULT_BUDGET_PATH
105
+
106
+ OptionParser.new do |opts|
107
+ opts.banner = "Usage: test_budget prune [options]"
108
+ opts.on("--budget PATH", "Path to budget file") { |path| budget_path = path }
109
+ end.parse!(args)
110
+
111
+ removed = Budget.load(budget_path).prune_allowlist
112
+
113
+ if removed.any?
114
+ puts "#{removed.size} obsolete allowlist #{Inflector.pluralize("entry", removed.size)} removed"
115
+ else
116
+ puts "No obsolete allowlist entries found"
117
+ end
118
+
119
+ 0
120
+ end
121
+
122
+ def run_breakdown(args)
123
+ sort = :duration
124
+
125
+ OptionParser.new do |opts|
126
+ opts.banner = "Usage: test_budget breakdown [timings_file] [options]"
127
+ opts.on("--sort FIELD", TestRun::Breakdown::SORT_OPTIONS, "Sort by: duration (default), count, type") { |s| sort = s }
128
+ end.parse!(args)
129
+
130
+ timings_path = args.shift || DEFAULT_TIMINGS_PATH
131
+ test_run = Parser::Rspec.parse(timings_path)
132
+ puts TestRun::Breakdown.new(test_run: test_run, sort: sort)
133
+ 0
134
+ end
135
+
136
+ def run_diff(args)
137
+ parsed_args = ArgumentParser.build {
138
+ required :before
139
+ required :after
140
+ }.parse!(args)
141
+
142
+ before = Parser::Rspec.parse(parsed_args[:before])
143
+ after = Parser::Rspec.parse(parsed_args[:after])
144
+
145
+ print TestRun::Diff.new(before, after)
146
+ 0
147
+ end
148
+
149
+ def run_init(args)
150
+ force = false
151
+
152
+ OptionParser.new do |opts|
153
+ opts.banner = "Usage: test_budget init [timings_file] [options]"
154
+ opts.on("--force", "Overwrite existing config") { force = true }
155
+ end.parse!(args)
156
+ timings_path = args.shift
157
+
158
+ Budget.estimate(timings_path: timings_path, force: force)
159
+
160
+ 0
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ module Format
5
+ extend self
6
+
7
+ def duration(seconds)
8
+ if seconds >= 60
9
+ minutes = (seconds / 60).to_i
10
+ secs = (seconds % 60).round
11
+ "#{minutes}m #{secs}s"
12
+ else
13
+ "#{seconds.round}s"
14
+ end
15
+ end
16
+
17
+ def signed_duration(seconds)
18
+ formatted = duration(seconds.abs)
19
+
20
+ if seconds > 0
21
+ "+#{formatted}"
22
+ elsif seconds < 0
23
+ "-#{formatted}"
24
+ else
25
+ "0s"
26
+ end
27
+ end
28
+
29
+ def signed_int(n)
30
+ n.zero? ? "0" : "%+d" % n
31
+ end
32
+
33
+ def percent(value)
34
+ return "new" if value.nil?
35
+
36
+ "%+.1f%%" % value
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ module Inflector
5
+ IRREGULARS = {
6
+ "entry" => "entries",
7
+ "policy" => "policies",
8
+ "factory" => "factories",
9
+ "query" => "queries"
10
+ }.freeze
11
+
12
+ def self.pluralize(word, count)
13
+ (count == 1) ? word : (IRREGULARS[word] || "#{word}s")
14
+ end
15
+
16
+ def self.singularize(word)
17
+ IRREGULARS.key(word) || word.chomp("s")
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module TestBudget
6
+ module Parser
7
+ module Rspec
8
+ extend self
9
+
10
+ def parse(pattern)
11
+ paths = Dir.glob(pattern)
12
+ raise TestBudget::Error, "No timing files found matching: #{pattern}" if paths.empty?
13
+
14
+ groups = paths.flat_map { |path| parse_file(path) }
15
+ TestRun.new(
16
+ test_cases: groups.flatten,
17
+ wall_time: groups.map { |g| g.sum(&:duration) }.max || 0
18
+ )
19
+ end
20
+
21
+ private
22
+
23
+ def parse_file(path)
24
+ read_json_objects(path).map do |data|
25
+ data["examples"].map do |example|
26
+ TestCase.new(
27
+ file: example["file_path"],
28
+ name: example["full_description"],
29
+ duration: example["run_time"],
30
+ status: example["status"],
31
+ line_number: example["line_number"]
32
+ )
33
+ end
34
+ end
35
+ end
36
+
37
+ def read_json_objects(path)
38
+ content = File.read(path)
39
+ [JSON.parse(content)]
40
+ rescue JSON::ParserError
41
+ parse_concatenated_json(content, path)
42
+ end
43
+
44
+ CONCATENATED_JSON_BOUNDARY = /(?<=\})(?=\{)/
45
+
46
+ def parse_concatenated_json(content, path)
47
+ content.split(CONCATENATED_JSON_BOUNDARY).map { |chunk| JSON.parse(chunk) }
48
+ rescue JSON::ParserError => e
49
+ raise TestBudget::Error, "Invalid JSON in #{path}: #{e.message}"
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ class Reporter
5
+ def initialize(budget_path:)
6
+ @budget_path = budget_path
7
+ end
8
+
9
+ def report(result)
10
+ violations = result.violations
11
+
12
+ if violations.empty?
13
+ puts "Test budget: all clear"
14
+ else
15
+ puts "Test budget: #{violations.size} violation(s) found\n\n"
16
+
17
+ violations.each_with_index do |violation, index|
18
+ puts " #{index + 1}) #{violation.message}"
19
+
20
+ if (locator = violation.locator)
21
+ budget_flag = (@budget_path == ".test_budget.yml") ? "" : " --budget #{@budget_path}"
22
+ puts " To allowlist, run:"
23
+ puts " bundle exec test_budget allowlist #{locator}#{budget_flag} --reason \"<reason>\""
24
+ end
25
+ end
26
+ end
27
+
28
+ result.warnings.each do |warning|
29
+ warn "Warning: #{warning.message}\n\n"
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ module Statistics
5
+ def self.p99(values, tolerance: 0) = percentile(0.99, values, tolerance: tolerance)
6
+
7
+ private_class_method def self.percentile(rank, values, tolerance: 0)
8
+ sorted = values.sort
9
+ n = sorted.size
10
+ return apply_tolerance(sorted[0], tolerance) if n == 1
11
+
12
+ index = rank * (n - 1)
13
+ lower = sorted[index.floor]
14
+ upper = sorted[index.ceil]
15
+ result = lower + (upper - lower) * (index - index.floor)
16
+
17
+ apply_tolerance(result, tolerance)
18
+ end
19
+
20
+ private_class_method def self.apply_tolerance(value, tolerance)
21
+ ceil_to_half(value * (1 + tolerance))
22
+ end
23
+
24
+ private_class_method def self.ceil_to_half(value)
25
+ (value * 2).ceil / 2.0
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ class Table
5
+ def initialize(columns)
6
+ @columns = columns
7
+ end
8
+
9
+ def render(rows, footer:)
10
+ all_rows = [headers, *rows, footer]
11
+ widths = resolve_widths(all_rows)
12
+
13
+ header = format_row(headers, widths)
14
+ body = rows.map { |cells| format_row(cells, widths) }
15
+
16
+ [
17
+ horizontal_line("┌", "┬", "┐", widths),
18
+ header,
19
+ horizontal_line("├", "┼", "┤", widths),
20
+ *body,
21
+ horizontal_line("├", "┼", "┤", widths),
22
+ format_row(footer, widths),
23
+ horizontal_line("└", "┴", "┘", widths)
24
+ ].join("\n") + "\n"
25
+ end
26
+
27
+ private
28
+
29
+ def headers
30
+ @columns.map(&:first)
31
+ end
32
+
33
+ def resolve_widths(all_rows)
34
+ @columns.each_with_index.map { |_, i|
35
+ all_rows.map { |row| row[i].to_s.length }.max
36
+ }
37
+ end
38
+
39
+ def format_row(cells, widths)
40
+ parts = @columns.zip(cells, widths).map { |(_, alignment), cell, width|
41
+ case alignment
42
+ when :right then cell.to_s.rjust(width)
43
+ else cell.to_s.ljust(width)
44
+ end
45
+ }
46
+
47
+ "│ #{parts.join(" │ ")} │"
48
+ end
49
+
50
+ def horizontal_line(left, mid, right, widths)
51
+ segments = widths.map { |w| "─" * (w + 2) }
52
+ left + segments.join(mid) + right
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ class TestCase < Data.define(:file, :name, :duration, :status, :line_number)
5
+ def initialize(file:, name:, duration:, status:, line_number:)
6
+ super(file: file.delete_prefix("./"), name: name, duration: duration, status: status, line_number: line_number)
7
+ end
8
+
9
+ def type
10
+ dir = file[%r{^spec/([^/]+)/}, 1]
11
+ return :default unless dir
12
+
13
+ Inflector.singularize(dir).to_sym
14
+ end
15
+
16
+ def key
17
+ "#{file} -- #{name}"
18
+ end
19
+
20
+ def violation_for(budget)
21
+ return unless violates?(budget)
22
+
23
+ Violation.new(test_case: self, duration: duration, limit: budget.limit_for(self), kind: :per_test_case)
24
+ end
25
+
26
+ def violates?(budget) = over?(budget) && !exempted?(budget)
27
+
28
+ def over?(budget) = !within?(budget)
29
+
30
+ def within?(budget)
31
+ limit = budget.limit_for(self)
32
+ return true if limit.nil?
33
+
34
+ duration <= limit
35
+ end
36
+
37
+ def exempted?(budget)
38
+ budget.exempt?(self)
39
+ end
40
+
41
+ def self.find_by_location!(test_cases, locator)
42
+ file, line = parse_locator(locator)
43
+ match = test_cases.find { |tc| tc.file == file && tc.line_number == line }
44
+
45
+ raise Error, "No test case found at #{locator}" unless match
46
+
47
+ match
48
+ end
49
+
50
+ def self.parse_locator(locator)
51
+ m = locator.match(/\A(.+):(\d+)\z/)
52
+ raise Error, "Line number required in locator (e.g., spec/file_spec.rb:10)" unless m
53
+
54
+ [m[1], m[2].to_i]
55
+ end
56
+
57
+ private_class_method :parse_locator
58
+ end
59
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ class TestRun
5
+ class Breakdown < Data.define(:test_run, :sort)
6
+ SORT_OPTIONS = %i[duration count type].freeze
7
+ TABLE = Table.new([
8
+ ["Test Type", :left],
9
+ ["Count", :right],
10
+ ["%", :right],
11
+ ["Duration", :right],
12
+ ["%", :right]
13
+ ])
14
+
15
+ def initialize(test_run:, sort: :duration) = super
16
+
17
+ def to_s
18
+ groups = test_run.groups
19
+ return "No test cases found.\n" if groups.empty?
20
+
21
+ rows = sort_groups(groups).map { |g|
22
+ [
23
+ g.type,
24
+ g.count.to_s,
25
+ "%.1f%%" % g.percent_count,
26
+ Format.duration(g.duration),
27
+ "%.1f%%" % g.percent_duration
28
+ ]
29
+ }
30
+
31
+ TABLE.render(
32
+ rows,
33
+ footer: ["Total", test_run.size.to_s, "", Format.duration(test_run.total_time), ""]
34
+ )
35
+ end
36
+
37
+ private
38
+
39
+ def sort_groups(groups)
40
+ case sort
41
+ when :count then groups.sort_by { |g| [-g.count, -g.duration] }
42
+ when :type then groups.sort_by { |g| g.type.to_s }
43
+ else groups.sort_by { |g| -g.duration }
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ class TestRun
5
+ Delta = Data.define(:label, :before, :after) do
6
+ def count = after.count - before.count
7
+ def duration = after.duration - before.duration
8
+
9
+ def new? = before.count == 0
10
+ def removed? = after.count == 0
11
+ def zero? = count == 0 && duration == 0
12
+
13
+ def percent_count
14
+ return if new?
15
+ return -100.0 if removed?
16
+
17
+ count * 100.0 / before.count
18
+ end
19
+
20
+ def percent_duration
21
+ return if new?
22
+ return -100.0 if removed?
23
+
24
+ duration * 100.0 / before.duration
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TestBudget
4
+ class TestRun
5
+ class Diff < Data.define(:before, :after)
6
+ TABLE = Table.new([
7
+ ["Test Type", :left],
8
+ ["Δ Count", :right],
9
+ ["%", :right],
10
+ ["Δ Duration", :right],
11
+ ["%", :right]
12
+ ])
13
+
14
+ def to_s
15
+ rows = delta_rows
16
+ return "" if rows.empty?
17
+
18
+ TABLE.render(
19
+ rows.map { |r| format_row(r) },
20
+ footer: format_row(total)
21
+ )
22
+ end
23
+
24
+ private
25
+
26
+ NULL_GROUP = Group.new(type: :null, count: 0, duration: 0.0, test_run: nil)
27
+
28
+ def delta_rows
29
+ full_outer_join(before.groups, after.groups, by: :type, default: NULL_GROUP)
30
+ .map { |type, b, a| Delta.new(label: type, before: b, after: a) }
31
+ .reject(&:zero?)
32
+ .sort_by { |delta| [-delta.duration.abs, -delta.count.abs] }
33
+ end
34
+
35
+ def total = Delta.new(label: "Total", before: before, after: after)
36
+
37
+ def format_row(row) = [
38
+ row.label,
39
+ Format.signed_int(row.count),
40
+ Format.percent(row.percent_count),
41
+ Format.signed_duration(row.duration),
42
+ Format.percent(row.percent_duration)
43
+ ]
44
+
45
+ def full_outer_join(left, right, by:, default:)
46
+ left_index = left.to_h { |item| [item.public_send(by), item] }
47
+ right_index = right.to_h { |item| [item.public_send(by), item] }
48
+
49
+ (left_index.keys | right_index.keys).map do |key|
50
+ [key, left_index.fetch(key, default), right_index.fetch(key, default)]
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end