Skip to content

Commit f2b4474

Browse files
committed
Improve SSHKit::Host comparison
* #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.
1 parent 08a213b commit f2b4474

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

lib/sshkit/host.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ module SSHKit
55
UnparsableHostStringError = Class.new(SSHKit::StandardError)
66

77
class Host
8+
DEFAULT_SSH_PORT = 22
89

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

@@ -60,10 +61,12 @@ def username
6061
end
6162

6263
def eql?(other_host)
63-
other_host.hash == hash
64+
other_host &&
65+
user == other_host.user &&
66+
hostname == other_host.hostname &&
67+
port_with_default == other_host.send(:port_with_default)
6468
end
6569
alias :== :eql?
66-
alias :equal? :eql?
6770

6871
def to_s
6972
hostname
@@ -84,6 +87,12 @@ def properties
8487
@properties ||= OpenStruct.new
8588
end
8689

90+
private
91+
92+
def port_with_default
93+
port || DEFAULT_SSH_PORT
94+
end
95+
8796
end
8897

8998
# @private

test/unit/test_host.rb

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,23 @@ def test_assert_hosts_hash_equally
5858
def test_assert_hosts_compare_equal
5959
assert Host.new('example.com') == Host.new('example.com')
6060
assert Host.new('example.com').eql? Host.new('example.com')
61-
assert Host.new('example.com').equal? Host.new('example.com')
61+
62+
assert Host.new('example.com:22') == Host.new('example.com')
63+
assert Host.new('example.com:22').eql? Host.new('example.com')
64+
65+
assert Host.new('example.com:22') != Host.new('example.com:23')
66+
assert !Host.new('example.com:22').eql?(Host.new('example.com:23'))
67+
68+
assert Host.new('[email protected]') == Host.new('[email protected]')
69+
assert Host.new('[email protected]').eql? Host.new('[email protected]')
70+
71+
assert Host.new('[email protected]') != Host.new('[email protected]')
72+
assert !Host.new('[email protected]').eql?(Host.new('[email protected]'))
73+
74+
a = Host.new('example.com')
75+
b = Host.new('example.com')
76+
assert a.equal? a
77+
assert !a.equal?(b)
6278
end
6379

6480
def test_arbitrary_host_properties

0 commit comments

Comments
 (0)