diff --git a/lib/mutant/parallel/connection.rb b/lib/mutant/parallel/connection.rb index cdf376411..c4666fba3 100644 --- a/lib/mutant/parallel/connection.rb +++ b/lib/mutant/parallel/connection.rb @@ -21,11 +21,11 @@ class Reader attr_reader :log def error - @errors.first + Util.max_one(@errors) end def result - @results.first + Util.max_one(@results) end def initialize(*) @@ -96,7 +96,7 @@ def advance_result end def length - @lengths.first + Util.max_one(@lengths) end def advance_log diff --git a/lib/mutant/util.rb b/lib/mutant/util.rb index 39dbcc80b..8573c0f0f 100644 --- a/lib/mutant/util.rb +++ b/lib/mutant/util.rb @@ -19,5 +19,23 @@ def self.one(array) fail SizeError, "expected size to be exactly 1 but size was #{array.size}" end end + + # Return only element in array if it contains max one member + # + # @param array [Array] + # + # @return [Object] first entry + # @return [nil] if empty + # + # rubocop:disable Lint/EmptyInPattern + def self.max_one(array) + case array + in [] + in [value] + value + else + fail SizeError, "expected size to be max 1 but size was #{array.size}" + end + end end # Util end # Mutant diff --git a/spec/unit/mutant/util_spec.rb b/spec/unit/mutant/util_spec.rb index a5a52a1ad..120cf1a92 100644 --- a/spec/unit/mutant/util_spec.rb +++ b/spec/unit/mutant/util_spec.rb @@ -53,3 +53,55 @@ def apply end end end + +RSpec.describe Mutant::Util, '.max_one' do + let(:item) { instance_double(Object) } + + def apply + described_class.max_one(array) + end + + context 'when array has exactly one element' do + context 'and that element is nil' do + let(:array) { [nil] } + + it 'returns nil' do + expect(apply).to be(nil) + end + end + + context 'and that element is false' do + let(:array) { [false] } + + it 'returns false' do + expect(apply).to be(false) + end + end + + context 'and that element is a regular object' do + let(:array) { [item] } + + it 'returns first element' do + expect(apply).to be(item) + end + end + end + + context 'when array is empty' do + let(:array) { [] } + + it 'returns nil' do + expect(apply).to be(nil) + end + end + + context 'when array has more than one element' do + let(:array) { [1, 2] } + + it 'raises expected error' do + expect { apply } + .to raise_error(described_class::SizeError) + .with_message('expected size to be max 1 but size was 2') + end + end +end