Skip to content

Commit

Permalink
Test added for external avatar url field
Browse files Browse the repository at this point in the history
  • Loading branch information
Artem committed Jul 18, 2013
1 parent da19fdd commit 6641773
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
14 changes: 13 additions & 1 deletion app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,26 @@ def check_external_avatar
extension = File.extname(uri.path)
unless Kandan::Config.options[:external_avatar_formats].include? extension.downcase
errors.add(:avatar_url, "extension is invalid")
return
end

# Check protocol
unless ['http', 'https'].include?(uri.scheme)
errors.add(:avatar_url, "protocol is invalid")
return
end

# Check for file size
Net::HTTP.start(uri.host) do |http|
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https') do |http|
begin
response = http.request_head(uri.to_s)
file_size = response['content-length']

if file_size.nil?
file_size = 0
end

size_in_bounds = Integer(file_size).between?(1, Kandan::Config.options[:external_avatar_max_size])
unless size_in_bounds
errors.add(:avatar_url, "image size is out of bounds (maximum %{max_size} bytes)" % {:max_size => Kandan::Config.options[:external_avatar_max_size]})
Expand Down
40 changes: 40 additions & 0 deletions spec/models/user_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,44 @@
subject { @user.gravatar_hash }
expect(subject).to_not eq(nil)
end

describe "external avatar" do
it "should have no avatar url on creation" do
subject { User.new() }
expect(subject.avatar_url).to be_nil
end

context "check url" do
subject { FactoryGirl.build(:user) }

it "should accept non-empty small image with allowed extension" do
subject.avatar_url = "https://github.global.ssl.fastly.net/images/icons/emoji/+1.png"
expect(subject.save).to be_true
expect(subject).to be_valid
end

it "should not accept extension that is not allowed in config" do
# a 35KB midi sound
subject.avatar_url = "http://saya.pianomidi.org/musica/lfals/a-asturias.mid"
expect(subject.save).to be_false
expect(subject).to_not be_valid
expect(subject.errors).to have_key(:avatar_url)
end

it "should not validate nonexistent url as avatar" do
subject.avatar_url = "unknownProtocol://some-url-that-does-not/realy/exist.png"
expect(subject.save).to be_false
expect(subject).to_not be_valid
expect(subject.errors).to have_key(:avatar_url)
end

it "should not validate big images as avatar" do
# a really big Hubble image of a pair of interacting galaxies
subject.avatar_url = "http://www.spacetelescope.org/static/archives/images/publicationjpg/heic1107a.jpg"
expect(subject.save).to be_false
expect(subject).to_not be_valid
expect(subject.errors).to have_key(:avatar_url)
end
end
end
end

0 comments on commit 6641773

Please sign in to comment.