INSTRUCTION
stringlengths 202
35.5k
| RESPONSE
stringlengths 75
161k
|
---|---|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class TagFollowingService
def initialize(user=nil)
@user = user
end
def create(name)
name_normalized = ActsAsTaggableOn::Tag.normalize(name)
raise ArgumentError, "Name field null or empty" if name_normalized.blank?
tag = ActsAsTaggableOn::Tag.find_or_create_by(name: name_normalized)
raise DuplicateTag if @user.tag_followings.exists?(tag_id: tag.id)
tag_following = @user.tag_followings.new(tag_id: tag.id)
raise "Can't process tag entity" unless tag_following.save
tag
end
def find(name)
name_normalized = ActsAsTaggableOn::Tag.normalize(name)
ActsAsTaggableOn::Tag.find_or_create_by(name: name_normalized)
end
def destroy(id)
tag_following = @user.tag_followings.find_by!(tag_id: id)
tag_following.destroy
end
def destroy_by_name(name)
name_normalized = ActsAsTaggableOn::Tag.normalize(name)
followed_tag = @user.followed_tags.find_by!(name: name_normalized)
destroy(followed_tag.id)
end
def index
@user.followed_tags
end
class DuplicateTag < RuntimeError; end
end
``` | # frozen_string_literal: true
describe TagFollowingService do
before do
add_tag("tag1", alice)
add_tag("tag2", alice)
end
describe "#create" do
it "Creates new tag with valid name" do
name = SecureRandom.uuid
expect(alice.followed_tags.find_by(name: name)).to be_nil
tag_data = tag_following_service(alice).create(name)
expect(alice.followed_tags.find_by(name: name).name).to eq(name)
expect(tag_data["name"]).to eq(name)
expect(tag_data["id"]).to be_truthy
expect(tag_data["taggings_count"]).to eq(0)
end
it "Throws error with empty tag" do
expect { tag_following_service(alice).create(nil) }.to raise_error(ArgumentError)
expect { tag_following_service(alice).create("") }.to raise_error(ArgumentError)
expect { tag_following_service(alice).create("#") }.to raise_error(ArgumentError)
expect { tag_following_service(alice).create(" ") }.to raise_error(ArgumentError)
end
it "throws an error when trying to follow an already followed tag" do
name = SecureRandom.uuid
tag_following_service.create(name)
expect {
tag_following_service.create(name)
}.to raise_error TagFollowingService::DuplicateTag
end
end
describe "#destroy" do
it "Deletes tag with valid name" do
name = SecureRandom.uuid
add_tag(name, alice)
expect(alice.followed_tags.find_by(name: name).name).to eq(name)
expect(tag_following_service(alice).destroy_by_name(name)).to be_truthy
expect(alice.followed_tags.find_by(name: name)).to be_nil
end
it "Deletes tag with id" do
name = SecureRandom.uuid
new_tag = add_tag(name, alice)
expect(alice.followed_tags.find_by(name: name).name).to eq(name)
expect(tag_following_service(alice).destroy(new_tag.tag_id)).to be_truthy
expect(alice.followed_tags.find_by(name: name)).to be_nil
end
it "Does nothing with tag that isn't already followed" do
original_length = alice.followed_tags.length
expect {
tag_following_service(alice).destroy_by_name(SecureRandom.uuid)
}.to raise_error ActiveRecord::RecordNotFound
expect {
tag_following_service(alice).destroy(-1)
}.to raise_error ActiveRecord::RecordNotFound
expect(alice.followed_tags.length).to eq(original_length)
end
it "Does nothing with empty tag name" do
original_length = alice.followed_tags.length
expect {
tag_following_service(alice).destroy_by_name("")
}.to raise_error ActiveRecord::RecordNotFound
expect(alice.followed_tags.length).to eq(original_length)
end
end
describe "#index" do
it "Returns user's list of tags" do
tags = tag_following_service(alice).index
expect(tags.length).to eq(alice.followed_tags.length)
end
end
private
def tag_following_service(user=alice)
TagFollowingService.new(user)
end
def add_tag(name, user)
tag = ActsAsTaggableOn::Tag.find_or_create_by(name: name)
tag_following = user.tag_followings.new(tag_id: tag.id)
tag_following.save
tag_following
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class AspectsMembershipService
def initialize(user=nil)
@user = user
end
def create(aspect_id, person_id)
person = Person.find(person_id)
aspect = @user.aspects.where(id: aspect_id).first
raise ActiveRecord::RecordNotFound unless person.present? && aspect.present?
contact = @user.share_with(person, aspect)
raise I18n.t("aspects.add_to_aspect.failure") if contact.blank?
AspectMembership.where(contact_id: contact.id, aspect_id: aspect.id).first
end
def destroy_by_ids(aspect_id, contact_id)
aspect = @user.aspects.where(id: aspect_id).first
contact = @user.contacts.where(person_id: contact_id).first
destroy(aspect, contact)
end
def destroy_by_membership_id(membership_id)
aspect = @user.aspects.joins(:aspect_memberships).where(aspect_memberships: {id: membership_id}).first
contact = @user.contacts.joins(:aspect_memberships).where(aspect_memberships: {id: membership_id}).first
destroy(aspect, contact)
end
def contacts_in_aspect(aspect_id)
order = [Arel.sql("contact_id IS NOT NULL DESC"), "profiles.first_name ASC", "profiles.last_name ASC",
"profiles.diaspora_handle ASC"]
@user.aspects.find(aspect_id) # to provide better error code if aspect isn't correct
contacts = @user.contacts.arel_table
aspect_memberships = AspectMembership.arel_table
@user.contacts.joins(
contacts.join(aspect_memberships).on(
aspect_memberships[:aspect_id].eq(aspect_id).and(
aspect_memberships[:contact_id].eq(contacts[:id])
)
).join_sources
).includes(person: :profile).order(order)
end
def all_contacts
order = ["profiles.first_name ASC", "profiles.last_name ASC",
"profiles.diaspora_handle ASC"]
@user.contacts.includes(person: :profile).order(order)
end
private
def destroy(aspect, contact)
raise ActiveRecord::RecordNotFound unless aspect.present? && contact.present?
raise Diaspora::NotMine unless @user.mine?(aspect) && @user.mine?(contact)
membership = contact.aspect_memberships.where(aspect_id: aspect.id).first
raise ActiveRecord::RecordNotFound if membership.blank?
success = membership.destroy
{success: success, membership: membership}
end
end
``` | # frozen_string_literal: true
describe AspectsMembershipService do
before do
@alice_aspect1 = alice.aspects.first
@alice_aspect2 = alice.aspects.create(name: "another aspect")
@bob_aspect1 = bob.aspects.first
end
describe "#create" do
context "with valid IDs" do
it "succeeds" do
membership = aspects_membership_service.create(@alice_aspect2.id, bob.person.id)
expect(membership[:aspect_id]).to eq(@alice_aspect2.id)
expect(@alice_aspect2.contacts.find_by(person_id: bob.person.id)).not_to be_nil
end
it "fails if already in aspect" do
aspects_membership_service.create(@alice_aspect2.id, bob.person.id)
expect {
aspects_membership_service.create(@alice_aspect2.id, bob.person.id)
}.to raise_error ActiveRecord::RecordNotUnique
end
end
context "with invalid IDs" do
it "fails with invalid User ID" do
expect {
aspects_membership_service.create(@alice_aspect2.id, -1)
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails with invalid Aspect ID" do
expect {
aspects_membership_service.create(-1, bob.person.id)
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails with aspect ID that isn't user's" do
expect {
aspects_membership_service.create(@bob_aspect1.id, eve.person.id)
}.to raise_error ActiveRecord::RecordNotFound
end
end
end
describe "#destroy" do
before do
@membership = aspects_membership_service.create(@alice_aspect2.id, bob.person.id)
end
context "with aspect/user valid IDs" do
it "succeeds if in aspect" do
aspects_membership_service.destroy_by_ids(@alice_aspect2.id, bob.person.id)
expect(@alice_aspect2.contacts.find_by(person_id: bob.person.id)).to be_nil
end
it "fails if not in aspect" do
expect {
aspects_membership_service.destroy_by_ids(@alice_aspect2.id, eve.person.id)
}.to raise_error ActiveRecord::RecordNotFound
end
end
context "with a membership ID" do
it "succeeds if their membership" do
aspects_membership_service.destroy_by_membership_id(@membership.id)
expect(@alice_aspect2.contacts.find_by(person_id: bob.person.id)).to be_nil
end
it "fails if not their membership" do
expect {
aspects_membership_service(eve).destroy_by_membership_id(@membership.id)
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails if invalid membership ID" do
expect {
aspects_membership_service(eve).destroy_by_membership_id(-1)
}.to raise_error ActiveRecord::RecordNotFound
end
end
context "with invalid IDs" do
it "fails with invalid User ID" do
expect {
aspects_membership_service.destroy_by_ids(@alice_aspect2.id, -1)
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails with invalid Aspect ID" do
expect {
aspects_membership_service.destroy_by_ids(-1, eve.person.id)
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails with aspect ID that isn't user's" do
expect {
aspects_membership_service(eve).destroy_by_ids(@alice_aspect2.id, bob.person.id)
}.to raise_error ActiveRecord::RecordNotFound
end
end
end
describe "#list" do
before do
aspects_membership_service.create(@alice_aspect2.id, bob.person.id)
aspects_membership_service.create(@alice_aspect2.id, eve.person.id)
@alice_aspect3 = alice.aspects.create(name: "empty aspect")
end
context "with valid aspect ID" do
it "returns users in full aspect" do
contacts = aspects_membership_service.contacts_in_aspect(@alice_aspect2.id)
expect(contacts.length).to eq(2)
expect(contacts.map {|c| c.person.guid }.sort).to eq([bob.person.guid, eve.person.guid].sort)
end
it "returns empty array in empty aspect" do
contacts = aspects_membership_service.contacts_in_aspect(@alice_aspect3.id)
expect(contacts.length).to eq(0)
end
end
context "with invalid aspect ID" do
it "fails" do
expect {
aspects_membership_service.contacts_in_aspect(-1)
}.to raise_error ActiveRecord::RecordNotFound
end
end
end
describe "#all_contacts" do
before do
aspects_membership_service.create(@alice_aspect2.id, bob.person.id)
aspects_membership_service.create(@alice_aspect2.id, eve.person.id)
@alice_aspect3 = alice.aspects.create(name: "empty aspect")
end
it "returns all user's contacts" do
contacts = aspects_membership_service.all_contacts
expect(contacts.length).to eq(2)
end
end
def aspects_membership_service(user=alice)
AspectsMembershipService.new(user)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class LikeService
def initialize(user=nil)
@user = user
end
def create_for_post(post_id)
post = post_service.find!(post_id)
user.like!(post)
end
def create_for_comment(comment_id)
comment = comment_service.find!(comment_id)
post_service.find!(comment.commentable_id) # checks implicit for visible posts
user.like_comment!(comment)
end
def destroy(like_id)
like = Like.find(like_id)
if user.owns?(like)
user.retract(like)
true
else
false
end
end
def find_for_post(post_id)
likes = post_service.find!(post_id).likes
user ? likes.order(Arel.sql("author_id = #{user.person.id} DESC")) : likes
end
def find_for_comment(comment_id)
comment = comment_service.find!(comment_id)
post_service.find!(comment.post.id) # checks implicit for visible posts
likes = comment.likes
user ? likes.order(Arel.sql("author_id = #{user.person.id} DESC")) : likes
end
def unlike_post(post_id)
likes = post_service.find!(post_id).likes
likes = likes.order(Arel.sql("author_id = #{user.person.id} DESC"))
if !likes.empty? && user.owns?(likes[0])
user.retract(likes[0])
true
else
false
end
end
def unlike_comment(comment_id)
likes = comment_service.find!(comment_id).likes
likes = likes.order(Arel.sql("author_id = #{user.person.id} DESC"))
if !likes.empty? && user.owns?(likes[0])
user.retract(likes[0])
true
else
false
end
end
private
attr_reader :user
def post_service
@post_service ||= PostService.new(user)
end
def comment_service
@comment_service ||= CommentService.new(user)
end
end
``` | # frozen_string_literal: true
describe LikeService do
let(:post) { alice.post(:status_message, text: "hello", to: alice.aspects.first) }
let(:alice_comment) { CommentService.new(alice).create(post.id, "This is a wonderful post") }
let(:bobs_comment) { CommentService.new(bob).create(post.id, "My post was better than yours") }
describe "#create_for_post" do
it "creates a like on my own post" do
expect {
LikeService.new(alice).create_for_post(post.id)
}.not_to raise_error
end
it "creates a like on a post of a contact" do
expect {
LikeService.new(bob).create_for_post(post.id)
}.not_to raise_error
end
it "attaches the like to the post" do
like = LikeService.new(alice).create_for_post(post.id)
expect(post.likes.first.id).to eq(like.id)
end
it "fails if the post does not exist" do
expect {
LikeService.new(bob).create_for_post("unknown id")
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails if the user can't see the post" do
expect {
LikeService.new(eve).create_for_post(post.id)
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails if the user already liked the post" do
LikeService.new(alice).create_for_post(post.id)
expect {
LikeService.new(alice).create_for_post(post.id)
}.to raise_error ActiveRecord::RecordInvalid
end
end
describe "#create_for_comment" do
it "creates a like on a posts comment" do
expect {
LikeService.new(alice).create_for_comment(alice_comment.id)
}.not_to raise_error
end
it "creates a like on someone else comment" do
expect {
LikeService.new(alice).create_for_comment(bobs_comment.id)
}.not_to raise_error
end
it "attaches the like to the comment" do
like = LikeService.new(alice).create_for_comment(bobs_comment.id)
expect(bobs_comment.likes.first.id).to eq(like.id)
end
it "fails if comment does not exist" do
expect {
LikeService.new(alice).create_for_comment("unknown_id")
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails if user cant see post and its comments" do
expect {
LikeService.new(eve).create_for_comment(bobs_comment.id)
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails if user already liked the comment" do
LikeService.new(alice).create_for_comment(bobs_comment.id)
expect {
LikeService.new(alice).create_for_comment(bobs_comment.id)
}.to raise_error ActiveRecord::RecordInvalid
end
end
describe "#destroy" do
context "for post like" do
let(:like) { LikeService.new(bob).create_for_post(post.id) }
it "lets the user destroy their own like" do
result = LikeService.new(bob).destroy(like.id)
expect(result).to be_truthy
end
it "doesn't let the parent author destroy others likes" do
result = LikeService.new(alice).destroy(like.id)
expect(result).to be_falsey
end
it "doesn't let someone destroy others likes" do
result = LikeService.new(eve).destroy(like.id)
expect(result).to be_falsey
end
it "fails if the like doesn't exist" do
expect {
LikeService.new(bob).destroy("unknown id")
}.to raise_error ActiveRecord::RecordNotFound
end
end
context "for comment like" do
let(:like) { LikeService.new(bob).create_for_comment(alice_comment.id) }
it "let the user destroy its own comment like" do
result = LikeService.new(bob).destroy(like.id)
expect(result).to be_truthy
end
it "doesn't let the parent author destroy other comment likes" do
result = LikeService.new(alice).destroy(like.id)
expect(result).to be_falsey
end
it "fails if the like doesn't exist" do
expect {
LikeService.new(alice).destroy("unknown id")
}.to raise_error ActiveRecord::RecordNotFound
end
end
end
describe "#find_for_post" do
context "with user" do
it "returns likes for a public post" do
post = alice.post(:status_message, text: "hello", public: true)
like = LikeService.new(alice).create_for_post(post.id)
expect(LikeService.new(eve).find_for_post(post.id)).to include(like)
end
it "returns likes for a visible private post" do
like = LikeService.new(alice).create_for_post(post.id)
expect(LikeService.new(bob).find_for_post(post.id)).to include(like)
end
it "doesn't return likes for a private post the user can not see" do
LikeService.new(alice).create_for_post(post.id)
expect {
LikeService.new(eve).find_for_post(post.id)
}.to raise_error ActiveRecord::RecordNotFound
end
it "returns the user's like first" do
post = alice.post(:status_message, text: "hello", public: true)
[alice, bob, eve].map {|user| LikeService.new(user).create_for_post(post.id) }
[alice, bob, eve].each do |user|
expect(
LikeService.new(user).find_for_post(post.id).first.author.id
).to be user.person.id
end
end
end
context "without user" do
it "returns likes for a public post" do
post = alice.post(:status_message, text: "hello", public: true)
like = LikeService.new(alice).create_for_post(post.id)
expect(LikeService.new.find_for_post(post.id)).to include(like)
end
it "doesn't return likes a for private post" do
LikeService.new(alice).create_for_post(post.id)
expect {
LikeService.new.find_for_post(post.id)
}.to raise_error Diaspora::NonPublic
end
end
it "returns all likes of a post" do
post = alice.post(:status_message, text: "hello", public: true)
likes = [alice, bob, eve].map {|user| LikeService.new(user).create_for_post(post.id) }
expect(LikeService.new.find_for_post(post.id)).to match_array(likes)
end
end
describe "#find_for_comment" do
context "with user" do
it "returns likes for a public post comment" do
post = alice.post(:status_message, text: "hello", public: true)
comment = CommentService.new(bob).create(post.id, "Hello comment")
like = LikeService.new(alice).create_for_comment(comment.id)
expect(LikeService.new(eve).find_for_comment(comment.id)).to include(like)
end
it "returns likes for visible private post comments" do
comment = CommentService.new(bob).create(post.id, "Hello comment")
like = LikeService.new(alice).create_for_comment(comment.id)
expect(LikeService.new(bob).find_for_comment(comment.id)).to include(like)
end
it "doesn't return likes for a posts comment the user can not see" do
expect {
LikeService.new(eve).find_for_comment(alice_comment.id)
}.to raise_error ActiveRecord::RecordNotFound
end
it "returns the user's like first" do
post = alice.post(:status_message, text: "hello", public: true)
comment = CommentService.new(alice).create(post.id, "I like my own post")
[alice, bob, eve].map {|user| LikeService.new(user).create_for_comment(comment.id) }
[alice, bob, eve].each do |user|
expect(
LikeService.new(user).find_for_comment(comment.id).first.author.id
).to be user.person.id
end
end
end
context "without user" do
it "returns likes for a comment on a public post" do
post = alice.post(:status_message, text: "hello", public: true)
comment = CommentService.new(bob).create(post.id, "I like my own post")
like = LikeService.new(alice).create_for_comment(comment.id)
expect(
LikeService.new.find_for_comment(comment.id)
).to include(like)
end
it "doesn't return likes for a private post comment" do
LikeService.new(alice).create_for_comment(alice_comment.id)
expect {
LikeService.new.find_for_comment(alice_comment.id)
}.to raise_error Diaspora::NonPublic
end
end
end
describe "#unlike_post" do
before do
LikeService.new(alice).create_for_post(post.id)
end
it "removes the like to the post" do
LikeService.new(alice).unlike_post(post.id)
expect(post.likes.length).to eq(0)
end
end
describe "#unlike_comment" do
it "removes the like for a comment" do
comment = CommentService.new(alice).create(post.id, "I like my own post")
LikeService.new(alice).create_for_comment(comment.id)
expect(comment.likes.length).to eq(1)
LikeService.new(alice).unlike_comment(comment.id)
comment = CommentService.new(alice).find!(comment.id)
expect(comment.likes.length).to eq(0)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class StatusMessageCreationService
include Rails.application.routes.url_helpers
def initialize(user)
@user = user
end
def create(params)
validate_content(params)
build_status_message(params).tap do |status_message|
load_aspects(params[:aspect_ids]) unless status_message.public?
add_attachments(status_message, params)
status_message.save
process(status_message, params[:services])
end
end
private
attr_reader :user, :aspects
def validate_content(params)
raise MissingContent unless params[:status_message][:text].present? || params[:photos].present?
end
def build_status_message(params)
public = params[:public] || false
user.build_post(:status_message, params[:status_message].merge(public: public))
end
def add_attachments(status_message, params)
add_location(status_message, params[:location_address], params[:location_coords])
add_poll(status_message, params)
add_photos(status_message, params[:photos])
end
def add_location(status_message, address, coordinates)
status_message.build_location(address: address, coordinates: coordinates) if address.present?
end
def add_poll(status_message, params)
if params[:poll_question].present?
status_message.build_poll(question: params[:poll_question])
[*params[:poll_answers]].each do |poll_answer|
answer = status_message.poll.poll_answers.build(answer: poll_answer)
answer.poll = status_message.poll
end
end
end
def add_photos(status_message, photos)
if photos.present?
status_message.photos << Photo.where(id: photos, author_id: status_message.author_id)
status_message.photos.each do |photo|
photo.public = status_message.public
photo.pending = false
end
end
end
def load_aspects(aspect_ids)
@aspects = user.aspects_from_ids(aspect_ids)
raise BadAspectsIDs if aspects.empty?
end
def process(status_message, services)
add_to_streams(status_message) unless status_message.public?
dispatch(status_message, services)
end
def add_to_streams(status_message)
user.add_to_streams(status_message, aspects)
status_message.photos.each {|photo| user.add_to_streams(photo, aspects) }
end
def dispatch(status_message, services)
receiving_services = services ? Service.titles(services) : []
status_message.filter_mentions # this is only required until changes from #6818 are deployed on every pod
user.dispatch_post(status_message,
url: short_post_url(status_message.guid, host: AppConfig.environment.url),
service_types: receiving_services)
end
class BadAspectsIDs < RuntimeError
end
class MissingContent < RuntimeError
end
end
``` | # frozen_string_literal: true
describe StatusMessageCreationService do
describe "#create" do
let(:aspect) { alice.aspects.first }
let(:text) { "I'm writing tests" }
let(:params) {
{
status_message: {text: text},
aspect_ids: [aspect.id.to_s]
}
}
it "returns the created StatusMessage" do
status_message = StatusMessageCreationService.new(alice).create(params)
expect(status_message).to_not be_nil
expect(status_message.text).to eq(text)
end
context "with aspect_ids" do
it "creates aspect_visibilities for the StatusMessages" do
alice.aspects.create(name: "another aspect")
status_message = StatusMessageCreationService.new(alice).create(params)
expect(status_message.aspect_visibilities.map(&:aspect)).to eq([aspect])
end
it "does not create aspect_visibilities if the post is public" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(public: true))
expect(status_message.aspect_visibilities).to be_empty
end
it "raises exception if aspects_ids don't contain any applicable aspect identifiers" do
bad_ids = [Aspect.ids.max.next, bob.aspects.first.id].map(&:to_s)
expect {
StatusMessageCreationService.new(alice).create(params.merge(aspect_ids: bad_ids))
}.to remain(StatusMessage, :count).and raise_error(StatusMessageCreationService::BadAspectsIDs)
end
end
context "with public" do
it "it creates a private StatusMessage by default" do
status_message = StatusMessageCreationService.new(alice).create(params)
expect(status_message.public).to be_falsey
end
it "it creates a private StatusMessage" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(public: false))
expect(status_message.public).to be_falsey
end
it "it creates a public StatusMessage" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(public: true))
expect(status_message.public).to be_truthy
end
end
context "with location" do
it "it creates a location" do
location_params = {location_address: "somewhere", location_coords: "1,2"}
status_message = StatusMessageCreationService.new(alice).create(params.merge(location_params))
location = status_message.location
expect(location.address).to eq("somewhere")
expect(location.lat).to eq("1")
expect(location.lng).to eq("2")
end
it "does not add a location without location params" do
status_message = StatusMessageCreationService.new(alice).create(params)
expect(status_message.location).to be_nil
end
end
context "with poll" do
it "it creates a poll" do
poll_params = {poll_question: "something?", poll_answers: %w(yes no maybe)}
status_message = StatusMessageCreationService.new(alice).create(params.merge(poll_params))
poll = status_message.poll
expect(poll.question).to eq("something?")
expect(poll.poll_answers.size).to eq(3)
poll_answers = poll.poll_answers.map(&:answer)
expect(poll_answers).to include("yes")
expect(poll_answers).to include("no")
expect(poll_answers).to include("maybe")
end
it "does not add a poll without poll params" do
status_message = StatusMessageCreationService.new(alice).create(params)
expect(status_message.poll).to be_nil
end
end
context "with photos" do
let(:photo1) {
alice.build_post(:photo, pending: true, user_file: File.open(photo_fixture_name), to: aspect.id).tap(&:save!)
}
let(:photo2) {
alice.build_post(:photo, pending: true, user_file: File.open(photo_fixture_name), to: aspect.id).tap(&:save!)
}
let(:photo_ids) { [photo1.id.to_s, photo2.id.to_s] }
it "it attaches all photos" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids))
photos = status_message.photos
expect(photos.size).to eq(2)
expect(photos.map(&:id).map(&:to_s)).to match_array(photo_ids)
end
it "does not attach photos without photos param" do
status_message = StatusMessageCreationService.new(alice).create(params)
expect(status_message.photos).to be_empty
end
context "with aspect_ids" do
it "it marks the photos as non-public if the post is non-public" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids))
status_message.photos.each do |photo|
expect(photo.public).to be_falsey
end
end
it "creates aspect_visibilities for the Photo" do
alice.aspects.create(name: "another aspect")
status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids))
status_message.photos.each do |photo|
expect(photo.aspect_visibilities.map(&:aspect)).to eq([aspect])
end
end
it "does not create aspect_visibilities if the post is public" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids, public: true))
status_message.photos.each do |photo|
expect(photo.aspect_visibilities).to be_empty
end
end
it "sets pending to false on any attached photos" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids))
status_message.photos.each do |photo|
expect(photo.reload.pending).to be_falsey
end
end
end
context "with public" do
it "it marks the photos as public if the post is public" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids, public: true))
status_message.photos.each do |photo|
expect(photo.public).to be_truthy
end
end
it "sets pending to false on any attached photos" do
status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids, public: true))
status_message.photos.each do |photo|
expect(photo.reload.pending).to be_falsey
end
end
end
end
context "dispatch" do
it "dispatches the StatusMessage" do
expect(alice).to receive(:dispatch_post).with(instance_of(StatusMessage), hash_including(service_types: []))
StatusMessageCreationService.new(alice).create(params)
end
it "dispatches the StatusMessage to services" do
expect(alice).to receive(:dispatch_post)
.with(instance_of(StatusMessage),
hash_including(service_types: array_including(%w[Services::Tumblr Services::Twitter])))
StatusMessageCreationService.new(alice).create(params.merge(services: %w[twitter tumblr]))
end
context "with mention" do
let(:text) { text_mentioning(eve) }
# this is only required until changes from #6818 are deployed on every pod
it "filters out mentions from text attribute" do
status_message = StatusMessageCreationService.new(alice).create(params)
expect(status_message.text).not_to include(eve.diaspora_handle)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class PostService
def initialize(user=nil)
@user = user
end
def find(id)
if user
user.find_visible_shareable_by_id(Post, id)
else
Post.find_by_id_and_public(id, true)
end
end
def find!(id_or_guid)
if user
find_non_public_by_guid_or_id_with_user!(id_or_guid)
else
find_public!(id_or_guid)
end
end
def present_json
PostPresenter.new(post, user)
end
def present_interactions_json
PostInteractionPresenter.new(post, user)
end
def mark_user_notifications(post_id)
return unless user
mark_comment_reshare_like_notifications_read(post_id)
mark_mention_notifications_read(post_id)
end
def destroy(post_id, private_allowed=true)
post = if private_allowed
find_non_public_by_guid_or_id_with_user!(post_id)
else
find_public!(post_id)
end
raise Diaspora::NotMine unless post.author == user.person
user.retract(post)
end
def mentionable_in_comment(post_id, query)
post = find!(post_id)
Person
.allowed_to_be_mentioned_in_a_comment_to(post)
.where.not(id: user.person_id)
.find_by_substring(query)
.sort_for_mention_suggestion(post, user)
.for_json
.limit(15)
end
private
attr_reader :user
def find_public!(id_or_guid)
Post.where(post_key(id_or_guid) => id_or_guid).first.tap do |post|
raise ActiveRecord::RecordNotFound, "could not find a post with id #{id_or_guid}" unless post
raise Diaspora::NonPublic unless post.public?
end
end
def find_non_public_by_guid_or_id_with_user!(id_or_guid)
user.find_visible_shareable_by_id(Post, id_or_guid, key: post_key(id_or_guid)).tap do |post|
raise ActiveRecord::RecordNotFound, "could not find a post with id #{id_or_guid} for user #{user.id}" unless post
end
end
# We can assume a guid is at least 16 characters long as we have guids set to hex(8) since we started using them.
def post_key(id_or_guid)
id_or_guid.to_s.length < 16 ? :id : :guid
end
def mark_comment_reshare_like_notifications_read(post_id)
Notification.where(recipient_id: user.id, target_type: "Post", target_id: post_id, unread: true)
.update_all(unread: false)
end
def mark_mention_notifications_read(post_id)
mention_ids = Mention.where(
mentions_container_id: post_id,
mentions_container_type: "Post",
person_id: user.person_id
).ids
mention_ids.concat(mentions_in_comments_for_post(post_id).pluck(:id))
Notification.where(recipient_id: user.id, target_type: "Mention", target_id: mention_ids, unread: true)
.update_all(unread: false) if mention_ids.any?
end
def mentions_in_comments_for_post(post_id)
Mention
.joins("INNER JOIN comments ON mentions_container_id = comments.id AND mentions_container_type = 'Comment'")
.where(comments: {commentable_id: post_id, commentable_type: "Post"})
end
end
``` | # frozen_string_literal: true
describe PostService do
let(:post) { alice.post(:status_message, text: "ohai", to: alice.aspects.first) }
let(:public) { alice.post(:status_message, text: "hey", public: true) }
describe "#find" do
context "with user" do
it "returns the post, if it is the users post" do
expect(PostService.new(alice).find(post.id)).to eq(post)
end
it "returns the post, if the user can see the it" do
expect(PostService.new(bob).find(post.id)).to eq(post)
end
it "returns the post, if it is public" do
expect(PostService.new(eve).find(public.id)).to eq(public)
end
it "does not return the post, if the post cannot be found" do
expect(PostService.new(alice).find("unknown")).to be_nil
end
it "does not return the post, if user cannot see the post" do
expect(PostService.new(eve).find(post.id)).to be_nil
end
end
context "without user" do
it "returns the post, if it is public" do
expect(PostService.new.find(public.id)).to eq(public)
end
it "does not return the post, if the post is private" do
expect(PostService.new.find(post.id)).to be_nil
end
it "does not return the post, if the post cannot be found" do
expect(PostService.new.find("unknown")).to be_nil
end
end
end
describe "#find!" do
context "with user" do
it "returns the post, if it is the users post" do
expect(PostService.new(alice).find!(post.id)).to eq(post)
end
it "works with guid" do
expect(PostService.new(alice).find!(post.guid)).to eq(post)
end
it "returns the post, if the user can see the it" do
expect(PostService.new(bob).find!(post.id)).to eq(post)
end
it "returns the post, if it is public" do
expect(PostService.new(eve).find!(public.id)).to eq(public)
end
it "RecordNotFound if the post cannot be found" do
expect {
PostService.new(alice).find!("unknown")
}.to raise_error ActiveRecord::RecordNotFound, "could not find a post with id unknown for user #{alice.id}"
end
it "RecordNotFound if user cannot see the post" do
expect {
PostService.new(eve).find!(post.id)
}.to raise_error ActiveRecord::RecordNotFound, "could not find a post with id #{post.id} for user #{eve.id}"
end
end
context "without user" do
it "returns the post, if it is public" do
expect(PostService.new.find!(public.id)).to eq(public)
end
it "works with guid" do
expect(PostService.new.find!(public.guid)).to eq(public)
end
it "NonPublic if the post is private" do
expect {
PostService.new.find!(post.id)
}.to raise_error Diaspora::NonPublic
end
it "RecordNotFound if the post cannot be found" do
expect {
PostService.new.find!("unknown")
}.to raise_error ActiveRecord::RecordNotFound, "could not find a post with id unknown"
end
end
context "id/guid switch" do
let(:public) { alice.post(:status_message, text: "ohai", public: true) }
it "assumes ids less than 16 chars are ids and not guids" do
post = Post.where(id: public.id)
expect(Post).to receive(:where).with(hash_including(id: "123456789012345")).and_return(post).at_least(:once)
PostService.new(alice).find!("123456789012345")
end
it "assumes ids more than (or equal to) 16 chars are actually guids" do
post = Post.where(guid: public.guid)
expect(Post).to receive(:where).with(hash_including(guid: "1234567890123456")).and_return(post).at_least(:once)
PostService.new(alice).find!("1234567890123456")
end
end
end
describe "#mark_user_notifications" do
let(:status_text) { text_mentioning(alice) }
it "marks a corresponding notifications as read" do
FactoryBot.create(:notification, recipient: alice, target: post, unread: true)
FactoryBot.create(:notification, recipient: alice, target: post, unread: true)
expect {
PostService.new(alice).mark_user_notifications(post.id)
}.to change(Notification.where(unread: true), :count).by(-2)
end
it "marks a corresponding mention notification as read" do
mention_post = bob.post(:status_message, text: status_text, public: true)
expect {
PostService.new(alice).mark_user_notifications(mention_post.id)
}.to change(Notification.where(unread: true), :count).by(-1)
end
it "marks a corresponding mention in comment notification as read" do
notification = FactoryBot.create(:notification_mentioned_in_comment)
status_message = notification.target.mentions_container.parent
user = notification.recipient
expect {
PostService.new(user).mark_user_notifications(status_message.id)
}.to change(Notification.where(unread: true), :count).by(-1)
end
it "does not change the update_at date/time for post notifications" do
notification = Timecop.travel(1.minute.ago) do
FactoryBot.create(:notification, recipient: alice, target: post, unread: true)
end
expect {
PostService.new(alice).mark_user_notifications(post.id)
}.not_to change { Notification.where(id: notification.id).pluck(:updated_at) }
end
it "does not change the update_at date/time for mention notifications" do
mention_post = Timecop.travel(1.minute.ago) do
bob.post(:status_message, text: status_text, public: true)
end
mention = mention_post.mentions.where(person_id: alice.person.id).first
expect {
PostService.new(alice).mark_user_notifications(post.id)
}.not_to change { Notification.where(target_type: "Mention", target_id: mention.id).pluck(:updated_at) }
end
it "does nothing without a user" do
expect_any_instance_of(PostService).not_to receive(:mark_comment_reshare_like_notifications_read).with(post.id)
expect_any_instance_of(PostService).not_to receive(:mark_mention_notifications_read).with(post.id)
PostService.new.mark_user_notifications(post.id)
end
end
describe "#destroy" do
it "let a user delete his message" do
PostService.new(alice).destroy(post.id)
expect(StatusMessage.find_by_id(post.id)).to be_nil
end
it "sends a retraction on delete" do
expect(alice).to receive(:retract).with(post)
PostService.new(alice).destroy(post.id)
end
it "won't delete private post if explicitly unallowed" do
expect {
PostService.new(alice).destroy(post.id, false)
}.to raise_error Diaspora::NonPublic
expect(StatusMessage.find_by(id: post.id)).not_to be_nil
end
it "will not let you destroy posts visible to you but that you do not own" do
expect {
PostService.new(bob).destroy(post.id)
}.to raise_error Diaspora::NotMine
expect(StatusMessage.find_by_id(post.id)).not_to be_nil
end
it "will not let you destroy posts that are not visible to you" do
expect {
PostService.new(eve).destroy(post.id)
}.to raise_error(ActiveRecord::RecordNotFound)
expect(StatusMessage.find_by_id(post.id)).not_to be_nil
end
end
describe "#mentionable_in_comment" do
describe "semi-integration test" do
let(:post_author_attributes) { {first_name: "Ro#{r_str}"} }
let(:post_author) { FactoryBot.create(:person, post_author_attributes) }
let(:current_user) { FactoryBot.create(:user_with_aspect) }
let(:post_service) { PostService.new(current_user) }
shared_context "with commenters and likers" do
# randomize ids of the created people so that the test doesn't pass just because of
# the id sequence matched against the expected ordering
let(:ids) { (1..4).map {|i| Person.maximum(:id) + i }.shuffle }
before do
# in case when post_author has't been instantiated before this context, specify id
# in order to avoid id conflict with the people generated here
post_author_attributes.merge!(id: ids.max + 1)
end
let!(:commenter1) {
FactoryBot.create(:person, id: ids.shift, first_name: "Ro1#{r_str}").tap {|person|
FactoryBot.create(:comment, author: person, post: post)
}
}
let!(:commenter2) {
FactoryBot.create(:person, id: ids.shift, first_name: "Ro2#{r_str}").tap {|person|
FactoryBot.create(:comment, author: person, post: post)
}
}
let!(:liker1) {
FactoryBot.create(:person, id: ids.shift, first_name: "Ro1#{r_str}").tap {|person|
FactoryBot.create(:like, author: person, target: post)
}
}
let!(:liker2) {
FactoryBot.create(:person, id: ids.shift, first_name: "Ro2#{r_str}").tap {|person|
FactoryBot.create(:like, author: person, target: post)
}
}
end
shared_context "with a current user's friend" do
let!(:current_users_friend) {
FactoryBot.create(:person).tap {|friend|
current_user.contacts.create!(
person: friend,
aspects: [current_user.aspects.first],
sharing: true,
receiving: true
)
}
}
end
context "with private post" do
let(:post) { FactoryBot.create(:status_message, text: "ohai", author: post_author) }
context "when the post doesn't have a visibility for the current user" do
it "doesn't find a post and raises an exception" do
expect {
post_service.mentionable_in_comment(post.id, "Ro")
}.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the post has a visibility for the current user" do
before do
ShareVisibility.batch_import([current_user.id], post)
end
context "with commenters and likers" do
include_context "with commenters and likers"
it "returns mention suggestions in the correct order" do
expected_suggestions = [
post_author, commenter1, commenter2, liker1, liker2
]
expect(post_service.mentionable_in_comment(post.id, "Ro")).to eq(expected_suggestions)
end
end
context "with a current user's friend" do
include_context "with a current user's friend"
it "doesn't include a contact" do
expect(post_service.mentionable_in_comment(post.id, current_users_friend.first_name)).to be_empty
end
end
it "doesn't include a non contact" do
expect(post_service.mentionable_in_comment(post.id, eve.person.first_name)).to be_empty
end
end
end
context "with public post" do
let(:post) { FactoryBot.create(:status_message, text: "ohai", public: true, author: post_author) }
context "with commenters and likers and with a current user's friend" do
include_context "with commenters and likers"
include_context "with a current user's friend"
it "returns mention suggestions in the correct order" do
result = post_service.mentionable_in_comment(post.id, "Ro").to_a
expect(result.size).to be > 7
# participants: post author, comments, likers
expect(result[0..4]).to eq([post_author, commenter1, commenter2, liker1, liker2])
# contacts
expect(result[5]).to eq(current_users_friend)
# non-contacts
result[6..-1].each {|person|
expect(person.contacts.where(user_id: current_user.id)).to be_empty
expect(person.profile.first_name).to include("Ro")
}
end
it "doesn't include people with non-matching names" do
commenter = FactoryBot.create(:person, first_name: "RRR#{r_str}")
FactoryBot.create(:comment, author: commenter)
liker = FactoryBot.create(:person, first_name: "RRR#{r_str}")
FactoryBot.create(:like, author: liker)
friend = FactoryBot.create(:person, first_name: "RRR#{r_str}")
current_user.contacts.create!(
person: friend,
aspects: [current_user.aspects.first],
sharing: true,
receiving: true
)
result = post_service.mentionable_in_comment(post.id, "Ro")
expect(result).not_to include(commenter)
expect(result).not_to include(liker)
expect(result).not_to include(friend)
end
end
shared_examples "current user can't mention themself" do
before do
current_user.profile.update(first_name: "Ro#{r_str}")
end
it "doesn't include current user" do
expect(post_service.mentionable_in_comment(post.id, "Ro")).not_to include(current_user.person)
end
end
context "when current user is a post author" do
let(:post_author) { current_user.person }
include_examples "current user can't mention themself"
end
context "current user is a participant" do
before do
current_user.like!(post)
current_user.comment!(post, "hello")
end
include_examples "current user can't mention themself"
end
context "current user is a stranger matching a search pattern" do
include_examples "current user can't mention themself"
end
it "doesn't fail when the post author doesn't match the requested pattern" do
expect(post_service.mentionable_in_comment(post.id, "#{r_str}#{r_str}#{r_str}")).to be_empty
end
it "renders a commenter with multiple comments only once" do
person = FactoryBot.create(:person, first_name: "Ro2#{r_str}")
2.times { FactoryBot.create(:comment, author: person, post: post) }
expect(post_service.mentionable_in_comment(post.id, person.first_name).length).to eq(1)
end
end
end
describe "unit test" do
let(:post_service) { PostService.new(alice) }
before do
expect(post_service).to receive(:find!).and_return(post)
end
it "calls Person.allowed_to_be_mentioned_in_a_comment_to" do
expect(Person).to receive(:allowed_to_be_mentioned_in_a_comment_to).with(post).and_call_original
post_service.mentionable_in_comment(post.id, "whatever")
end
it "calls Person.find_by_substring" do
expect(Person).to receive(:find_by_substring).with("whatever").and_call_original
post_service.mentionable_in_comment(post.id, "whatever")
end
it "calls Person.sort_for_mention_suggestion" do
expect(Person).to receive(:sort_for_mention_suggestion).with(post, alice).and_call_original
post_service.mentionable_in_comment(post.id, "whatever")
end
it "calls Person.limit" do
16.times {
FactoryBot.create(:comment, author: FactoryBot.create(:person, first_name: "Ro#{r_str}"), post: post)
}
expect(post_service.mentionable_in_comment(post.id, "Ro").length).to eq(15)
end
it "contains a constraint on a current user" do
expect(Person).to receive(:allowed_to_be_mentioned_in_a_comment_to) { Person.all }
expect(Person).to receive(:find_by_substring) { Person.all }
expect(Person).to receive(:sort_for_mention_suggestion) { Person.all }
expect(post_service.mentionable_in_comment(post.id, alice.person.first_name))
.not_to include(alice.person)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class NotificationService
NOTIFICATION_TYPES = {
Comment => [Notifications::MentionedInComment, Notifications::CommentOnPost, Notifications::AlsoCommented],
Like => [Notifications::Liked, Notifications::LikedComment],
StatusMessage => [Notifications::MentionedInPost],
Conversation => [Notifications::PrivateMessage],
Message => [Notifications::PrivateMessage],
Reshare => [Notifications::Reshared],
Contact => [Notifications::StartedSharing]
}.freeze
NOTIFICATIONS_JSON_TYPES = {
"also_commented" => "Notifications::AlsoCommented",
"comment_on_post" => "Notifications::CommentOnPost",
"liked" => "Notifications::Liked",
"liked_comment" => "Notifications::LikedComment",
"mentioned" => "Notifications::MentionedInPost",
"mentioned_in_comment" => "Notifications::MentionedInComment",
"reshared" => "Notifications::Reshared",
"started_sharing" => "Notifications::StartedSharing",
"contacts_birthday" => "Notifications::ContactsBirthday"
}.freeze
NOTIFICATIONS_REVERSE_JSON_TYPES = NOTIFICATIONS_JSON_TYPES.invert.freeze
def initialize(user=nil)
@user = user
end
def index(unread_only=nil, only_after=nil)
query_string = "recipient_id = ? "
query_string += "AND unread = true " if unread_only
where_clause = [query_string, @user.id]
if only_after
query_string += " AND created_at >= ?"
where_clause = [query_string, @user.id, only_after]
end
Notification.where(where_clause).includes(:target, actors: :profile)
end
def get_by_guid(guid)
Notification.where(recipient_id: @user.id, guid: guid).first
end
def update_status_by_guid(guid, is_read_status)
notification = get_by_guid(guid)
raise ActiveRecord::RecordNotFound unless notification
notification.set_read_state(is_read_status)
true
end
def notify(object, recipient_user_ids)
notification_types(object).each {|type| type.notify(object, recipient_user_ids) }
end
private
def notification_types(object)
NOTIFICATION_TYPES.fetch(object.class, [])
end
end
``` | # frozen_string_literal: true
describe NotificationService do
describe "notification interrelation" do
context "with mention in comment" do
let(:status_message) {
FactoryBot.create(:status_message, public: true, author: alice.person).tap {|status_message|
eve.comment!(status_message, "whatever")
}
}
let(:comment) {
FactoryBot.create(
:comment,
author: bob.person,
text: text_mentioning(alice, eve),
post: status_message
)
}
it "sends only mention notification" do
[alice, eve].each do |user|
expect(Workers::Mail::MentionedInComment).to receive(:perform_async).with(
user.id,
bob.person.id,
*comment.mentions.where(person: user.person).ids
)
end
expect {
NotificationService.new.notify(comment, [])
}.to change { Notification.where(recipient_id: alice).count }.by(1)
.and change { Notification.where(recipient_id: eve).count }.by(1)
[alice, eve].each do |user|
expect(
Notifications::MentionedInComment.where(target: comment.mentions, recipient_id: user.id)
).to exist
expect(
Notifications::CommentOnPost.where(target: comment.parent, recipient_id: user.id)
).not_to exist
expect(
Notifications::AlsoCommented.where(target: comment.parent, recipient_id: user.id)
).not_to exist
end
end
context "with \"mentioned in comment\" email turned off" do
before do
alice.user_preferences.create(email_type: "mentioned_in_comment")
eve.user_preferences.create(email_type: "mentioned_in_comment")
end
it "calls appropriate mail worker instead" do
expect(Workers::Mail::MentionedInComment).not_to receive(:perform_async)
expect(Workers::Mail::CommentOnPost).to receive(:perform_async).with(
alice.id,
bob.person.id,
*comment.mentions.where(person: alice.person).ids
)
expect(Workers::Mail::AlsoCommented).to receive(:perform_async).with(
eve.id,
bob.person.id,
*comment.mentions.where(person: eve.person).ids
)
NotificationService.new.notify(comment, [])
end
end
end
end
describe "query methods" do
before do
@post = alice.post(
:status_message,
text: "This is a status message",
public: true,
to: "all"
)
@notification = FactoryBot.create(:notification, recipient: alice, target: @post)
@service = NotificationService.new(alice)
end
describe "#index" do
it "gets all" do
notifications = @service.index
expect(notifications.length).to eq(1)
end
it "gets unread only" do
notifications = @service.index(true)
expect(notifications.length).to eq(1)
@notification.set_read_state(true)
notifications = @service.index(true)
expect(notifications.length).to eq(0)
end
it "gets only after" do
notifications = @service.index(nil, (Time.current - 1.day))
expect(notifications.length).to eq(1)
@notification.set_read_state(true)
notifications = @service.index(nil, (Time.current + 1.day))
expect(notifications.length).to eq(0)
end
it "combined filtering" do
notifications = @service.index(true, (Time.current - 1.day))
expect(notifications.length).to eq(1)
end
end
describe "#show" do
it "succeeds with valid GUID" do
notification = @service.get_by_guid(@notification.guid)
expect(notification).not_to be_nil
end
end
describe "#update" do
it "succeeds with valid GUID" do
expect(@service.update_status_by_guid(@notification.guid, true)).to be_truthy
expect(@notification.reload.unread).to eq(false)
expect(@service.update_status_by_guid(@notification.guid, false)).to be_truthy
expect(@notification.reload.unread).to eq(true)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
# Encapsulates logic of processing diaspora:// links
class DiasporaLinkService
attr_reader :type, :author, :guid
def initialize(link)
@link = link.dup
parse
end
def find_or_fetch_entity
if type && guid
entity_finder.find || fetch_entity
elsif author
find_or_fetch_person
end
end
private
attr_accessor :link
def fetch_entity
DiasporaFederation::Federation::Fetcher.fetch_public(author, type, guid)
entity_finder.find
rescue DiasporaFederation::Federation::Fetcher::NotFetchable
nil
end
def entity_finder
@entity_finder ||= Diaspora::EntityFinder.new(type, guid)
end
def find_or_fetch_person
Person.find_or_fetch_by_identifier(author)
rescue DiasporaFederation::Discovery::DiscoveryError
nil
end
def normalize
link.gsub!(%r{^web\+diaspora://}, "diaspora://") ||
link.gsub!(%r{^//}, "diaspora://") ||
%r{^diaspora://}.match(link) ||
self.link = "diaspora://#{link}"
end
def parse
normalize
match = DiasporaFederation::Federation::DiasporaUrlParser::DIASPORA_URL_REGEX.match(link)
if match
@author, @type, @guid = match.captures
else
@author = %r{^diaspora://(#{Validation::Rule::DiasporaId::DIASPORA_ID_REGEX})$}u.match(link)&.captures&.first
end
end
end
``` | # frozen_string_literal: true
describe DiasporaLinkService do
let(:service) { described_class.new(link) }
describe "#find_or_fetch_entity" do
context "when entity is known" do
let(:post) { FactoryBot.create(:status_message) }
let(:link) { "diaspora://#{post.author.diaspora_handle}/post/#{post.guid}" }
it "returns the entity" do
expect(service.find_or_fetch_entity).to eq(post)
end
end
context "when entity is unknown" do
let(:remote_person) { FactoryBot.create(:person) }
let(:guid) { "1234567890abcdef" }
let(:link) { "diaspora://#{remote_person.diaspora_handle}/post/#{guid}" }
it "fetches entity" do
expect(DiasporaFederation::Federation::Fetcher)
.to receive(:fetch_public)
.with(remote_person.diaspora_handle, "post", guid) {
FactoryBot.create(:status_message, author: remote_person, guid: guid)
}
entity = service.find_or_fetch_entity
expect(entity).to be_a(StatusMessage)
expect(entity.guid).to eq(guid)
expect(entity.author).to eq(remote_person)
end
it "returns nil when entity is non fetchable" do
expect(DiasporaFederation::Federation::Fetcher)
.to receive(:fetch_public)
.with(remote_person.diaspora_handle, "post", guid)
.and_raise(DiasporaFederation::Federation::Fetcher::NotFetchable)
expect(service.find_or_fetch_entity).to be_nil
end
end
context "with invalid links" do
it "returns nil when the link is invalid" do
service = described_class.new("web+diaspora://something_invalid")
expect(service.find_or_fetch_entity).to be_nil
end
it "returns nil when the author is valid, but rest of the link is invalid" do
service = described_class.new("web+diaspora://#{alice.diaspora_handle}/foo/bar")
expect(service.find_or_fetch_entity).to be_nil
end
end
context "with only a diaspora ID" do
let(:person) { FactoryBot.create(:person) }
let(:link) { "diaspora://#{person.diaspora_handle}" }
it "returns the person" do
expect(service.find_or_fetch_entity).to eq(person)
end
it "returns nil when person is non fetchable" do
expect(Person).to receive(:find_or_fetch_by_identifier)
.with(person.diaspora_handle).and_raise(DiasporaFederation::Discovery::DiscoveryError)
expect(service.find_or_fetch_entity).to be_nil
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class PollParticipationService
def initialize(user)
@user = user
end
def vote(post_id, answer_id)
answer = PollAnswer.find(answer_id)
@user.participate_in_poll!(target(post_id), answer) if target(post_id)
end
private
def target(post_id)
@target ||= @user.find_visible_shareable_by_id(Post, post_id) || raise(ActiveRecord::RecordNotFound.new)
end
end
``` | # frozen_string_literal: true
describe PollParticipationService do
let(:poll_post) { FactoryBot.create(:status_message_with_poll, public: true) }
let(:poll_answer) { poll_post.poll.poll_answers.first }
describe "voting on poll" do
it "succeeds" do
expect(poll_service.vote(poll_post.id, poll_answer.id)).not_to be_nil
end
it "fails to vote twice" do
expect(poll_service.vote(poll_post.id, poll_answer.id)).not_to be_nil
expect { poll_service.vote(poll_post.id, poll_answer.id) }.to raise_error(ActiveRecord::RecordInvalid)
end
it "fails with bad answer id" do
expect { poll_service.vote(poll_post.id, -2) }.to raise_error(ActiveRecord::RecordNotFound)
end
it "fails with bad post id" do
expect { poll_service.vote(-1, poll_answer.id) }.to raise_error(ActiveRecord::RecordNotFound)
end
end
def poll_service(user=alice)
PollParticipationService.new(user)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class ReshareService
def initialize(user=nil)
@user = user
end
def create(post_id)
post = post_service.find!(post_id)
post = post.absolute_root if post.is_a? Reshare
user.reshare!(post)
end
def find_for_post(post_id)
reshares = post_service.find!(post_id).reshares
user ? reshares.order(Arel.sql("author_id = #{user.person.id} DESC")) : reshares
end
private
attr_reader :user
def post_service
@post_service ||= PostService.new(user)
end
end
``` | # frozen_string_literal: true
describe ReshareService do
let(:post) { alice.post(:status_message, text: "hello", public: true) }
describe "#create" do
it "doesn't create a reshare of my own post" do
expect {
ReshareService.new(alice).create(post.id)
}.to raise_error RuntimeError
end
it "creates a reshare of a post of a contact" do
expect {
ReshareService.new(bob).create(post.id)
}.not_to raise_error
end
it "attaches the reshare to the post" do
reshare = ReshareService.new(bob).create(post.id)
expect(post.reshares.first.id).to eq(reshare.id)
end
it "reshares the original post when called with a reshare" do
reshare = ReshareService.new(bob).create(post.id)
reshare2 = ReshareService.new(eve).create(reshare.id)
expect(post.reshares.map(&:id)).to include(reshare2.id)
end
it "fails if the post does not exist" do
expect {
ReshareService.new(bob).create("unknown id")
}.to raise_error ActiveRecord::RecordNotFound
end
it "fails if the post is not public" do
post = alice.post(:status_message, text: "hello", to: alice.aspects.first)
expect {
ReshareService.new(bob).create(post.id)
}.to raise_error ActiveRecord::RecordInvalid
end
it "fails if the user already reshared the post" do
ReshareService.new(bob).create(post.id)
expect {
ReshareService.new(bob).create(post.id)
}.to raise_error ActiveRecord::RecordInvalid
end
it "fails if the user already reshared the original post" do
reshare = ReshareService.new(bob).create(post.id)
expect {
ReshareService.new(bob).create(reshare.id)
}.to raise_error ActiveRecord::RecordInvalid
end
end
describe "#find_for_post" do
context "with user" do
it "returns reshares for a public post" do
reshare = ReshareService.new(bob).create(post.id)
expect(ReshareService.new(eve).find_for_post(post.id)).to include(reshare)
end
it "returns reshares for a visible private post" do
post = alice.post(:status_message, text: "hello", to: alice.aspects.first)
expect(ReshareService.new(bob).find_for_post(post.id)).to be_empty
end
it "doesn't return reshares for a private post the user can not see" do
post = alice.post(:status_message, text: "hello", to: alice.aspects.first)
expect {
ReshareService.new(eve).find_for_post(post.id)
}.to raise_error ActiveRecord::RecordNotFound
end
it "returns the user's reshare first" do
[bob, eve].map {|user| ReshareService.new(user).create(post.id) }
[bob, eve].each do |user|
expect(
ReshareService.new(user).find_for_post(post.id).first.author.id
).to be user.person.id
end
end
end
context "without user" do
it "returns reshares for a public post" do
reshare = ReshareService.new(bob).create(post.id)
expect(ReshareService.new.find_for_post(post.id)).to include(reshare)
end
it "doesn't return reshares a for private post" do
post = alice.post(:status_message, text: "hello", to: alice.aspects.first)
expect {
ReshareService.new.find_for_post(post.id)
}.to raise_error Diaspora::NonPublic
end
end
it "returns all reshares of a post" do
reshares = [bob, eve].map {|user| ReshareService.new(user).create(post.id) }
expect(ReshareService.new.find_for_post(post.id)).to match_array(reshares)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class PhotoService
def initialize(user=nil, deny_raw_files=true)
@user = user
@deny_raw_files = deny_raw_files
end
def visible_photo(photo_guid)
Photo.owned_or_visible_by_user(@user).where(guid: photo_guid).first
end
def create_from_params_and_file(base_params, uploaded_file)
photo_params = build_params(base_params)
raise RuntimeError if @deny_raw_files && !confirm_uploaded_file_settings(uploaded_file)
photo_params[:user_file] = uploaded_file
photo = @user.build_post(:photo, photo_params)
raise RuntimeError unless photo.save
send_messages(photo, photo_params)
update_profile_photo(photo) if photo_params[:set_profile_photo]
photo
end
private
def build_params(base_params)
photo_params = base_params.permit(:pending, :set_profile_photo, aspect_ids: [])
if base_params.permit(:aspect_ids)[:aspect_ids] == "all"
photo_params[:aspect_ids] = @user.aspects.map(&:id)
elsif photo_params[:aspect_ids].is_a?(Hash)
photo_params[:aspect_ids] = params[:photo][:aspect_ids].values
end
photo_params
end
def confirm_uploaded_file_settings(uploaded_file)
unless uploaded_file.is_a?(ActionDispatch::Http::UploadedFile) || uploaded_file.is_a?(Rack::Test::UploadedFile)
return false
end
return false if uploaded_file.original_filename.empty?
return false if uploaded_file.content_type.empty?
true
end
def send_messages(photo, photo_params)
send_to_streams(photo, photo_params) unless photo.pending && photo.public?
@user.dispatch_post(photo, to: photo_params[:aspect_ids]) unless photo.pending
end
def update_profile_photo(photo)
@user.update_profile(photo: photo)
end
def send_to_streams(photo, photo_params)
aspects = @user.aspects_from_ids(photo_params[:aspect_ids])
@user.add_to_streams(photo, aspects)
end
end
``` | # frozen_string_literal: true
describe PhotoService do
before do
alice_eve_spec = alice.aspects.create(name: "eve aspect")
alice.share_with(eve.person, alice_eve_spec)
alice_bob_spec = alice.aspects.create(name: "bob aspect")
alice.share_with(bob.person, alice_bob_spec)
@alice_eve_photo = alice.post(:photo, pending: false, user_file: File.open(photo_fixture_name),
to: alice_eve_spec.id)
@alice_bob_photo = alice.post(:photo, pending: false, user_file: File.open(photo_fixture_name),
to: alice_bob_spec.id)
@alice_public_photo = alice.post(:photo, pending: false, user_file: File.open(photo_fixture_name), public: true)
@bob_photo1 = bob.post(:photo, pending: true, user_file: File.open(photo_fixture_name), public: true)
end
describe "visible_photo" do
it "returns a user's photo" do
photo = photo_service.visible_photo(@bob_photo1.guid)
expect(photo.guid).to eq(@bob_photo1.guid)
end
it "returns another user's public photo" do
photo = photo_service.visible_photo(@alice_public_photo.guid)
expect(photo.guid).to eq(@alice_public_photo.guid)
end
it "returns another user's shared photo" do
photo = photo_service.visible_photo(@alice_bob_photo.guid)
expect(photo.guid).to eq(@alice_bob_photo.guid)
end
it "returns nil for other user's private photo" do
photo = photo_service.visible_photo(@alice_eve_photo.guid)
expect(photo).to be_nil
end
end
describe "create" do
before do
@image_file = Rack::Test::UploadedFile.new(Rails.root.join("spec", "fixtures", "button.png").to_s, "image/png")
end
context "succeeds" do
it "accepts a photo from a regular form uploaded file no parameters" do
params = ActionController::Parameters.new
photo = photo_service.create_from_params_and_file(params, @image_file)
expect(photo).not_to be_nil
expect(photo.pending?).to be_falsey
expect(photo.public?).to be_falsey
end
it "honors pending" do
params = ActionController::Parameters.new(pending: true)
photo = photo_service.create_from_params_and_file(params, @image_file)
expect(photo).not_to be_nil
expect(photo.pending?).to be_truthy
expect(photo.public?).to be_falsey
end
it "sets a user profile when requested" do
original_profile_pic = bob.person.profile.image_url
params = ActionController::Parameters.new(set_profile_photo: true)
photo = photo_service.create_from_params_and_file(params, @image_file)
expect(photo).not_to be_nil
expect(bob.reload.person.profile.image_url).not_to eq(original_profile_pic)
end
it "has correct aspects settings for limited shared" do
params = ActionController::Parameters.new(pending: false, aspect_ids: [bob.aspects.first.id])
photo = photo_service.create_from_params_and_file(params, @image_file)
expect(photo).not_to be_nil
expect(photo.pending?).to be_falsey
expect(photo.public?).to be_falsey
end
it "allow raw file if explicitly allowing" do
params = ActionController::Parameters.new
photo = photo_service(bob, false).create_from_params_and_file(params, uploaded_photo)
expect(photo).not_to be_nil
end
end
context "fails" do
before do
@params = ActionController::Parameters.new
end
it "fails if given a raw file" do
expect {
photo_service.create_from_params_and_file(@params, uploaded_photo)
}.to raise_error RuntimeError
end
it "file type isn't an image" do
text_file = Rack::Test::UploadedFile.new(Rails.root.join("README.md").to_s, "text/plain")
expect {
photo_service.create_from_params_and_file(@params, text_file)
}.to raise_error CarrierWave::IntegrityError
text_file = Rack::Test::UploadedFile.new(Rails.root.join("README.md").to_s, "image/png")
expect {
photo_service.create_from_params_and_file(@params, text_file)
}.to raise_error CarrierWave::IntegrityError
end
end
end
def photo_service(user=bob, deny_raw_files=true)
PhotoService.new(user, deny_raw_files)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class ConversationService
def initialize(user=nil)
@user = user
end
def all_for_user(filter={})
conversation_filter = {}
unless filter[:only_after].nil?
conversation_filter = \
"conversations.created_at >= ?", filter[:only_after]
end
visibility_filter = if filter[:unread]
{
person_id: @user.person_id,
unread: 1
}
else
{person_id: @user.person_id}
end
Conversation.where(conversation_filter)
.joins(:conversation_visibilities)
.where(conversation_visibilities: visibility_filter)
.all
end
def build(subject, text, recipients)
person_ids = @user.contacts
.mutual
.where(person_id: recipients)
.pluck(:person_id)
opts = {
subject: subject,
message: {text: text},
participant_ids: person_ids
}
@user.build_conversation(opts)
end
def find!(conversation_guid)
conversation = Conversation.find_by!(guid: conversation_guid)
@user.conversations
.joins(:conversation_visibilities)
.where(conversation_visibilities: {
person_id: @user.person_id,
conversation_id: conversation.id
}).first!
end
def destroy!(conversation_guid)
conversation = find!(conversation_guid)
conversation.destroy!
end
def get_visibility(conversation_guid)
conversation = find!(conversation_guid)
ConversationVisibility.where(
person_id: @user.person.id,
conversation_id: conversation.id
).first!
end
end
``` | # frozen_string_literal: true
describe ConversationService do
before do
opts = {
subject: "conversation subject",
message: {text: "conversation text"},
participant_ids: [bob.person.id]
}
@conversation = alice.build_conversation(opts)
@conversation.created_at = 2.hours.ago
@conversation.save!
end
describe "#all_for_user" do
before do
opts = {
subject: "conversation subject 2",
message: {text: "conversation text 2"},
participant_ids: [bob.person.id]
}
@conversation = alice.build_conversation(opts)
@conversation.created_at = 1.hour.ago
@conversation.save!
@date = @conversation.created_at
opts = {
subject: "conversation subject 3",
message: {text: "conversation text 3"},
participant_ids: []
}
@conversation = bob.build_conversation(opts)
@conversation.save!
end
it "returns all conversations" do
expect(alice_conversation_service.all_for_user.length).to eq(2)
expect(bob_conversation_service.all_for_user.length).to eq(3)
end
it "returns all unread conversations" do
@conversation.conversation_visibilities[0].unread = true
@conversation.conversation_visibilities[0].save!
conversations = bob_conversation_service.all_for_user(unread: true)
expect(conversations.length).to eq(1)
end
it "returns conversation after a given date" do
conversations = bob_conversation_service.all_for_user(only_after: @date)
expect(conversations.length).to eq(2)
end
end
describe "#find!" do
it "returns the conversation, if it is the user's conversation" do
expect(bob_conversation_service.find!(@conversation.guid)).to eq(
@conversation
)
end
it "returns the conversation, if the user is recipient" do
expect(bob_conversation_service.find!(@conversation.guid)).to eq(
@conversation
)
end
it "raises RecordNotFound if the conversation cannot be found" do
expect {
alice_conversation_service.find!("unknown")
}.to raise_error ActiveRecord::RecordNotFound
end
it "raises RecordNotFound if the user is not recipient" do
expect {
eve_conversation_service.find!(@conversation.guid)
}.to raise_error ActiveRecord::RecordNotFound
end
end
describe "#build" do
it "creates the conversation for given user and recipients" do
new_conversation = alice_conversation_service.build(
"subject test",
"message test",
[bob.person.id]
)
expect(new_conversation.subject).to eq("subject test")
expect(new_conversation.author_id).to eq(alice.person.id)
expect(new_conversation.messages[0].text).to eq("message test")
expect(new_conversation.messages[0].author_id).to eq(alice.person.id)
expect(new_conversation.participants.length).to eq(2)
end
it "doesn't add recipients if they are not user contacts" do
new_conversation = alice_conversation_service.build(
"subject test",
"message test",
[bob.person.id, eve.person.id]
)
expect(new_conversation.participants.length).to eq(2)
expect(new_conversation.messages[0].text).to eq("message test")
expect(new_conversation.messages[0].author_id).to eq(alice.person.id)
end
end
describe "#get_visibility" do
it "returns visibility for current user" do
visibility = alice_conversation_service.get_visibility(
@conversation.guid
)
expect(visibility).to_not be_nil
end
it "raises RecordNotFound if the user has no visibility" do
expect {
eve_conversation_service.get_visibility(@conversation.id)
}.to raise_error ActiveRecord::RecordNotFound
end
end
describe "#destroy!" do
it "deletes the conversation, when it is the user conversation" do
alice_conversation_service.destroy!(@conversation.guid)
expect {
alice_conversation_service.find!(@conversation.guid)
}.to raise_error ActiveRecord::RecordNotFound
end
it "raises RecordNotFound if the conversation cannot be found" do
expect {
alice_conversation_service.destroy!("unknown")
}.to raise_error ActiveRecord::RecordNotFound
end
it "raises RecordNotFound if the user is not part of the conversation" do
expect {
eve_conversation_service.destroy!(@conversation.guid)
}.to raise_error ActiveRecord::RecordNotFound
end
end
def alice_conversation_service
ConversationService.new(alice)
end
def bob_conversation_service
ConversationService.new(bob)
end
def eve_conversation_service
ConversationService.new(eve)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class CommentService
def initialize(user=nil)
@user = user
end
def create(post_id, text)
post = post_service.find!(post_id)
user.comment!(post, text)
end
def find_for_post(post_id)
post_service.find!(post_id).comments.for_a_stream
end
def find!(id_or_guid)
Comment.find_by!(comment_key(id_or_guid) => id_or_guid)
end
def destroy(comment_id)
comment = Comment.find(comment_id)
if user.owns?(comment) || user.owns?(comment.parent)
user.retract(comment)
true
else
false
end
end
def destroy!(comment_guid)
comment = find!(comment_guid)
if user.owns?(comment)
user.retract(comment)
elsif user.owns?(comment.parent)
user.retract(comment)
elsif comment
raise ActiveRecord::RecordInvalid
else
raise ActiveRecord::RecordNotFound
end
end
private
attr_reader :user
# We can assume a guid is at least 16 characters long as we have guids set to hex(8) since we started using them.
def comment_key(id_or_guid)
id_or_guid.to_s.length < 16 ? :id : :guid
end
def post_service
@post_service ||= PostService.new(user)
end
end
``` | # frozen_string_literal: true
describe CommentService do
let(:post) { alice.post(:status_message, text: "hello", to: alice.aspects.first) }
describe "#create" do
it "creates a comment on my own post" do
comment = CommentService.new(alice).create(post.id, "hi")
expect(comment.text).to eq("hi")
end
it "creates a comment on post of a contact" do
comment = CommentService.new(bob).create(post.id, "hi")
expect(comment.text).to eq("hi")
end
it "attaches the comment to the post" do
comment = CommentService.new(alice).create(post.id, "hi")
expect(post.comments.first.text).to eq("hi")
expect(post.comments.first.id).to eq(comment.id)
end
it "fail if the post does not exist" do
expect {
CommentService.new(alice).create("unknown id", "hi")
}.to raise_error ActiveRecord::RecordNotFound
end
it "fail if the user can not see the post" do
expect {
CommentService.new(eve).create(post.id, "hi")
}.to raise_error ActiveRecord::RecordNotFound
end
end
describe "#find!" do
let(:comment) { CommentService.new(bob).create(post.id, "hi") }
it "returns comment" do
result = CommentService.new(bob).find!(comment.guid)
expect(result.id).to eq(comment.id)
end
it "raises exception the comment does not exist" do
expect {
CommentService.new(bob).find!("unknown id")
}.to raise_error ActiveRecord::RecordNotFound
end
end
describe "#destroy" do
let(:comment) { CommentService.new(bob).create(post.id, "hi") }
it "lets the user destroy his own comment" do
result = CommentService.new(bob).destroy(comment.id)
expect(result).to be_truthy
end
it "lets the parent author destroy others comment" do
result = CommentService.new(alice).destroy(comment.id)
expect(result).to be_truthy
end
it "does not let someone destroy others comment" do
result = CommentService.new(eve).destroy(comment.id)
expect(result).to be_falsey
end
it "fails if the comment does not exist" do
expect {
CommentService.new(bob).destroy("unknown id")
}.to raise_error ActiveRecord::RecordNotFound
end
end
describe "#destroy!" do
let(:comment) { CommentService.new(bob).create(post.id, "hi") }
it "lets the user destroy his own comment" do
result = CommentService.new(bob).destroy!(comment.guid)
expect(result).to be_truthy
end
it "lets the parent author destroy others comment" do
result = CommentService.new(alice).destroy!(comment.guid)
expect(result).to be_truthy
end
it "does not let someone destroy others comment" do
expect {
CommentService.new(eve).destroy!(comment.guid)
}.to raise_error ActiveRecord::RecordInvalid
end
it "raises exception the comment does not exist" do
expect {
CommentService.new(bob).destroy!("unknown id")
}.to raise_error ActiveRecord::RecordNotFound
end
end
describe "#find_for_post" do
context "with user" do
it "returns comments for a public post" do
post = alice.post(:status_message, text: "hello", public: true)
comment = CommentService.new(alice).create(post.id, "hi")
expect(CommentService.new(eve).find_for_post(post.id)).to include(comment)
end
it "returns comments for a visible private post" do
comment = CommentService.new(alice).create(post.id, "hi")
expect(CommentService.new(bob).find_for_post(post.id)).to include(comment)
end
it "does not return comments for private post the user can not see" do
expect {
CommentService.new(eve).find_for_post(post.id)
}.to raise_error ActiveRecord::RecordNotFound
end
end
context "without user" do
it "returns comments for a public post" do
post = alice.post(:status_message, text: "hello", public: true)
comment = CommentService.new(alice).create(post.id, "hi")
expect(CommentService.new.find_for_post(post.id)).to include(comment)
end
it "does not return comments for private post" do
expect {
CommentService.new.find_for_post(post.id)
}.to raise_error Diaspora::NonPublic
end
end
it "returns all comments of a post" do
post = alice.post(:status_message, text: "hello", public: true)
comments = [alice, bob, eve].map {|user| CommentService.new(user).create(post.id, "hi") }
expect(CommentService.new.find_for_post(post.id)).to match_array(comments)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
require 'csv'
# NOTE: This is a deprecated service, only kept to not break ongoing imports
# on upgrade. See `BulkImportService` for its replacement.
class ImportService < BaseService
ROWS_PROCESSING_LIMIT = 20_000
def call(import)
@import = import
@account = @import.account
case @import.type
when 'following'
import_follows!
when 'blocking'
import_blocks!
when 'muting'
import_mutes!
when 'domain_blocking'
import_domain_blocks!
when 'bookmarks'
import_bookmarks!
end
end
private
def import_follows!
parse_import_data!(['Account address'])
import_relationships!('follow', 'unfollow', @account.following, ROWS_PROCESSING_LIMIT, reblogs: { header: 'Show boosts', default: true }, notify: { header: 'Notify on new posts', default: false }, languages: { header: 'Languages', default: nil })
end
def import_blocks!
parse_import_data!(['Account address'])
import_relationships!('block', 'unblock', @account.blocking, ROWS_PROCESSING_LIMIT)
end
def import_mutes!
parse_import_data!(['Account address'])
import_relationships!('mute', 'unmute', @account.muting, ROWS_PROCESSING_LIMIT, notifications: { header: 'Hide notifications', default: true })
end
def import_domain_blocks!
parse_import_data!(['#domain'])
items = @data.take(ROWS_PROCESSING_LIMIT).map { |row| row['#domain'].strip }
if @import.overwrite?
presence_hash = items.index_with(true)
@account.domain_blocks.find_each do |domain_block|
if presence_hash[domain_block.domain]
items.delete(domain_block.domain)
else
@account.unblock_domain!(domain_block.domain)
end
end
end
items.each do |domain|
@account.block_domain!(domain)
end
AfterAccountDomainBlockWorker.push_bulk(items) do |domain|
[@account.id, domain]
end
end
def import_relationships!(action, undo_action, overwrite_scope, limit, extra_fields = {})
local_domain_suffix = "@#{Rails.configuration.x.local_domain}"
items = @data.take(limit).map { |row| [row['Account address']&.strip&.delete_suffix(local_domain_suffix), extra_fields.to_h { |key, field_settings| [key, row[field_settings[:header]]&.strip || field_settings[:default]] }] }.reject { |(id, _)| id.blank? }
if @import.overwrite?
presence_hash = items.each_with_object({}) { |(id, extra), mapping| mapping[id] = [true, extra] }
overwrite_scope.reorder(nil).find_each do |target_account|
if presence_hash[target_account.acct]
items.delete(target_account.acct)
extra = presence_hash[target_account.acct][1]
Import::RelationshipWorker.perform_async(@account.id, target_account.acct, action, extra.stringify_keys)
else
Import::RelationshipWorker.perform_async(@account.id, target_account.acct, undo_action)
end
end
end
head_items = items.uniq { |acct, _| acct.split('@')[1] }
tail_items = items - head_items
Import::RelationshipWorker.push_bulk(head_items + tail_items) do |acct, extra|
[@account.id, acct, action, extra.stringify_keys]
end
end
def import_bookmarks!
parse_import_data!(['#uri'])
items = @data.take(ROWS_PROCESSING_LIMIT).map { |row| row['#uri'].strip }
if @import.overwrite?
presence_hash = items.index_with(true)
@account.bookmarks.find_each do |bookmark|
if presence_hash[bookmark.status.uri]
items.delete(bookmark.status.uri)
else
bookmark.destroy!
end
end
end
statuses = items.filter_map do |uri|
status = ActivityPub::TagManager.instance.uri_to_resource(uri, Status)
next if status.nil? && ActivityPub::TagManager.instance.local_uri?(uri)
status || ActivityPub::FetchRemoteStatusService.new.call(uri)
rescue HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::UnexpectedResponseError
nil
rescue => e
Rails.logger.warn "Unexpected error when importing bookmark: #{e}"
nil
end
account_ids = statuses.map(&:account_id)
preloaded_relations = @account.relations_map(account_ids, skip_blocking_and_muting: true)
statuses.keep_if { |status| StatusPolicy.new(@account, status, preloaded_relations).show? }
statuses.each do |status|
@account.bookmarks.find_or_create_by!(account: @account, status: status)
end
end
def parse_import_data!(default_headers)
data = CSV.parse(import_data, headers: true)
data = CSV.parse(import_data, headers: default_headers) unless data.headers&.first&.strip&.include?(' ')
@data = data.compact_blank
end
def import_data
Paperclip.io_adapters.for(@import.data).read.force_encoding(Encoding::UTF_8)
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe ImportService, type: :service do
include RoutingHelper
let!(:account) { Fabricate(:account, locked: false) }
let!(:bob) { Fabricate(:account, username: 'bob', locked: false) }
let!(:eve) { Fabricate(:account, username: 'eve', domain: 'example.com', locked: false, protocol: :activitypub, inbox_url: 'https://example.com/inbox') }
before do
stub_request(:post, 'https://example.com/inbox').to_return(status: 200)
end
context 'when importing old-style list of muted users' do
subject { described_class.new }
let(:csv) { attachment_fixture('mute-imports.txt') }
describe 'when no accounts are muted' do
let(:import) { Import.create(account: account, type: 'muting', data: csv) }
it 'mutes the listed accounts, including notifications' do
subject.call(import)
expect(account.muting.count).to eq 2
expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true
end
end
describe 'when some accounts are muted and overwrite is not set' do
let(:import) { Import.create(account: account, type: 'muting', data: csv) }
it 'mutes the listed accounts, including notifications' do
account.mute!(bob, notifications: false)
subject.call(import)
expect(account.muting.count).to eq 2
expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true
end
end
describe 'when some accounts are muted and overwrite is set' do
let(:import) { Import.create(account: account, type: 'muting', data: csv, overwrite: true) }
it 'mutes the listed accounts, including notifications' do
account.mute!(bob, notifications: false)
subject.call(import)
expect(account.muting.count).to eq 2
expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true
end
end
end
context 'when importing new-style list of muted users' do
subject { described_class.new }
let(:csv) { attachment_fixture('new-mute-imports.txt') }
describe 'when no accounts are muted' do
let(:import) { Import.create(account: account, type: 'muting', data: csv) }
it 'mutes the listed accounts, respecting notifications' do
subject.call(import)
expect(account.muting.count).to eq 2
expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true
expect(Mute.find_by(account: account, target_account: eve).hide_notifications).to be false
end
end
describe 'when some accounts are muted and overwrite is not set' do
let(:import) { Import.create(account: account, type: 'muting', data: csv) }
it 'mutes the listed accounts, respecting notifications' do
account.mute!(bob, notifications: true)
subject.call(import)
expect(account.muting.count).to eq 2
expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true
expect(Mute.find_by(account: account, target_account: eve).hide_notifications).to be false
end
end
describe 'when some accounts are muted and overwrite is set' do
let(:import) { Import.create(account: account, type: 'muting', data: csv, overwrite: true) }
it 'mutes the listed accounts, respecting notifications' do
account.mute!(bob, notifications: true)
subject.call(import)
expect(account.muting.count).to eq 2
expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true
expect(Mute.find_by(account: account, target_account: eve).hide_notifications).to be false
end
end
end
context 'when importing old-style list of followed users' do
subject { described_class.new }
let(:csv) { attachment_fixture('mute-imports.txt') }
describe 'when no accounts are followed' do
let(:import) { Import.create(account: account, type: 'following', data: csv) }
it 'follows the listed accounts, including boosts' do
subject.call(import)
expect(account.following.count).to eq 1
expect(account.follow_requests.count).to eq 1
expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true
end
end
describe 'when some accounts are already followed and overwrite is not set' do
let(:import) { Import.create(account: account, type: 'following', data: csv) }
it 'follows the listed accounts, including notifications' do
account.follow!(bob, reblogs: false)
subject.call(import)
expect(account.following.count).to eq 1
expect(account.follow_requests.count).to eq 1
expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true
end
end
describe 'when some accounts are already followed and overwrite is set' do
let(:import) { Import.create(account: account, type: 'following', data: csv, overwrite: true) }
it 'mutes the listed accounts, including notifications' do
account.follow!(bob, reblogs: false)
subject.call(import)
expect(account.following.count).to eq 1
expect(account.follow_requests.count).to eq 1
expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true
end
end
end
context 'when importing new-style list of followed users' do
subject { described_class.new }
let(:csv) { attachment_fixture('new-following-imports.txt') }
describe 'when no accounts are followed' do
let(:import) { Import.create(account: account, type: 'following', data: csv) }
it 'follows the listed accounts, respecting boosts' do
subject.call(import)
expect(account.following.count).to eq 1
expect(account.follow_requests.count).to eq 1
expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true
expect(FollowRequest.find_by(account: account, target_account: eve).show_reblogs).to be false
end
end
describe 'when some accounts are already followed and overwrite is not set' do
let(:import) { Import.create(account: account, type: 'following', data: csv) }
it 'mutes the listed accounts, respecting notifications' do
account.follow!(bob, reblogs: true)
subject.call(import)
expect(account.following.count).to eq 1
expect(account.follow_requests.count).to eq 1
expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true
expect(FollowRequest.find_by(account: account, target_account: eve).show_reblogs).to be false
end
end
describe 'when some accounts are already followed and overwrite is set' do
let(:import) { Import.create(account: account, type: 'following', data: csv, overwrite: true) }
it 'mutes the listed accounts, respecting notifications' do
account.follow!(bob, reblogs: true)
subject.call(import)
expect(account.following.count).to eq 1
expect(account.follow_requests.count).to eq 1
expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true
expect(FollowRequest.find_by(account: account, target_account: eve).show_reblogs).to be false
end
end
end
# Based on the bug report 20571 where UTF-8 encoded domains were rejecting import of their users
#
# https://github.com/mastodon/mastodon/issues/20571
context 'with a utf-8 encoded domains' do
subject { described_class.new }
let!(:nare) { Fabricate(:account, username: 'nare', domain: 'թութ.հայ', locked: false, protocol: :activitypub, inbox_url: 'https://թութ.հայ/inbox') }
let(:csv) { attachment_fixture('utf8-followers.txt') }
let(:import) { Import.create(account: account, type: 'following', data: csv) }
# Make sure to not actually go to the remote server
before do
stub_request(:post, 'https://թութ.հայ/inbox').to_return(status: 200)
end
it 'follows the listed account' do
expect(account.follow_requests.count).to eq 0
subject.call(import)
expect(account.follow_requests.count).to eq 1
end
end
context 'when importing bookmarks' do
subject { described_class.new }
let(:csv) { attachment_fixture('bookmark-imports.txt') }
let(:local_account) { Fabricate(:account, username: 'foo', domain: '') }
let!(:remote_status) { Fabricate(:status, uri: 'https://example.com/statuses/1312') }
let!(:direct_status) { Fabricate(:status, uri: 'https://example.com/statuses/direct', visibility: :direct) }
around do |example|
local_before = Rails.configuration.x.local_domain
web_before = Rails.configuration.x.web_domain
Rails.configuration.x.local_domain = 'local.com'
Rails.configuration.x.web_domain = 'local.com'
example.run
Rails.configuration.x.web_domain = web_before
Rails.configuration.x.local_domain = local_before
end
before do
service = instance_double(ActivityPub::FetchRemoteStatusService)
allow(ActivityPub::FetchRemoteStatusService).to receive(:new).and_return(service)
allow(service).to receive(:call).with('https://unknown-remote.com/users/bar/statuses/1') do
Fabricate(:status, uri: 'https://unknown-remote.com/users/bar/statuses/1')
end
end
describe 'when no bookmarks are set' do
let(:import) { Import.create(account: account, type: 'bookmarks', data: csv) }
it 'adds the toots the user has access to to bookmarks' do
local_status = Fabricate(:status, account: local_account, uri: 'https://local.com/users/foo/statuses/42', id: 42, local: true)
subject.call(import)
expect(account.bookmarks.map { |bookmark| bookmark.status.id }).to include(local_status.id)
expect(account.bookmarks.map { |bookmark| bookmark.status.id }).to include(remote_status.id)
expect(account.bookmarks.map { |bookmark| bookmark.status.id }).to_not include(direct_status.id)
expect(account.bookmarks.count).to eq 3
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class AuthorizeFollowService < BaseService
include Payloadable
def call(source_account, target_account, **options)
if options[:skip_follow_request]
follow_request = FollowRequest.new(account: source_account, target_account: target_account, uri: options[:follow_request_uri])
else
follow_request = FollowRequest.find_by!(account: source_account, target_account: target_account)
follow_request.authorize!
end
create_notification(follow_request) if !source_account.local? && source_account.activitypub?
follow_request
end
private
def create_notification(follow_request)
ActivityPub::DeliveryWorker.perform_async(build_json(follow_request), follow_request.target_account_id, follow_request.account.inbox_url)
end
def build_json(follow_request)
Oj.dump(serialize_payload(follow_request, ActivityPub::AcceptFollowSerializer))
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe AuthorizeFollowService, type: :service do
subject { described_class.new }
let(:sender) { Fabricate(:account, username: 'alice') }
describe 'local' do
let(:bob) { Fabricate(:account, username: 'bob') }
before do
FollowRequest.create(account: bob, target_account: sender)
subject.call(bob, sender)
end
it 'removes follow request' do
expect(bob.requested?(sender)).to be false
end
it 'creates follow relation' do
expect(bob.following?(sender)).to be true
end
end
describe 'remote ActivityPub' do
let(:bob) { Fabricate(:account, username: 'bob', domain: 'example.com', protocol: :activitypub, inbox_url: 'http://example.com/inbox') }
before do
FollowRequest.create(account: bob, target_account: sender)
stub_request(:post, bob.inbox_url).to_return(status: 200)
subject.call(bob, sender)
end
it 'removes follow request' do
expect(bob.requested?(sender)).to be false
end
it 'creates follow relation' do
expect(bob.following?(sender)).to be true
end
it 'sends an accept activity' do
expect(a_request(:post, bob.inbox_url)).to have_been_made.once
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class PrecomputeFeedService < BaseService
include Redisable
def call(account)
FeedManager.instance.populate_home(account)
ensure
redis.del("account:#{account.id}:regeneration")
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe PrecomputeFeedService, type: :service do
subject { described_class.new }
describe 'call' do
let(:account) { Fabricate(:account) }
it 'fills a user timeline with statuses' do
account = Fabricate(:account)
status = Fabricate(:status, account: account)
subject.call(account)
expect(redis.zscore(FeedManager.instance.key(:home, account.id), status.id)).to be_within(0.1).of(status.id.to_f)
end
it 'does not raise an error even if it could not find any status' do
account = Fabricate(:account)
expect { subject.call(account) }.to_not raise_error
end
it 'filters statuses' do
account = Fabricate(:account)
muted_account = Fabricate(:account)
Fabricate(:mute, account: account, target_account: muted_account)
reblog = Fabricate(:status, account: muted_account)
Fabricate(:status, account: account, reblog: reblog)
subject.call(account)
expect(redis.zscore(FeedManager.instance.key(:home, account.id), reblog.id)).to be_nil
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class PostStatusService < BaseService
include Redisable
include LanguagesHelper
MIN_SCHEDULE_OFFSET = 5.minutes.freeze
class UnexpectedMentionsError < StandardError
attr_reader :accounts
def initialize(message, accounts)
super(message)
@accounts = accounts
end
end
# Post a text status update, fetch and notify remote users mentioned
# @param [Account] account Account from which to post
# @param [Hash] options
# @option [String] :text Message
# @option [Status] :thread Optional status to reply to
# @option [Boolean] :sensitive
# @option [String] :visibility
# @option [String] :spoiler_text
# @option [String] :language
# @option [String] :scheduled_at
# @option [Hash] :poll Optional poll to attach
# @option [Enumerable] :media_ids Optional array of media IDs to attach
# @option [Doorkeeper::Application] :application
# @option [String] :idempotency Optional idempotency key
# @option [Boolean] :with_rate_limit
# @option [Enumerable] :allowed_mentions Optional array of expected mentioned account IDs, raises `UnexpectedMentionsError` if unexpected accounts end up in mentions
# @return [Status]
def call(account, options = {})
@account = account
@options = options
@text = @options[:text] || ''
@in_reply_to = @options[:thread]
return idempotency_duplicate if idempotency_given? && idempotency_duplicate?
validate_media!
preprocess_attributes!
if scheduled?
schedule_status!
else
process_status!
end
redis.setex(idempotency_key, 3_600, @status.id) if idempotency_given?
unless scheduled?
postprocess_status!
bump_potential_friendship!
end
@status
end
private
def preprocess_attributes!
@sensitive = (@options[:sensitive].nil? ? @account.user&.setting_default_sensitive : @options[:sensitive]) || @options[:spoiler_text].present?
@text = @options.delete(:spoiler_text) if @text.blank? && @options[:spoiler_text].present?
@visibility = @options[:visibility] || @account.user&.setting_default_privacy
@visibility = :unlisted if @visibility&.to_sym == :public && @account.silenced?
@scheduled_at = @options[:scheduled_at]&.to_datetime
@scheduled_at = nil if scheduled_in_the_past?
rescue ArgumentError
raise ActiveRecord::RecordInvalid
end
def process_status!
@status = @account.statuses.new(status_attributes)
process_mentions_service.call(@status, save_records: false)
safeguard_mentions!(@status)
# The following transaction block is needed to wrap the UPDATEs to
# the media attachments when the status is created
ApplicationRecord.transaction do
@status.save!
end
end
def safeguard_mentions!(status)
return if @options[:allowed_mentions].nil?
expected_account_ids = @options[:allowed_mentions].map(&:to_i)
unexpected_accounts = status.mentions.map(&:account).to_a.reject { |mentioned_account| expected_account_ids.include?(mentioned_account.id) }
return if unexpected_accounts.empty?
raise UnexpectedMentionsError.new('Post would be sent to unexpected accounts', unexpected_accounts)
end
def schedule_status!
status_for_validation = @account.statuses.build(status_attributes)
if status_for_validation.valid?
# Marking the status as destroyed is necessary to prevent the status from being
# persisted when the associated media attachments get updated when creating the
# scheduled status.
status_for_validation.destroy
# The following transaction block is needed to wrap the UPDATEs to
# the media attachments when the scheduled status is created
ApplicationRecord.transaction do
@status = @account.scheduled_statuses.create!(scheduled_status_attributes)
end
else
raise ActiveRecord::RecordInvalid
end
end
def postprocess_status!
process_hashtags_service.call(@status)
Trends.tags.register(@status)
LinkCrawlWorker.perform_async(@status.id)
DistributionWorker.perform_async(@status.id)
ActivityPub::DistributionWorker.perform_async(@status.id)
PollExpirationNotifyWorker.perform_at(@status.poll.expires_at, @status.poll.id) if @status.poll
end
def validate_media!
if @options[:media_ids].blank? || !@options[:media_ids].is_a?(Enumerable)
@media = []
return
end
raise Mastodon::ValidationError, I18n.t('media_attachments.validations.too_many') if @options[:media_ids].size > 4 || @options[:poll].present?
@media = @account.media_attachments.where(status_id: nil).where(id: @options[:media_ids].take(4).map(&:to_i))
raise Mastodon::ValidationError, I18n.t('media_attachments.validations.images_and_video') if @media.size > 1 && @media.find(&:audio_or_video?)
raise Mastodon::ValidationError, I18n.t('media_attachments.validations.not_ready') if @media.any?(&:not_processed?)
end
def process_mentions_service
ProcessMentionsService.new
end
def process_hashtags_service
ProcessHashtagsService.new
end
def scheduled?
@scheduled_at.present?
end
def idempotency_key
"idempotency:status:#{@account.id}:#{@options[:idempotency]}"
end
def idempotency_given?
@options[:idempotency].present?
end
def idempotency_duplicate
if scheduled?
@account.schedule_statuses.find(@idempotency_duplicate)
else
@account.statuses.find(@idempotency_duplicate)
end
end
def idempotency_duplicate?
@idempotency_duplicate = redis.get(idempotency_key)
end
def scheduled_in_the_past?
@scheduled_at.present? && @scheduled_at <= Time.now.utc + MIN_SCHEDULE_OFFSET
end
def bump_potential_friendship!
return if [email protected]? || @account.id == @status.in_reply_to_account_id
ActivityTracker.increment('activity:interactions')
return if @account.following?(@status.in_reply_to_account_id)
PotentialFriendshipTracker.record(@account.id, @status.in_reply_to_account_id, :reply)
end
def status_attributes
{
text: @text,
media_attachments: @media || [],
ordered_media_attachment_ids: (@options[:media_ids] || []).map(&:to_i) & @media.map(&:id),
thread: @in_reply_to,
poll_attributes: poll_attributes,
sensitive: @sensitive,
spoiler_text: @options[:spoiler_text] || '',
visibility: @visibility,
language: valid_locale_cascade(@options[:language], @account.user&.preferred_posting_language, I18n.default_locale),
application: @options[:application],
rate_limit: @options[:with_rate_limit],
}.compact
end
def scheduled_status_attributes
{
scheduled_at: @scheduled_at,
media_attachments: @media || [],
params: scheduled_options,
}
end
def poll_attributes
return if @options[:poll].blank?
@options[:poll].merge(account: @account, voters_count: 0)
end
def scheduled_options
@options.tap do |options_hash|
options_hash[:in_reply_to_id] = options_hash.delete(:thread)&.id
options_hash[:application_id] = options_hash.delete(:application)&.id
options_hash[:scheduled_at] = nil
options_hash[:idempotency] = nil
options_hash[:with_rate_limit] = false
end
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe PostStatusService, type: :service do
subject { described_class.new }
it 'creates a new status' do
account = Fabricate(:account)
text = 'test status update'
status = subject.call(account, text: text)
expect(status).to be_persisted
expect(status.text).to eq text
end
it 'creates a new response status' do
in_reply_to_status = Fabricate(:status)
account = Fabricate(:account)
text = 'test status update'
status = subject.call(account, text: text, thread: in_reply_to_status)
expect(status).to be_persisted
expect(status.text).to eq text
expect(status.thread).to eq in_reply_to_status
end
context 'when scheduling a status' do
let!(:account) { Fabricate(:account) }
let!(:future) { Time.now.utc + 2.hours }
let!(:previous_status) { Fabricate(:status, account: account) }
it 'schedules a status' do
status = subject.call(account, text: 'Hi future!', scheduled_at: future)
expect(status).to be_a ScheduledStatus
expect(status.scheduled_at).to eq future
expect(status.params['text']).to eq 'Hi future!'
end
it 'does not immediately create a status' do
media = Fabricate(:media_attachment, account: account)
status = subject.call(account, text: 'Hi future!', media_ids: [media.id], scheduled_at: future)
expect(status).to be_a ScheduledStatus
expect(status.scheduled_at).to eq future
expect(status.params['text']).to eq 'Hi future!'
expect(status.params['media_ids']).to eq [media.id]
expect(media.reload.status).to be_nil
expect(Status.where(text: 'Hi future!')).to_not exist
end
it 'does not change statuses count' do
expect { subject.call(account, text: 'Hi future!', scheduled_at: future, thread: previous_status) }.to_not(change { [account.statuses_count, previous_status.replies_count] })
end
end
it 'creates response to the original status of boost' do
boosted_status = Fabricate(:status)
in_reply_to_status = Fabricate(:status, reblog: boosted_status)
account = Fabricate(:account)
text = 'test status update'
status = subject.call(account, text: text, thread: in_reply_to_status)
expect(status).to be_persisted
expect(status.text).to eq text
expect(status.thread).to eq boosted_status
end
it 'creates a sensitive status' do
status = create_status_with_options(sensitive: true)
expect(status).to be_persisted
expect(status).to be_sensitive
end
it 'creates a status with spoiler text' do
spoiler_text = 'spoiler text'
status = create_status_with_options(spoiler_text: spoiler_text)
expect(status).to be_persisted
expect(status.spoiler_text).to eq spoiler_text
end
it 'creates a sensitive status when there is a CW but no text' do
status = subject.call(Fabricate(:account), text: '', spoiler_text: 'foo')
expect(status).to be_persisted
expect(status).to be_sensitive
end
it 'creates a status with empty default spoiler text' do
status = create_status_with_options(spoiler_text: nil)
expect(status).to be_persisted
expect(status.spoiler_text).to eq ''
end
it 'creates a status with the given visibility' do
status = create_status_with_options(visibility: :private)
expect(status).to be_persisted
expect(status.visibility).to eq 'private'
end
it 'creates a status with limited visibility for silenced users' do
status = subject.call(Fabricate(:account, silenced: true), text: 'test', visibility: :public)
expect(status).to be_persisted
expect(status.visibility).to eq 'unlisted'
end
it 'creates a status for the given application' do
application = Fabricate(:application)
status = create_status_with_options(application: application)
expect(status).to be_persisted
expect(status.application).to eq application
end
it 'creates a status with a language set' do
account = Fabricate(:account)
text = 'This is an English text.'
status = subject.call(account, text: text)
expect(status.language).to eq 'en'
end
it 'processes mentions' do
mention_service = instance_double(ProcessMentionsService)
allow(mention_service).to receive(:call)
allow(ProcessMentionsService).to receive(:new).and_return(mention_service)
account = Fabricate(:account)
status = subject.call(account, text: 'test status update')
expect(ProcessMentionsService).to have_received(:new)
expect(mention_service).to have_received(:call).with(status, save_records: false)
end
it 'safeguards mentions' do
account = Fabricate(:account)
mentioned_account = Fabricate(:account, username: 'alice')
unexpected_mentioned_account = Fabricate(:account, username: 'bob')
expect do
subject.call(account, text: '@alice hm, @bob is really annoying lately', allowed_mentions: [mentioned_account.id])
end.to raise_error(an_instance_of(PostStatusService::UnexpectedMentionsError).and(having_attributes(accounts: [unexpected_mentioned_account])))
end
it 'processes duplicate mentions correctly' do
account = Fabricate(:account)
Fabricate(:account, username: 'alice')
expect do
subject.call(account, text: '@alice @alice @alice hey @alice')
end.to_not raise_error
end
it 'processes hashtags' do
hashtags_service = instance_double(ProcessHashtagsService)
allow(hashtags_service).to receive(:call)
allow(ProcessHashtagsService).to receive(:new).and_return(hashtags_service)
account = Fabricate(:account)
status = subject.call(account, text: 'test status update')
expect(ProcessHashtagsService).to have_received(:new)
expect(hashtags_service).to have_received(:call).with(status)
end
it 'gets distributed' do
allow(DistributionWorker).to receive(:perform_async)
allow(ActivityPub::DistributionWorker).to receive(:perform_async)
account = Fabricate(:account)
status = subject.call(account, text: 'test status update')
expect(DistributionWorker).to have_received(:perform_async).with(status.id)
expect(ActivityPub::DistributionWorker).to have_received(:perform_async).with(status.id)
end
it 'crawls links' do
allow(LinkCrawlWorker).to receive(:perform_async)
account = Fabricate(:account)
status = subject.call(account, text: 'test status update')
expect(LinkCrawlWorker).to have_received(:perform_async).with(status.id)
end
it 'attaches the given media to the created status' do
account = Fabricate(:account)
media = Fabricate(:media_attachment, account: account)
status = subject.call(
account,
text: 'test status update',
media_ids: [media.id]
)
expect(media.reload.status).to eq status
end
it 'does not attach media from another account to the created status' do
account = Fabricate(:account)
media = Fabricate(:media_attachment, account: Fabricate(:account))
subject.call(
account,
text: 'test status update',
media_ids: [media.id]
)
expect(media.reload.status).to be_nil
end
it 'does not allow attaching more than 4 files' do
account = Fabricate(:account)
expect do
subject.call(
account,
text: 'test status update',
media_ids: [
Fabricate(:media_attachment, account: account),
Fabricate(:media_attachment, account: account),
Fabricate(:media_attachment, account: account),
Fabricate(:media_attachment, account: account),
Fabricate(:media_attachment, account: account),
].map(&:id)
)
end.to raise_error(
Mastodon::ValidationError,
I18n.t('media_attachments.validations.too_many')
)
end
it 'does not allow attaching both videos and images' do
account = Fabricate(:account)
video = Fabricate(:media_attachment, type: :video, account: account)
image = Fabricate(:media_attachment, type: :image, account: account)
video.update(type: :video)
expect do
subject.call(
account,
text: 'test status update',
media_ids: [
video,
image,
].map(&:id)
)
end.to raise_error(
Mastodon::ValidationError,
I18n.t('media_attachments.validations.images_and_video')
)
end
it 'returns existing status when used twice with idempotency key' do
account = Fabricate(:account)
status1 = subject.call(account, text: 'test', idempotency: 'meepmeep')
status2 = subject.call(account, text: 'test', idempotency: 'meepmeep')
expect(status2.id).to eq status1.id
end
def create_status_with_options(**options)
subject.call(Fabricate(:account), options.merge(text: 'test'))
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class AccountSearchService < BaseService
attr_reader :query, :limit, :offset, :options, :account
MENTION_ONLY_RE = /\A#{Account::MENTION_RE}\z/i
# Min. number of characters to look for non-exact matches
MIN_QUERY_LENGTH = 5
class QueryBuilder
def initialize(query, account, options = {})
@query = query
@account = account
@options = options
end
def build
AccountsIndex.query(
bool: {
must: {
function_score: {
query: {
bool: {
must: must_clauses,
},
},
functions: [
reputation_score_function,
followers_score_function,
time_distance_function,
],
},
},
should: should_clauses,
}
)
end
private
def must_clauses
if @account && @options[:following]
[core_query, only_following_query]
else
[core_query]
end
end
def should_clauses
if @account && !@options[:following]
[boost_following_query]
else
[]
end
end
# This function limits results to only the accounts the user is following
def only_following_query
{
terms: {
id: following_ids,
},
}
end
# This function promotes accounts the user is following
def boost_following_query
{
terms: {
id: following_ids,
boost: 100,
},
}
end
# This function deranks accounts that follow more people than follow them
def reputation_score_function
{
script_score: {
script: {
source: "(Math.max(doc['followers_count'].value, 0) + 0.0) / (Math.max(doc['followers_count'].value, 0) + Math.max(doc['following_count'].value, 0) + 1)",
},
},
}
end
# This function promotes accounts that have more followers
def followers_score_function
{
script_score: {
script: {
source: "(Math.max(doc['followers_count'].value, 0) / (Math.max(doc['followers_count'].value, 0) + 1))",
},
},
}
end
# This function deranks accounts that haven't posted in a long time
def time_distance_function
{
gauss: {
last_status_at: {
scale: '30d',
offset: '30d',
decay: 0.3,
},
},
}
end
def following_ids
@following_ids ||= @account.active_relationships.pluck(:target_account_id) + [@account.id]
end
end
class AutocompleteQueryBuilder < QueryBuilder
private
def core_query
{
multi_match: {
query: @query,
type: 'bool_prefix',
fields: %w(username^2 username.*^2 display_name display_name.*),
},
}
end
end
class FullQueryBuilder < QueryBuilder
private
def core_query
{
multi_match: {
query: @query,
type: 'most_fields',
fields: %w(username^2 display_name^2 text text.*),
operator: 'and',
},
}
end
end
def call(query, account = nil, options = {})
@query = query&.strip&.gsub(/\A@/, '')
@limit = options[:limit].to_i
@offset = options[:offset].to_i
@options = options
@account = account
search_service_results.compact.uniq
end
private
def search_service_results
return [] if query.blank? || limit < 1
[exact_match] + search_results
end
def exact_match
return unless offset.zero? && username_complete?
return @exact_match if defined?(@exact_match)
match = if options[:resolve]
ResolveAccountService.new.call(query)
elsif domain_is_local?
Account.find_local(query_username)
else
Account.find_remote(query_username, query_domain)
end
match = nil if !match.nil? && !account.nil? && options[:following] && !account.following?(match)
@exact_match = match
end
def search_results
return [] if limit_for_non_exact_results.zero?
@search_results ||= begin
results = from_elasticsearch if Chewy.enabled?
results ||= from_database
results
end
end
def from_database
if account
advanced_search_results
else
simple_search_results
end
end
def advanced_search_results
Account.advanced_search_for(terms_for_query, account, limit: limit_for_non_exact_results, following: options[:following], offset: offset)
end
def simple_search_results
Account.search_for(terms_for_query, limit: limit_for_non_exact_results, offset: offset)
end
def from_elasticsearch
query_builder = begin
if options[:use_searchable_text]
FullQueryBuilder.new(terms_for_query, account, options.slice(:following))
else
AutocompleteQueryBuilder.new(terms_for_query, account, options.slice(:following))
end
end
records = query_builder.build.limit(limit_for_non_exact_results).offset(offset).objects.compact
ActiveRecord::Associations::Preloader.new(records: records, associations: :account_stat)
records
rescue Faraday::ConnectionFailed, Parslet::ParseFailed
nil
end
def limit_for_non_exact_results
return 0 if @account.nil? && query.size < MIN_QUERY_LENGTH
if exact_match?
limit - 1
else
limit
end
end
def terms_for_query
if domain_is_local?
query_username
else
query
end
end
def split_query_string
@split_query_string ||= query.split('@')
end
def query_username
@query_username ||= split_query_string.first || ''
end
def query_domain
@query_domain ||= query_without_split? ? nil : split_query_string.last
end
def query_without_split?
split_query_string.size == 1
end
def domain_is_local?
@domain_is_local ||= TagManager.instance.local_domain?(query_domain)
end
def exact_match?
exact_match.present?
end
def username_complete?
query.include?('@') && "@#{query}".match?(MENTION_ONLY_RE)
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
describe AccountSearchService, type: :service do
describe '#call' do
context 'with a query to ignore' do
it 'returns empty array for missing query' do
results = subject.call('', nil, limit: 10)
expect(results).to eq []
end
it 'returns empty array for limit zero' do
Fabricate(:account, username: 'match')
results = subject.call('match', nil, limit: 0)
expect(results).to eq []
end
end
context 'when searching for a simple term that is not an exact match' do
it 'does not return a nil entry in the array for the exact match' do
account = Fabricate(:account, username: 'matchingusername')
results = subject.call('match', nil, limit: 5)
expect(results).to eq [account]
end
end
context 'when there is a local domain' do
around do |example|
before = Rails.configuration.x.local_domain
example.run
Rails.configuration.x.local_domain = before
end
it 'returns exact match first' do
remote = Fabricate(:account, username: 'a', domain: 'remote', display_name: 'e')
remote_too = Fabricate(:account, username: 'b', domain: 'remote', display_name: 'e')
exact = Fabricate(:account, username: 'e')
Rails.configuration.x.local_domain = 'example.com'
results = subject.call('[email protected]', nil, limit: 2)
expect(results).to eq([exact, remote]).or eq([exact, remote_too])
end
end
context 'when there is a domain but no exact match' do
it 'follows the remote account when resolve is true' do
service = instance_double(ResolveAccountService, call: nil)
allow(ResolveAccountService).to receive(:new).and_return(service)
subject.call('[email protected]', nil, limit: 10, resolve: true)
expect(service).to have_received(:call).with('[email protected]')
end
it 'does not follow the remote account when resolve is false' do
service = instance_double(ResolveAccountService, call: nil)
allow(ResolveAccountService).to receive(:new).and_return(service)
subject.call('[email protected]', nil, limit: 10, resolve: false)
expect(service).to_not have_received(:call)
end
end
it 'returns the fuzzy match first, and does not return suspended exacts' do
partial = Fabricate(:account, username: 'exactness')
Fabricate(:account, username: 'exact', suspended: true)
results = subject.call('exact', nil, limit: 10)
expect(results.size).to eq 1
expect(results).to eq [partial]
end
it 'does not return suspended remote accounts' do
Fabricate(:account, username: 'a', domain: 'remote', display_name: 'e', suspended: true)
results = subject.call('[email protected]', nil, limit: 2)
expect(results.size).to eq 0
expect(results).to eq []
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class SoftwareUpdateCheckService < BaseService
def call
clean_outdated_updates!
return unless SoftwareUpdate.check_enabled?
process_update_notices!(fetch_update_notices)
end
private
def clean_outdated_updates!
SoftwareUpdate.find_each do |software_update|
software_update.delete if Mastodon::Version.gem_version >= software_update.gem_version
rescue ArgumentError
software_update.delete
end
end
def fetch_update_notices
Request.new(:get, "#{api_url}?version=#{version}").add_headers('Accept' => 'application/json', 'User-Agent' => 'Mastodon update checker').perform do |res|
return Oj.load(res.body_with_limit, mode: :strict) if res.code == 200
end
rescue HTTP::Error, OpenSSL::SSL::SSLError, Oj::ParseError
nil
end
def api_url
ENV.fetch('UPDATE_CHECK_URL', 'https://api.joinmastodon.org/update-check')
end
def version
@version ||= Mastodon::Version.to_s.split('+')[0]
end
def process_update_notices!(update_notices)
return if update_notices.blank? || update_notices['updatesAvailable'].nil?
# Clear notices that are not listed by the update server anymore
SoftwareUpdate.where.not(version: update_notices['updatesAvailable'].pluck('version')).delete_all
return if update_notices['updatesAvailable'].blank?
# Check if any of the notices is new, and issue notifications
known_versions = SoftwareUpdate.where(version: update_notices['updatesAvailable'].pluck('version')).pluck(:version)
new_update_notices = update_notices['updatesAvailable'].filter { |notice| known_versions.exclude?(notice['version']) }
return if new_update_notices.blank?
new_updates = new_update_notices.map do |notice|
SoftwareUpdate.create!(version: notice['version'], urgent: notice['urgent'], type: notice['type'], release_notes: notice['releaseNotes'])
end
notify_devops!(new_updates)
end
def should_notify_user?(user, urgent_version, patch_version)
case user.settings['notification_emails.software_updates']
when 'none'
false
when 'critical'
urgent_version
when 'patch'
urgent_version || patch_version
when 'all'
true
end
end
def notify_devops!(new_updates)
has_new_urgent_version = new_updates.any?(&:urgent?)
has_new_patch_version = new_updates.any?(&:patch_type?)
User.those_who_can(:view_devops).includes(:account).find_each do |user|
next unless should_notify_user?(user, has_new_urgent_version, has_new_patch_version)
if has_new_urgent_version
AdminMailer.with(recipient: user.account).new_critical_software_updates.deliver_later
else
AdminMailer.with(recipient: user.account).new_software_updates.deliver_later
end
end
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe SoftwareUpdateCheckService, type: :service do
subject { described_class.new }
shared_examples 'when the feature is enabled' do
let(:full_update_check_url) { "#{update_check_url}?version=#{Mastodon::Version.to_s.split('+')[0]}" }
let(:devops_role) { Fabricate(:user_role, name: 'DevOps', permissions: UserRole::FLAGS[:view_devops]) }
let(:owner_user) { Fabricate(:user, role: UserRole.find_by(name: 'Owner')) }
let(:old_devops_user) { Fabricate(:user) }
let(:none_user) { Fabricate(:user, role: devops_role) }
let(:patch_user) { Fabricate(:user, role: devops_role) }
let(:critical_user) { Fabricate(:user, role: devops_role) }
around do |example|
queue_adapter = ActiveJob::Base.queue_adapter
ActiveJob::Base.queue_adapter = :test
example.run
ActiveJob::Base.queue_adapter = queue_adapter
end
before do
Fabricate(:software_update, version: '3.5.0', type: 'major', urgent: false)
Fabricate(:software_update, version: '42.13.12', type: 'major', urgent: false)
owner_user.settings.update('notification_emails.software_updates': 'all')
owner_user.save!
old_devops_user.settings.update('notification_emails.software_updates': 'all')
old_devops_user.save!
none_user.settings.update('notification_emails.software_updates': 'none')
none_user.save!
patch_user.settings.update('notification_emails.software_updates': 'patch')
patch_user.save!
critical_user.settings.update('notification_emails.software_updates': 'critical')
critical_user.save!
end
context 'when the update server errors out' do
before do
stub_request(:get, full_update_check_url).to_return(status: 404)
end
it 'deletes outdated update records but keeps valid update records' do
expect { subject.call }.to change { SoftwareUpdate.pluck(:version).sort }.from(['3.5.0', '42.13.12']).to(['42.13.12'])
end
end
context 'when the server returns new versions' do
let(:server_json) do
{
updatesAvailable: [
{
version: '4.2.1',
urgent: false,
type: 'patch',
releaseNotes: 'https://github.com/mastodon/mastodon/releases/v4.2.1',
},
{
version: '4.3.0',
urgent: false,
type: 'minor',
releaseNotes: 'https://github.com/mastodon/mastodon/releases/v4.3.0',
},
{
version: '5.0.0',
urgent: false,
type: 'minor',
releaseNotes: 'https://github.com/mastodon/mastodon/releases/v5.0.0',
},
],
}
end
before do
stub_request(:get, full_update_check_url).to_return(body: Oj.dump(server_json))
end
it 'updates the list of known updates' do
expect { subject.call }.to change { SoftwareUpdate.pluck(:version).sort }.from(['3.5.0', '42.13.12']).to(['4.2.1', '4.3.0', '5.0.0'])
end
context 'when no update is urgent' do
it 'sends e-mail notifications according to settings', :aggregate_failures do
expect { subject.call }.to have_enqueued_mail(AdminMailer, :new_software_updates)
.with(hash_including(params: { recipient: owner_user.account })).once
.and(have_enqueued_mail(AdminMailer, :new_software_updates).with(hash_including(params: { recipient: patch_user.account })).once)
.and(have_enqueued_mail.at_most(2))
end
end
context 'when an update is urgent' do
let(:server_json) do
{
updatesAvailable: [
{
version: '5.0.0',
urgent: true,
type: 'minor',
releaseNotes: 'https://github.com/mastodon/mastodon/releases/v5.0.0',
},
],
}
end
it 'sends e-mail notifications according to settings', :aggregate_failures do
expect { subject.call }.to have_enqueued_mail(AdminMailer, :new_critical_software_updates)
.with(hash_including(params: { recipient: owner_user.account })).once
.and(have_enqueued_mail(AdminMailer, :new_critical_software_updates).with(hash_including(params: { recipient: patch_user.account })).once)
.and(have_enqueued_mail(AdminMailer, :new_critical_software_updates).with(hash_including(params: { recipient: critical_user.account })).once)
.and(have_enqueued_mail.at_most(3))
end
end
end
end
context 'when update checking is disabled' do
around do |example|
ClimateControl.modify UPDATE_CHECK_URL: '' do
example.run
end
end
before do
Fabricate(:software_update, version: '3.5.0', type: 'major', urgent: false)
end
it 'deletes outdated update records' do
expect { subject.call }.to change(SoftwareUpdate, :count).from(1).to(0)
end
end
context 'when using the default update checking API' do
let(:update_check_url) { 'https://api.joinmastodon.org/update-check' }
it_behaves_like 'when the feature is enabled'
end
context 'when using a custom update check URL' do
let(:update_check_url) { 'https://api.example.com/update_check' }
around do |example|
ClimateControl.modify UPDATE_CHECK_URL: 'https://api.example.com/update_check' do
example.run
end
end
it_behaves_like 'when the feature is enabled'
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class UnsuspendAccountService < BaseService
include Payloadable
# Restores a recently-unsuspended account
# @param [Account] account Account to restore
def call(account)
@account = account
refresh_remote_account!
return if @account.nil? || @account.suspended?
merge_into_home_timelines!
merge_into_list_timelines!
publish_media_attachments!
distribute_update_actor!
end
private
def refresh_remote_account!
return if @account.local?
# While we had the remote account suspended, it could be that
# it got suspended on its origin, too. So, we need to refresh
# it straight away so it gets marked as remotely suspended in
# that case.
@account.update!(last_webfingered_at: nil)
@account = ResolveAccountService.new.call(@account)
# Worth noting that it is possible that the remote has not only
# been suspended, but deleted permanently, in which case
# @account would now be nil.
end
def distribute_update_actor!
return unless @account.local?
account_reach_finder = AccountReachFinder.new(@account)
ActivityPub::DeliveryWorker.push_bulk(account_reach_finder.inboxes, limit: 1_000) do |inbox_url|
[signed_activity_json, @account.id, inbox_url]
end
end
def merge_into_home_timelines!
@account.followers_for_local_distribution.reorder(nil).find_each do |follower|
FeedManager.instance.merge_into_home(@account, follower)
end
end
def merge_into_list_timelines!
@account.lists_for_local_distribution.reorder(nil).find_each do |list|
FeedManager.instance.merge_into_list(@account, list)
end
end
def publish_media_attachments!
attachment_names = MediaAttachment.attachment_definitions.keys
@account.media_attachments.find_each do |media_attachment|
attachment_names.each do |attachment_name|
attachment = media_attachment.public_send(attachment_name)
styles = MediaAttachment::DEFAULT_STYLES | attachment.styles.keys
next if attachment.blank?
styles.each do |style|
case Paperclip::Attachment.default_options[:storage]
when :s3
# Prevent useless S3 calls if ACLs are disabled
next if ENV['S3_PERMISSION'] == ''
begin
attachment.s3_object(style).acl.put(acl: Paperclip::Attachment.default_options[:s3_permissions])
rescue Aws::S3::Errors::NoSuchKey
Rails.logger.warn "Tried to change acl on non-existent key #{attachment.s3_object(style).key}"
rescue Aws::S3::Errors::NotImplemented => e
Rails.logger.error "Error trying to change ACL on #{attachment.s3_object(style).key}: #{e.message}"
end
when :fog, :azure
# Not supported
when :filesystem
begin
FileUtils.chmod(0o666 & ~File.umask, attachment.path(style)) unless attachment.path(style).nil?
rescue Errno::ENOENT
Rails.logger.warn "Tried to change permission on non-existent file #{attachment.path(style)}"
end
end
CacheBusterWorker.perform_async(attachment.path(style)) if Rails.configuration.x.cache_buster_enabled
end
end
end
end
def signed_activity_json
@signed_activity_json ||= Oj.dump(serialize_payload(@account, ActivityPub::UpdateSerializer, signer: @account))
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe UnsuspendAccountService, type: :service do
shared_context 'with common context' do
subject { described_class.new.call(account) }
let!(:local_follower) { Fabricate(:user, current_sign_in_at: 1.hour.ago).account }
let!(:list) { Fabricate(:list, account: local_follower) }
before do
allow(FeedManager.instance).to receive_messages(merge_into_home: nil, merge_into_list: nil)
local_follower.follow!(account)
list.accounts << account
account.unsuspend!
end
end
describe 'unsuspending a local account' do
def match_update_actor_request(req, account)
json = JSON.parse(req.body)
actor_id = ActivityPub::TagManager.instance.uri_for(account)
json['type'] == 'Update' && json['actor'] == actor_id && json['object']['id'] == actor_id && !json['object']['suspended']
end
before do
stub_request(:post, 'https://alice.com/inbox').to_return(status: 201)
stub_request(:post, 'https://bob.com/inbox').to_return(status: 201)
end
it 'does not change the “suspended” flag' do
expect { subject }.to_not change(account, :suspended?)
end
include_examples 'with common context' do
let!(:account) { Fabricate(:account) }
let!(:remote_follower) { Fabricate(:account, uri: 'https://alice.com', inbox_url: 'https://alice.com/inbox', protocol: :activitypub, domain: 'alice.com') }
let!(:remote_reporter) { Fabricate(:account, uri: 'https://bob.com', inbox_url: 'https://bob.com/inbox', protocol: :activitypub, domain: 'bob.com') }
let!(:report) { Fabricate(:report, account: remote_reporter, target_account: account) }
before do
remote_follower.follow!(account)
end
it "merges back into local followers' feeds" do
subject
expect(FeedManager.instance).to have_received(:merge_into_home).with(account, local_follower)
expect(FeedManager.instance).to have_received(:merge_into_list).with(account, list)
end
it 'sends an update actor to followers and reporters' do
subject
expect(a_request(:post, remote_follower.inbox_url).with { |req| match_update_actor_request(req, account) }).to have_been_made.once
expect(a_request(:post, remote_reporter.inbox_url).with { |req| match_update_actor_request(req, account) }).to have_been_made.once
end
end
end
describe 'unsuspending a remote account' do
include_examples 'with common context' do
let!(:account) { Fabricate(:account, domain: 'bob.com', uri: 'https://bob.com', inbox_url: 'https://bob.com/inbox', protocol: :activitypub) }
let!(:resolve_account_service) { instance_double(ResolveAccountService) }
before do
allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service)
end
context 'when the account is not remotely suspended' do
before do
allow(resolve_account_service).to receive(:call).with(account).and_return(account)
end
it 're-fetches the account' do
subject
expect(resolve_account_service).to have_received(:call).with(account)
end
it "merges back into local followers' feeds" do
subject
expect(FeedManager.instance).to have_received(:merge_into_home).with(account, local_follower)
expect(FeedManager.instance).to have_received(:merge_into_list).with(account, list)
end
it 'does not change the “suspended” flag' do
expect { subject }.to_not change(account, :suspended?)
end
end
context 'when the account is remotely suspended' do
before do
allow(resolve_account_service).to receive(:call).with(account) do |account|
account.suspend!(origin: :remote)
account
end
end
it 're-fetches the account' do
subject
expect(resolve_account_service).to have_received(:call).with(account)
end
it "does not merge back into local followers' feeds" do
subject
expect(FeedManager.instance).to_not have_received(:merge_into_home).with(account, local_follower)
expect(FeedManager.instance).to_not have_received(:merge_into_list).with(account, list)
end
it 'marks account as suspended' do
expect { subject }.to change(account, :suspended?).from(false).to(true)
end
end
context 'when the account is remotely deleted' do
before do
allow(resolve_account_service).to receive(:call).with(account).and_return(nil)
end
it 're-fetches the account' do
subject
expect(resolve_account_service).to have_received(:call).with(account)
end
it "does not merge back into local followers' feeds" do
subject
expect(FeedManager.instance).to_not have_received(:merge_into_home).with(account, local_follower)
expect(FeedManager.instance).to_not have_received(:merge_into_list).with(account, list)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class AfterBlockDomainFromAccountService < BaseService
include Payloadable
# This service does not create an AccountDomainBlock record,
# it's meant to be called after such a record has been created
# synchronously, to "clean up"
def call(account, domain)
@account = account
@domain = domain
clear_notifications!
remove_follows!
reject_existing_followers!
reject_pending_follow_requests!
end
private
def remove_follows!
@account.active_relationships.where(target_account: Account.where(domain: @domain)).includes(:target_account).reorder(nil).find_each do |follow|
UnfollowService.new.call(@account, follow.target_account)
end
end
def clear_notifications!
Notification.where(account: @account).where(from_account: Account.where(domain: @domain)).in_batches.delete_all
end
def reject_existing_followers!
@account.passive_relationships.where(account: Account.where(domain: @domain)).includes(:account).reorder(nil).find_each do |follow|
reject_follow!(follow)
end
end
def reject_pending_follow_requests!
FollowRequest.where(target_account: @account).where(account: Account.where(domain: @domain)).includes(:account).reorder(nil).find_each do |follow_request|
reject_follow!(follow_request)
end
end
def reject_follow!(follow)
follow.destroy
return unless follow.account.activitypub?
ActivityPub::DeliveryWorker.perform_async(Oj.dump(serialize_payload(follow, ActivityPub::RejectFollowSerializer)), @account.id, follow.account.inbox_url)
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe AfterBlockDomainFromAccountService, type: :service do
subject { described_class.new }
let!(:wolf) { Fabricate(:account, username: 'wolf', domain: 'evil.org', inbox_url: 'https://evil.org/inbox', protocol: :activitypub) }
let!(:alice) { Fabricate(:account, username: 'alice') }
before do
allow(ActivityPub::DeliveryWorker).to receive(:perform_async)
end
it 'purge followers from blocked domain' do
wolf.follow!(alice)
subject.call(alice, 'evil.org')
expect(wolf.following?(alice)).to be false
end
it 'sends Reject->Follow to followers from blocked domain' do
wolf.follow!(alice)
subject.call(alice, 'evil.org')
expect(ActivityPub::DeliveryWorker).to have_received(:perform_async).once
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class BlockDomainService < BaseService
attr_reader :domain_block
def call(domain_block, update = false)
@domain_block = domain_block
process_domain_block!
process_retroactive_updates! if update
end
private
def process_retroactive_updates!
# If the domain block severity has been changed, undo the appropriate limitations
scope = Account.by_domain_and_subdomains(domain_block.domain)
scope.where(silenced_at: domain_block.created_at).in_batches.update_all(silenced_at: nil) unless domain_block.silence?
scope.where(suspended_at: domain_block.created_at).in_batches.update_all(suspended_at: nil, suspension_origin: nil) unless domain_block.suspend?
end
def process_domain_block!
if domain_block.silence?
silence_accounts!
elsif domain_block.suspend?
suspend_accounts!
end
DomainClearMediaWorker.perform_async(domain_block.id) if domain_block.reject_media?
end
def silence_accounts!
blocked_domain_accounts.without_silenced.in_batches.update_all(silenced_at: @domain_block.created_at)
end
def suspend_accounts!
blocked_domain_accounts.without_suspended.in_batches.update_all(suspended_at: @domain_block.created_at, suspension_origin: :local)
blocked_domain_accounts.where(suspended_at: @domain_block.created_at).reorder(nil).find_each do |account|
DeleteAccountService.new.call(account, reserve_username: true, suspended_at: @domain_block.created_at)
end
end
def blocked_domain
domain_block.domain
end
def blocked_domain_accounts
Account.by_domain_and_subdomains(blocked_domain)
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe BlockDomainService, type: :service do
subject { described_class.new }
let!(:bad_account) { Fabricate(:account, username: 'badguy666', domain: 'evil.org') }
let!(:bad_status_plain) { Fabricate(:status, account: bad_account, text: 'You suck') }
let!(:bad_status_with_attachment) { Fabricate(:status, account: bad_account, text: 'Hahaha') }
let!(:bad_attachment) { Fabricate(:media_attachment, account: bad_account, status: bad_status_with_attachment, file: attachment_fixture('attachment.jpg')) }
let!(:already_banned_account) { Fabricate(:account, username: 'badguy', domain: 'evil.org', suspended: true, silenced: true) }
describe 'for a suspension' do
before do
subject.call(DomainBlock.create!(domain: 'evil.org', severity: :suspend))
end
it 'creates a domain block' do
expect(DomainBlock.blocked?('evil.org')).to be true
end
it 'removes remote accounts from that domain' do
expect(Account.find_remote('badguy666', 'evil.org').suspended?).to be true
end
it 'records suspension date appropriately' do
expect(Account.find_remote('badguy666', 'evil.org').suspended_at).to eq DomainBlock.find_by(domain: 'evil.org').created_at
end
it 'keeps already-banned accounts banned' do
expect(Account.find_remote('badguy', 'evil.org').suspended?).to be true
end
it 'does not overwrite suspension date of already-banned accounts' do
expect(Account.find_remote('badguy', 'evil.org').suspended_at).to_not eq DomainBlock.find_by(domain: 'evil.org').created_at
end
it 'removes the remote accounts\'s statuses and media attachments' do
expect { bad_status_plain.reload }.to raise_exception ActiveRecord::RecordNotFound
expect { bad_status_with_attachment.reload }.to raise_exception ActiveRecord::RecordNotFound
expect { bad_attachment.reload }.to raise_exception ActiveRecord::RecordNotFound
end
end
describe 'for a silence with reject media' do
before do
subject.call(DomainBlock.create!(domain: 'evil.org', severity: :silence, reject_media: true))
end
it 'does not create a domain block' do
expect(DomainBlock.blocked?('evil.org')).to be false
end
it 'silences remote accounts from that domain' do
expect(Account.find_remote('badguy666', 'evil.org').silenced?).to be true
end
it 'records suspension date appropriately' do
expect(Account.find_remote('badguy666', 'evil.org').silenced_at).to eq DomainBlock.find_by(domain: 'evil.org').created_at
end
it 'keeps already-banned accounts banned' do
expect(Account.find_remote('badguy', 'evil.org').silenced?).to be true
end
it 'does not overwrite suspension date of already-banned accounts' do
expect(Account.find_remote('badguy', 'evil.org').silenced_at).to_not eq DomainBlock.find_by(domain: 'evil.org').created_at
end
it 'leaves the domains status and attachments, but clears media' do
expect { bad_status_plain.reload }.to_not raise_error
expect { bad_status_with_attachment.reload }.to_not raise_error
expect { bad_attachment.reload }.to_not raise_error
expect(bad_attachment.file.exists?).to be false
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class BlockService < BaseService
include Payloadable
def call(account, target_account)
return if account.id == target_account.id
UnfollowService.new.call(account, target_account) if account.following?(target_account)
UnfollowService.new.call(target_account, account) if target_account.following?(account)
RejectFollowService.new.call(target_account, account) if target_account.requested?(account)
block = account.block!(target_account)
BlockWorker.perform_async(account.id, target_account.id)
create_notification(block) if !target_account.local? && target_account.activitypub?
block
end
private
def create_notification(block)
ActivityPub::DeliveryWorker.perform_async(build_json(block), block.account_id, block.target_account.inbox_url)
end
def build_json(block)
Oj.dump(serialize_payload(block, ActivityPub::BlockSerializer))
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe BlockService, type: :service do
subject { described_class.new }
let(:sender) { Fabricate(:account, username: 'alice') }
describe 'local' do
let(:bob) { Fabricate(:account, username: 'bob') }
before do
subject.call(sender, bob)
end
it 'creates a blocking relation' do
expect(sender.blocking?(bob)).to be true
end
end
describe 'remote ActivityPub' do
let(:bob) { Fabricate(:account, username: 'bob', protocol: :activitypub, domain: 'example.com', inbox_url: 'http://example.com/inbox') }
before do
stub_request(:post, 'http://example.com/inbox').to_return(status: 200)
subject.call(sender, bob)
end
it 'creates a blocking relation' do
expect(sender.blocking?(bob)).to be true
end
it 'sends a block activity' do
expect(a_request(:post, 'http://example.com/inbox')).to have_been_made.once
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class UnfollowService < BaseService
include Payloadable
include Redisable
include Lockable
# Unfollow and notify the remote user
# @param [Account] source_account Where to unfollow from
# @param [Account] target_account Which to unfollow
# @param [Hash] options
# @option [Boolean] :skip_unmerge
def call(source_account, target_account, options = {})
@source_account = source_account
@target_account = target_account
@options = options
with_redis_lock("relationship:#{[source_account.id, target_account.id].sort.join(':')}") do
unfollow! || undo_follow_request!
end
end
private
def unfollow!
follow = Follow.find_by(account: @source_account, target_account: @target_account)
return unless follow
follow.destroy!
create_notification(follow) if !@target_account.local? && @target_account.activitypub?
create_reject_notification(follow) if @target_account.local? && !@source_account.local? && @source_account.activitypub?
UnmergeWorker.perform_async(@target_account.id, @source_account.id) unless @options[:skip_unmerge]
follow
end
def undo_follow_request!
follow_request = FollowRequest.find_by(account: @source_account, target_account: @target_account)
return unless follow_request
follow_request.destroy!
create_notification(follow_request) unless @target_account.local?
follow_request
end
def create_notification(follow)
ActivityPub::DeliveryWorker.perform_async(build_json(follow), follow.account_id, follow.target_account.inbox_url)
end
def create_reject_notification(follow)
ActivityPub::DeliveryWorker.perform_async(build_reject_json(follow), follow.target_account_id, follow.account.inbox_url)
end
def build_json(follow)
Oj.dump(serialize_payload(follow, ActivityPub::UndoFollowSerializer))
end
def build_reject_json(follow)
Oj.dump(serialize_payload(follow, ActivityPub::RejectFollowSerializer))
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe UnfollowService, type: :service do
subject { described_class.new }
let(:sender) { Fabricate(:account, username: 'alice') }
describe 'local' do
let(:bob) { Fabricate(:account, username: 'bob') }
before do
sender.follow!(bob)
subject.call(sender, bob)
end
it 'destroys the following relation' do
expect(sender.following?(bob)).to be false
end
end
describe 'remote ActivityPub' do
let(:bob) { Fabricate(:account, username: 'bob', protocol: :activitypub, domain: 'example.com', inbox_url: 'http://example.com/inbox') }
before do
sender.follow!(bob)
stub_request(:post, 'http://example.com/inbox').to_return(status: 200)
subject.call(sender, bob)
end
it 'destroys the following relation' do
expect(sender.following?(bob)).to be false
end
it 'sends an unfollow activity' do
expect(a_request(:post, 'http://example.com/inbox')).to have_been_made.once
end
end
describe 'remote ActivityPub (reverse)' do
let(:bob) { Fabricate(:account, username: 'bob', protocol: :activitypub, domain: 'example.com', inbox_url: 'http://example.com/inbox') }
before do
bob.follow!(sender)
stub_request(:post, 'http://example.com/inbox').to_return(status: 200)
subject.call(bob, sender)
end
it 'destroys the following relation' do
expect(bob.following?(sender)).to be false
end
it 'sends a reject activity' do
expect(a_request(:post, 'http://example.com/inbox')).to have_been_made.once
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class SuspendAccountService < BaseService
include Payloadable
# Carry out the suspension of a recently-suspended account
# @param [Account] account Account to suspend
def call(account)
return unless account.suspended?
@account = account
reject_remote_follows!
distribute_update_actor!
unmerge_from_home_timelines!
unmerge_from_list_timelines!
privatize_media_attachments!
end
private
def reject_remote_follows!
return if @account.local? || [email protected]?
# When suspending a remote account, the account obviously doesn't
# actually become suspended on its origin server, i.e. unlike a
# locally suspended account it continues to have access to its home
# feed and other content. To prevent it from being able to continue
# to access toots it would receive because it follows local accounts,
# we have to force it to unfollow them. Unfortunately, there is no
# counterpart to this operation, i.e. you can't then force a remote
# account to re-follow you, so this part is not reversible.
Follow.where(account: @account).find_in_batches do |follows|
ActivityPub::DeliveryWorker.push_bulk(follows) do |follow|
[Oj.dump(serialize_payload(follow, ActivityPub::RejectFollowSerializer)), follow.target_account_id, @account.inbox_url]
end
follows.each(&:destroy)
end
end
def distribute_update_actor!
return unless @account.local?
account_reach_finder = AccountReachFinder.new(@account)
ActivityPub::DeliveryWorker.push_bulk(account_reach_finder.inboxes, limit: 1_000) do |inbox_url|
[signed_activity_json, @account.id, inbox_url]
end
end
def unmerge_from_home_timelines!
@account.followers_for_local_distribution.reorder(nil).find_each do |follower|
FeedManager.instance.unmerge_from_home(@account, follower)
end
end
def unmerge_from_list_timelines!
@account.lists_for_local_distribution.reorder(nil).find_each do |list|
FeedManager.instance.unmerge_from_list(@account, list)
end
end
def privatize_media_attachments!
attachment_names = MediaAttachment.attachment_definitions.keys
@account.media_attachments.find_each do |media_attachment|
attachment_names.each do |attachment_name|
attachment = media_attachment.public_send(attachment_name)
styles = MediaAttachment::DEFAULT_STYLES | attachment.styles.keys
next if attachment.blank?
styles.each do |style|
case Paperclip::Attachment.default_options[:storage]
when :s3
# Prevent useless S3 calls if ACLs are disabled
next if ENV['S3_PERMISSION'] == ''
begin
attachment.s3_object(style).acl.put(acl: 'private')
rescue Aws::S3::Errors::NoSuchKey
Rails.logger.warn "Tried to change acl on non-existent key #{attachment.s3_object(style).key}"
rescue Aws::S3::Errors::NotImplemented => e
Rails.logger.error "Error trying to change ACL on #{attachment.s3_object(style).key}: #{e.message}"
end
when :fog, :azure
# Not supported
when :filesystem
begin
FileUtils.chmod(0o600 & ~File.umask, attachment.path(style)) unless attachment.path(style).nil?
rescue Errno::ENOENT
Rails.logger.warn "Tried to change permission on non-existent file #{attachment.path(style)}"
end
end
CacheBusterWorker.perform_async(attachment.path(style)) if Rails.configuration.x.cache_buster_enabled
end
end
end
end
def signed_activity_json
@signed_activity_json ||= Oj.dump(serialize_payload(@account, ActivityPub::UpdateSerializer, signer: @account))
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe SuspendAccountService, type: :service do
shared_examples 'common behavior' do
subject { described_class.new.call(account) }
let!(:local_follower) { Fabricate(:user, current_sign_in_at: 1.hour.ago).account }
let!(:list) { Fabricate(:list, account: local_follower) }
before do
allow(FeedManager.instance).to receive_messages(unmerge_from_home: nil, unmerge_from_list: nil)
local_follower.follow!(account)
list.accounts << account
account.suspend!
end
it "unmerges from local followers' feeds" do
subject
expect(FeedManager.instance).to have_received(:unmerge_from_home).with(account, local_follower)
expect(FeedManager.instance).to have_received(:unmerge_from_list).with(account, list)
end
it 'does not change the “suspended” flag' do
expect { subject }.to_not change(account, :suspended?)
end
end
describe 'suspending a local account' do
def match_update_actor_request(req, account)
json = JSON.parse(req.body)
actor_id = ActivityPub::TagManager.instance.uri_for(account)
json['type'] == 'Update' && json['actor'] == actor_id && json['object']['id'] == actor_id && json['object']['suspended']
end
before do
stub_request(:post, 'https://alice.com/inbox').to_return(status: 201)
stub_request(:post, 'https://bob.com/inbox').to_return(status: 201)
end
include_examples 'common behavior' do
let!(:account) { Fabricate(:account) }
let!(:remote_follower) { Fabricate(:account, uri: 'https://alice.com', inbox_url: 'https://alice.com/inbox', protocol: :activitypub, domain: 'alice.com') }
let!(:remote_reporter) { Fabricate(:account, uri: 'https://bob.com', inbox_url: 'https://bob.com/inbox', protocol: :activitypub, domain: 'bob.com') }
let!(:report) { Fabricate(:report, account: remote_reporter, target_account: account) }
before do
remote_follower.follow!(account)
end
it 'sends an update actor to followers and reporters' do
subject
expect(a_request(:post, remote_follower.inbox_url).with { |req| match_update_actor_request(req, account) }).to have_been_made.once
expect(a_request(:post, remote_reporter.inbox_url).with { |req| match_update_actor_request(req, account) }).to have_been_made.once
end
end
end
describe 'suspending a remote account' do
def match_reject_follow_request(req, account, followee)
json = JSON.parse(req.body)
json['type'] == 'Reject' && json['actor'] == ActivityPub::TagManager.instance.uri_for(followee) && json['object']['actor'] == account.uri
end
before do
stub_request(:post, 'https://bob.com/inbox').to_return(status: 201)
end
include_examples 'common behavior' do
let!(:account) { Fabricate(:account, domain: 'bob.com', uri: 'https://bob.com', inbox_url: 'https://bob.com/inbox', protocol: :activitypub) }
let!(:local_followee) { Fabricate(:account) }
before do
account.follow!(local_followee)
end
it 'sends a reject follow' do
subject
expect(a_request(:post, account.inbox_url).with { |req| match_reject_follow_request(req, account, local_followee) }).to have_been_made.once
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class BulkImportService < BaseService
def call(import)
@import = import
@account = @import.account
case @import.type.to_sym
when :following
import_follows!
when :blocking
import_blocks!
when :muting
import_mutes!
when :domain_blocking
import_domain_blocks!
when :bookmarks
import_bookmarks!
when :lists
import_lists!
end
@import.update!(state: :finished, finished_at: Time.now.utc) if @import.processed_items == @import.total_items
rescue
@import.update!(state: :finished, finished_at: Time.now.utc)
raise
end
private
def extract_rows_by_acct
local_domain_suffix = "@#{Rails.configuration.x.local_domain}"
@import.rows.to_a.index_by { |row| row.data['acct'].delete_suffix(local_domain_suffix) }
end
def import_follows!
rows_by_acct = extract_rows_by_acct
if @import.overwrite?
@account.following.reorder(nil).find_each do |followee|
row = rows_by_acct.delete(followee.acct)
if row.nil?
UnfollowService.new.call(@account, followee)
else
row.destroy
@import.processed_items += 1
@import.imported_items += 1
# Since we're updating the settings of an existing relationship, we can safely call
# FollowService directly
FollowService.new.call(@account, followee, reblogs: row.data['show_reblogs'], notify: row.data['notify'], languages: row.data['languages'])
end
end
# Save pending infos due to `overwrite?` handling
@import.save!
end
Import::RowWorker.push_bulk(rows_by_acct.values) do |row|
[row.id]
end
end
def import_blocks!
rows_by_acct = extract_rows_by_acct
if @import.overwrite?
@account.blocking.reorder(nil).find_each do |blocked_account|
row = rows_by_acct.delete(blocked_account.acct)
if row.nil?
UnblockService.new.call(@account, blocked_account)
else
row.destroy
@import.processed_items += 1
@import.imported_items += 1
BlockService.new.call(@account, blocked_account)
end
end
# Save pending infos due to `overwrite?` handling
@import.save!
end
Import::RowWorker.push_bulk(rows_by_acct.values) do |row|
[row.id]
end
end
def import_mutes!
rows_by_acct = extract_rows_by_acct
if @import.overwrite?
@account.muting.reorder(nil).find_each do |muted_account|
row = rows_by_acct.delete(muted_account.acct)
if row.nil?
UnmuteService.new.call(@account, muted_account)
else
row.destroy
@import.processed_items += 1
@import.imported_items += 1
MuteService.new.call(@account, muted_account, notifications: row.data['hide_notifications'])
end
end
# Save pending infos due to `overwrite?` handling
@import.save!
end
Import::RowWorker.push_bulk(rows_by_acct.values) do |row|
[row.id]
end
end
def import_domain_blocks!
domains = @import.rows.map { |row| row.data['domain'] }
if @import.overwrite?
@account.domain_blocks.find_each do |domain_block|
domain = domains.delete(domain_block)
@account.unblock_domain!(domain_block.domain) if domain.nil?
end
end
@import.rows.delete_all
domains.each { |domain| @account.block_domain!(domain) }
@import.update!(processed_items: @import.total_items, imported_items: @import.total_items)
AfterAccountDomainBlockWorker.push_bulk(domains) do |domain|
[@account.id, domain]
end
end
def import_bookmarks!
rows_by_uri = @import.rows.index_by { |row| row.data['uri'] }
if @import.overwrite?
@account.bookmarks.includes(:status).find_each do |bookmark|
row = rows_by_uri.delete(ActivityPub::TagManager.instance.uri_for(bookmark.status))
if row.nil?
bookmark.destroy!
else
row.destroy
@import.processed_items += 1
@import.imported_items += 1
end
end
# Save pending infos due to `overwrite?` handling
@import.save!
end
Import::RowWorker.push_bulk(rows_by_uri.values) do |row|
[row.id]
end
end
def import_lists!
rows = @import.rows.to_a
included_lists = rows.map { |row| row.data['list_name'] }.uniq
if @import.overwrite?
@account.owned_lists.where.not(title: included_lists).destroy_all
# As list membership changes do not retroactively change timeline
# contents, simplify things by just clearing everything
@account.owned_lists.find_each do |list|
list.list_accounts.destroy_all
end
end
included_lists.each do |title|
@account.owned_lists.find_or_create_by!(title: title)
end
Import::RowWorker.push_bulk(rows) do |row|
[row.id]
end
end
end
``` | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe BulkImportService do
subject { described_class.new }
let(:account) { Fabricate(:account) }
let(:import) { Fabricate(:bulk_import, account: account, type: import_type, overwrite: overwrite, state: :in_progress, imported_items: 0, processed_items: 0) }
before do
import.update(total_items: import.rows.count)
end
describe '#call', :sidekiq_fake do
context 'when importing follows' do
let(:import_type) { 'following' }
let(:overwrite) { false }
let!(:rows) do
[
{ 'acct' => '[email protected]' },
{ 'acct' => '[email protected]' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.follow!(Fabricate(:account))
end
it 'does not immediately change who the account follows' do
expect { subject.call(import) }.to_not(change { account.reload.active_relationships.to_a })
end
it 'enqueues workers for the expected rows' do
subject.call(import)
expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))
end
it 'requests to follow all the listed users once the workers have run' do
subject.call(import)
resolve_account_service_double = instance_double(ResolveAccountService)
allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }
Import::RowWorker.drain
expect(FollowRequest.includes(:target_account).where(account: account).map { |follow_request| follow_request.target_account.acct }).to contain_exactly('[email protected]', '[email protected]')
end
end
context 'when importing follows with overwrite' do
let(:import_type) { 'following' }
let(:overwrite) { true }
let!(:followed) { Fabricate(:account, username: 'followed', domain: 'foo.bar', protocol: :activitypub) }
let!(:to_be_unfollowed) { Fabricate(:account, username: 'to_be_unfollowed', domain: 'foo.bar', protocol: :activitypub) }
let!(:rows) do
[
{ 'acct' => '[email protected]', 'show_reblogs' => false, 'notify' => true, 'languages' => ['en'] },
{ 'acct' => '[email protected]' },
{ 'acct' => '[email protected]' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.follow!(followed, reblogs: true, notify: false)
account.follow!(to_be_unfollowed)
end
it 'unfollows user not present on list' do
subject.call(import)
expect(account.following?(to_be_unfollowed)).to be false
end
it 'updates the existing follow relationship as expected' do
expect { subject.call(import) }.to change { Follow.where(account: account, target_account: followed).pick(:show_reblogs, :notify, :languages) }.from([true, false, nil]).to([false, true, ['en']])
end
it 'enqueues workers for the expected rows' do
subject.call(import)
expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows[1..].map(&:id))
end
it 'requests to follow all the expected users once the workers have run' do
subject.call(import)
resolve_account_service_double = instance_double(ResolveAccountService)
allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }
Import::RowWorker.drain
expect(FollowRequest.includes(:target_account).where(account: account).map { |follow_request| follow_request.target_account.acct }).to contain_exactly('[email protected]', '[email protected]')
end
end
context 'when importing blocks' do
let(:import_type) { 'blocking' }
let(:overwrite) { false }
let!(:rows) do
[
{ 'acct' => '[email protected]' },
{ 'acct' => '[email protected]' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.block!(Fabricate(:account, username: 'already_blocked', domain: 'remote.org'))
end
it 'does not immediately change who the account blocks' do
expect { subject.call(import) }.to_not(change { account.reload.blocking.to_a })
end
it 'enqueues workers for the expected rows' do
subject.call(import)
expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))
end
it 'blocks all the listed users once the workers have run' do
subject.call(import)
resolve_account_service_double = instance_double(ResolveAccountService)
allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }
Import::RowWorker.drain
expect(account.blocking.map(&:acct)).to contain_exactly('[email protected]', '[email protected]', '[email protected]')
end
end
context 'when importing blocks with overwrite' do
let(:import_type) { 'blocking' }
let(:overwrite) { true }
let!(:blocked) { Fabricate(:account, username: 'blocked', domain: 'foo.bar', protocol: :activitypub) }
let!(:to_be_unblocked) { Fabricate(:account, username: 'to_be_unblocked', domain: 'foo.bar', protocol: :activitypub) }
let!(:rows) do
[
{ 'acct' => '[email protected]' },
{ 'acct' => '[email protected]' },
{ 'acct' => '[email protected]' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.block!(blocked)
account.block!(to_be_unblocked)
end
it 'unblocks user not present on list' do
subject.call(import)
expect(account.blocking?(to_be_unblocked)).to be false
end
it 'enqueues workers for the expected rows' do
subject.call(import)
expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows[1..].map(&:id))
end
it 'requests to follow all the expected users once the workers have run' do
subject.call(import)
resolve_account_service_double = instance_double(ResolveAccountService)
allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }
Import::RowWorker.drain
expect(account.blocking.map(&:acct)).to contain_exactly('[email protected]', '[email protected]', '[email protected]')
end
end
context 'when importing mutes' do
let(:import_type) { 'muting' }
let(:overwrite) { false }
let!(:rows) do
[
{ 'acct' => '[email protected]' },
{ 'acct' => '[email protected]' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.mute!(Fabricate(:account, username: 'already_muted', domain: 'remote.org'))
end
it 'does not immediately change who the account blocks' do
expect { subject.call(import) }.to_not(change { account.reload.muting.to_a })
end
it 'enqueues workers for the expected rows' do
subject.call(import)
expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))
end
it 'mutes all the listed users once the workers have run' do
subject.call(import)
resolve_account_service_double = instance_double(ResolveAccountService)
allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }
Import::RowWorker.drain
expect(account.muting.map(&:acct)).to contain_exactly('[email protected]', '[email protected]', '[email protected]')
end
end
context 'when importing mutes with overwrite' do
let(:import_type) { 'muting' }
let(:overwrite) { true }
let!(:muted) { Fabricate(:account, username: 'muted', domain: 'foo.bar', protocol: :activitypub) }
let!(:to_be_unmuted) { Fabricate(:account, username: 'to_be_unmuted', domain: 'foo.bar', protocol: :activitypub) }
let!(:rows) do
[
{ 'acct' => '[email protected]', 'hide_notifications' => true },
{ 'acct' => '[email protected]' },
{ 'acct' => '[email protected]' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.mute!(muted, notifications: false)
account.mute!(to_be_unmuted)
end
it 'updates the existing mute as expected' do
expect { subject.call(import) }.to change { Mute.where(account: account, target_account: muted).pick(:hide_notifications) }.from(false).to(true)
end
it 'unblocks user not present on list' do
subject.call(import)
expect(account.muting?(to_be_unmuted)).to be false
end
it 'enqueues workers for the expected rows' do
subject.call(import)
expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows[1..].map(&:id))
end
it 'requests to follow all the expected users once the workers have run' do
subject.call(import)
resolve_account_service_double = instance_double(ResolveAccountService)
allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }
allow(resolve_account_service_double).to receive(:call).with('[email protected]', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }
Import::RowWorker.drain
expect(account.muting.map(&:acct)).to contain_exactly('[email protected]', '[email protected]', '[email protected]')
end
end
context 'when importing domain blocks' do
let(:import_type) { 'domain_blocking' }
let(:overwrite) { false }
let!(:rows) do
[
{ 'domain' => 'blocked.com' },
{ 'domain' => 'to_block.com' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.block_domain!('alreadyblocked.com')
account.block_domain!('blocked.com')
end
it 'blocks all the new domains' do
subject.call(import)
expect(account.domain_blocks.pluck(:domain)).to contain_exactly('alreadyblocked.com', 'blocked.com', 'to_block.com')
end
it 'marks the import as finished' do
subject.call(import)
expect(import.reload.finished?).to be true
end
end
context 'when importing domain blocks with overwrite' do
let(:import_type) { 'domain_blocking' }
let(:overwrite) { true }
let!(:rows) do
[
{ 'domain' => 'blocked.com' },
{ 'domain' => 'to_block.com' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.block_domain!('alreadyblocked.com')
account.block_domain!('blocked.com')
end
it 'blocks all the new domains' do
subject.call(import)
expect(account.domain_blocks.pluck(:domain)).to contain_exactly('blocked.com', 'to_block.com')
end
it 'marks the import as finished' do
subject.call(import)
expect(import.reload.finished?).to be true
end
end
context 'when importing bookmarks' do
let(:import_type) { 'bookmarks' }
let(:overwrite) { false }
let!(:already_bookmarked) { Fabricate(:status, uri: 'https://already.bookmarked/1') }
let!(:status) { Fabricate(:status, uri: 'https://foo.bar/posts/1') }
let!(:inaccessible_status) { Fabricate(:status, uri: 'https://foo.bar/posts/inaccessible', visibility: :direct) }
let!(:bookmarked) { Fabricate(:status, uri: 'https://foo.bar/posts/already-bookmarked') }
let!(:rows) do
[
{ 'uri' => status.uri },
{ 'uri' => inaccessible_status.uri },
{ 'uri' => bookmarked.uri },
{ 'uri' => 'https://domain.unknown/foo' },
{ 'uri' => 'https://domain.unknown/private' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.bookmarks.create!(status: already_bookmarked)
account.bookmarks.create!(status: bookmarked)
end
it 'enqueues workers for the expected rows' do
subject.call(import)
expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))
end
it 'updates the bookmarks as expected once the workers have run' do
subject.call(import)
service_double = instance_double(ActivityPub::FetchRemoteStatusService)
allow(ActivityPub::FetchRemoteStatusService).to receive(:new).and_return(service_double)
allow(service_double).to receive(:call).with('https://domain.unknown/foo') { Fabricate(:status, uri: 'https://domain.unknown/foo') }
allow(service_double).to receive(:call).with('https://domain.unknown/private') { Fabricate(:status, uri: 'https://domain.unknown/private', visibility: :direct) }
Import::RowWorker.drain
expect(account.bookmarks.map { |bookmark| bookmark.status.uri }).to contain_exactly(already_bookmarked.uri, status.uri, bookmarked.uri, 'https://domain.unknown/foo')
end
end
context 'when importing bookmarks with overwrite' do
let(:import_type) { 'bookmarks' }
let(:overwrite) { true }
let!(:already_bookmarked) { Fabricate(:status, uri: 'https://already.bookmarked/1') }
let!(:status) { Fabricate(:status, uri: 'https://foo.bar/posts/1') }
let!(:inaccessible_status) { Fabricate(:status, uri: 'https://foo.bar/posts/inaccessible', visibility: :direct) }
let!(:bookmarked) { Fabricate(:status, uri: 'https://foo.bar/posts/already-bookmarked') }
let!(:rows) do
[
{ 'uri' => status.uri },
{ 'uri' => inaccessible_status.uri },
{ 'uri' => bookmarked.uri },
{ 'uri' => 'https://domain.unknown/foo' },
{ 'uri' => 'https://domain.unknown/private' },
].map { |data| import.rows.create!(data: data) }
end
before do
account.bookmarks.create!(status: already_bookmarked)
account.bookmarks.create!(status: bookmarked)
end
it 'enqueues workers for the expected rows' do
subject.call(import)
expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))
end
it 'updates the bookmarks as expected once the workers have run' do
subject.call(import)
service_double = instance_double(ActivityPub::FetchRemoteStatusService)
allow(ActivityPub::FetchRemoteStatusService).to receive(:new).and_return(service_double)
allow(service_double).to receive(:call).with('https://domain.unknown/foo') { Fabricate(:status, uri: 'https://domain.unknown/foo') }
allow(service_double).to receive(:call).with('https://domain.unknown/private') { Fabricate(:status, uri: 'https://domain.unknown/private', visibility: :direct) }
Import::RowWorker.drain
expect(account.bookmarks.map { |bookmark| bookmark.status.uri }).to contain_exactly(status.uri, bookmarked.uri, 'https://domain.unknown/foo')
end
end
end
end
|
End of preview. Expand
in Dataset Viewer.
YAML Metadata
Warning:
empty or missing yaml metadata in repo card
(https://huggingface.co/docs/hub/datasets-cards)
Ruby dataset
Custom ruby dataset
- rspec_dataset
Bigcode dataset
- ruby-dataset
- shell-dataset
- python-dataset
- sql-dataset
rspec dataset
Specs are exclusively gathered from the 'app/services' directory within the specified repositories. This approach is employed since the majority of business logic is encapsulated within these services
REPO_URLS = [
'https://github.com/diaspora/diaspora.git',
'https://github.com/mastodon/mastodon.git',
'https://github.com/gitlabhq/gitlabhq.git',
'https://github.com/discourse/discourse.git',
'https://github.com/chatwoot/chatwoot.git',
'https://github.com/opf/openproject.git',
]
output
Repository Avg Source Lines Avg Test Lines Test Cases
diaspora 62 156 12
mastodon 97 131 59
gitlabhq 66 154 952
discourse 188 303 49
chatwoot 63 107 50
openproject 86 178 98
------------------------------------------------------------
Total 74 159 1220
------------------------------------------------------------
# avg_source_lines = [62, 97, 66, 188, 63, 86]
# avg_test_lines = [156, 131, 154, 303, 107, 178]
# test_cases = [12, 59, 952, 49, 50, 98]
# Assuming an average of 10 tokens per line of code, which is a rough average for programming languages
# tokens_per_line = 10
# Calculating the total tokens for source and test lines
# total_source_tokens = sum([lines * tokens_per_line for lines in avg_source_lines])
# total_test_tokens = sum([lines * tokens_per_line for lines in avg_test_lines])
# Total tokens
# total_tokens = total_source_tokens + total_test_tokens
# Average tokens per test case
# avg_tokens_per_test_case = total_tokens / sum(test_cases)
# total_tokens, avg_tokens_per_test_case
# -> (15910, 13.040983606557377)
When you prepare data for training or inference with an LLM, each example (in this case, each test case or code snippet) needs to fit within this context window. The average tokens per test case calculated earlier (approximately 13.04 tokens) is well within the limits of LLMs
- Downloads last month
- 15