Skip to content

Commit

Permalink
Improve SSHKit::Host comparison
Browse files Browse the repository at this point in the history
 * #equal? should test for object identity, not whether the contents
   are equal, as per the Ruby documentation.
 * #eql? and #== should check the contents directly instead of comparing
   the hash. This prevents false positives.
  • Loading branch information
FooBarWidget committed Dec 27, 2014
1 parent 08a213b commit f2b4474
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
13 changes: 11 additions & 2 deletions lib/sshkit/host.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ module SSHKit
UnparsableHostStringError = Class.new(SSHKit::StandardError)

class Host
DEFAULT_SSH_PORT = 22

attr_accessor :password, :hostname, :port, :user, :ssh_options

Expand Down Expand Up @@ -60,10 +61,12 @@ def username
end

def eql?(other_host)
other_host.hash == hash
other_host &&
user == other_host.user &&
hostname == other_host.hostname &&
port_with_default == other_host.send(:port_with_default)
end
alias :== :eql?
alias :equal? :eql?

def to_s
hostname
Expand All @@ -84,6 +87,12 @@ def properties
@properties ||= OpenStruct.new
end

private

def port_with_default
port || DEFAULT_SSH_PORT
end

end

# @private
Expand Down
18 changes: 17 additions & 1 deletion test/unit/test_host.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,23 @@ def test_assert_hosts_hash_equally
def test_assert_hosts_compare_equal
assert Host.new('example.com') == Host.new('example.com')
assert Host.new('example.com').eql? Host.new('example.com')
assert Host.new('example.com').equal? Host.new('example.com')

assert Host.new('example.com:22') == Host.new('example.com')
assert Host.new('example.com:22').eql? Host.new('example.com')

assert Host.new('example.com:22') != Host.new('example.com:23')
assert !Host.new('example.com:22').eql?(Host.new('example.com:23'))

assert Host.new('foo@example.com') == Host.new('foo@example.com')
assert Host.new('foo@example.com').eql? Host.new('foo@example.com')

assert Host.new('foo@example.com') != Host.new('bar@example.com')
assert !Host.new('foo@example.com').eql?(Host.new('bar@example.com'))

a = Host.new('example.com')
b = Host.new('example.com')
assert a.equal? a
assert !a.equal?(b)
end

def test_arbitrary_host_properties
Expand Down

0 comments on commit f2b4474

Please sign in to comment.