Skip to content

A platform for community discussion. Free, open, simple.

18.6 KB
Raw Blame
# frozen_string_literal: true

RSpec.describe TopicsController do
  let(:p1) { Fabricate(:post, like_count: 1) }
  let(:topic) { p1.topic }
  let(:p2) { Fabricate(:post, like_count: 2, topic:, user: Fabricate(:user)) }
  let(:p2_single_answer_json) do
    ',"acceptedAnswer":[%{answer_json}]' % { answer_json: solved_answer_json(post: p2) }
  end

  def solved_answer_json(post:)
    '{"@type":"Answer","author":{"@type":"Person","name":"%{username2}","url":"%{user2_url}"},"dateModified":"%{answer_modified}","datePublished":"%{answered_at}","text":"%{answer_text}","upvoteCount":%{answer_likes},"url":"%{answer_url}"}' %
      {
        answer_text: post.excerpt,
        answer_likes: post.like_count,
        answered_at: post.created_at.as_json,
        answer_modified: (post.last_version_at || post.created_at).as_json,
        answer_url: post.full_url,
        username2: post.user&.username,
        user2_url: post.user&.full_url,
      }
  end

  def solved_schema_json(topic:, first_post:, answers_json:, answer_count: 1)
    '<script type="application/ld+json">{"@context":"http://schema.org","@type":"QAPage","name":"%{title}","datePublished":"%{created_at}","mainEntity":{"@type":"Question","answerCount":%{answer_count},"author":{"@type":"Person","name":"%{username1}","url":"%{user1_url}"},"dateModified":"%{question_modified}","datePublished":"%{created_at}","name":"%{title}","text":"%{question_text}","upvoteCount":%{question_likes}%{answer_json}}}</script>' %
      {
        answer_count:,
        title: topic.title,
        question_text: first_post.excerpt,
        question_likes: first_post.like_count,
        created_at: topic.created_at.as_json,
        question_modified: (first_post.last_version_at || first_post.created_at).as_json,
        username1: topic.user&.username,
        user1_url: topic.user&.full_url,
        answer_json: answers_json,
      }
  end

  context "with solved enabled on every topic" do
    before { SiteSetting.allow_solved_on_all_topics = true }

    it "omits schema information for single-post topics without answers" do
      get "/t/#{topic.slug}/#{topic.id}"

      expect(response.body).not_to include("QAPage")
    end

    it "includes schema information for the accepted answer" do
      Fabricate(:solved_topic, topic:, answer_post: p2)

      get "/t/#{topic.slug}/#{topic.id}"

      expect(response.body).to include(
        solved_schema_json(topic:, first_post: p1, answers_json: p2_single_answer_json),
      )
    end

    it "does not include first post text in schema information when the guardian cannot see it" do
      hidden_text = "super-secret first post body"
      p1.update!(raw: hidden_text, hidden: true)
      p1.rebake!
      Fabricate(:solved_topic, topic:, answer_post: p2)

      get "/t/#{topic.slug}/#{topic.id}"

      schema_json =
        Nokogiri::HTML5
          .fragment(response.body)
          .at_css('script[type="application/ld+json"]')
          &.content

      expect(response.status).to eq(200)
      expect(schema_json).to include('"@type":"QAPage"')
      expect(schema_json).not_to include(hidden_text)
    end

    it "includes quoted content in schema information" do
      Fabricate(:solved_topic, topic:, answer_post: p2)

      post = topic.first_post
      post.raw = "[quote]This is a quoted text.[/quote]"
      post.save!
      post.rebake!

      get "/t/#{topic.slug}/#{topic.id}"

      expect(response.body).to include('"text":"This is a quoted text."')
    end

    it "includes the user name when enabled in site settings" do
      SiteSetting.display_name_on_posts = true
      SiteSetting.show_who_marked_solved = true
      accepter = Fabricate(:user)
      Fabricate(:solved_topic, topic:, topic_answer: Fabricate(:topic_answer, post: p2, accepter:))

      get "/t/#{topic.slug}/#{topic.id}.json"

      expect(response.parsed_body["accepted_answers"][0]["name"]).to eq(p2.user.name)
      expect(response.parsed_body["accepted_answers"][0]["username"]).to eq(p2.user.username)
      expect(response.parsed_body["accepted_answers"][0]["accepter_name"]).to eq(accepter.name)
      expect(response.parsed_body["accepted_answers"][0]["accepter_username"]).to eq(
        accepter.username,
      )

      SiteSetting.show_who_marked_solved = false
      get "/t/#{topic.slug}/#{topic.id}.json"
      expect(response.parsed_body["accepted_answers"][0]["accepter_name"]).to eq(nil)
      expect(response.parsed_body["accepted_answers"][0]["accepter_username"]).to eq(nil)

      # enable_names is default ON, this ensures disabling it also disables names here
      SiteSetting.enable_names = false
      get "/t/#{topic.slug}/#{topic.id}.json"
      expect(response.parsed_body["accepted_answers"][0]["name"]).to eq(nil)
      expect(response.parsed_body["accepted_answers"][0]["accepter_name"]).to eq(nil)
    end

    it "omits the user name when disabled in site settings" do
      SiteSetting.display_name_on_posts = false
      Fabricate(:solved_topic, topic:, answer_post: p2)

      get "/t/#{topic.slug}/#{topic.id}.json"

      expect(response.parsed_body["accepted_answers"][0]["name"]).to eq(nil)
      expect(response.parsed_body["accepted_answers"][0]["username"]).to eq(p2.user.username)
    end

    it "does not serialize accepted answers hidden from the current user" do
      answer_post =
        Fabricate(:post, topic:, raw: "secret accepted whisper solution", user: Fabricate(:user))
      Fabricate(:solved_topic, topic:, answer_post:)
      answer_post.update!(post_type: Post.types[:whisper])
      sign_in(Fabricate(:user))

      get "/t/#{topic.slug}/#{topic.id}.json"

      expect(response.status).to eq(200)
      expect(response.parsed_body["accepted_answers"]).to be_nil
      expect(response.parsed_body.to_s).not_to include(answer_post.raw)
    end

    it "does not serialize accepted answers that are hidden from the current user" do
      answer_post =
        Fabricate(:post, topic:, raw: "secret accepted hidden solution", user: Fabricate(:user))
      Fabricate(:solved_topic, topic:, answer_post:)
      answer_post.update!(
        hidden: true,
        hidden_reason_id: Post.hidden_reasons[:flag_threshold_reached],
      )
      sign_in(Fabricate(:user))

      get "/t/#{topic.slug}/#{topic.id}.json"

      expect(response.status).to eq(200)
      expect(response.parsed_body["accepted_answers"]).to be_nil
      expect(response.parsed_body.to_s).not_to include(answer_post.raw)
    end

    describe "with multiple solutions enabled" do
      before { SiteSetting.solved_allow_multiple_solutions = true }

      describe "when topic has two accepted answers and one not accepted" do
        let(:p3) { Fabricate(:post, topic:) }
        let(:p4) { Fabricate(:post, topic:) }
        let(:solved_topic) { Fabricate(:solved_topic, topic:) }
        let!(:first_topic_answer) { Fabricate(:topic_answer, solved_topic:, post: p2) }
        let!(:second_topic_answer) { Fabricate(:topic_answer, solved_topic:, post: p3) }
        let!(:unaccepted_post) { p4 }

        it "includes the expected schema information" do
          get "/t/#{topic.slug}/#{topic.id}"

          two_accepted_answers_json =
            ',"acceptedAnswer":[%{answer_p2},%{answer_p3}]' %
              { answer_p2: solved_answer_json(post: p2), answer_p3: solved_answer_json(post: p3) }
          suggested_answer_json =
            ',"suggestedAnswer":[%{answer_p4}]' % { answer_p4: solved_answer_json(post: p4) }

          answers_json = "#{two_accepted_answers_json}#{suggested_answer_json}"

          expect(response.body).to include(
            solved_schema_json(topic:, first_post: p1, answers_json:, answer_count: 3),
          )
        end
      end
    end
  end

  describe "crawler schema modifiers" do
    let(:crawler_env) { { "HTTP_USER_AGENT" => "Googlebot" } }
    let(:parsed_crawler_body) { Nokogiri::HTML5.fragment(response.body) }

    before { SiteSetting.allow_solved_on_all_topics = true }

    it "uses Question schema instead of DiscussionForumPosting when topic has replies" do
      Fabricate(:post, topic:, user: Fabricate(:user))

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      expect(doc.css('[itemtype*="Question"]').size).to eq(1)
      expect(doc.css('[itemtype*="DiscussionForumPosting"]').size).to eq(0)
    end

    it "keeps DiscussionForumPosting for single-post topics" do
      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      expect(doc.css('[itemtype*="DiscussionForumPosting"]').size).to eq(1)
      expect(doc.css('[itemtype*="QAPage"]').size).to eq(0)
    end

    it "keeps DiscussionForumPosting when only replies are hidden" do
      Fabricate(:post, topic:, hidden: true)

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      expect(doc.css('[itemtype*="DiscussionForumPosting"]').size).to eq(1)
      expect(doc.css('[itemtype*="QAPage"]').size).to eq(0)
    end

    it "keeps DiscussionForumPosting when only replies are small action posts" do
      Fabricate(:post, topic:, post_type: Post.types[:small_action])

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      expect(doc.css('[itemtype*="DiscussionForumPosting"]').size).to eq(1)
      expect(doc.css('[itemtype*="QAPage"]').size).to eq(0)
    end

    it "emits valid QAPage microdata with all required schema.org properties" do
      p3 = Fabricate(:post, topic:, user: Fabricate(:user))
      Fabricate(:solved_topic, topic:, answer_post: p2)

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      qa_page = doc.at_css('[itemtype*="QAPage"]')
      expect(qa_page).to be_present
      expect(qa_page.at_css('> [itemprop="name"]')["content"]).to eq(topic.title)

      question = doc.at_css('[itemtype*="Question"]')
      expect(question).to be_present
      expect(question.at_css('[itemprop="name"]')["content"]).to eq(topic.title)
      expect(question.at_css('[itemprop="datePublished"]')["content"]).to be_present
      expect(question.at_css('[itemprop="answerCount"]')["content"]).to eq("2")
      expect(question.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p1.like_count.to_s)
      expect(question.at_css('[itemprop="text"]')).to be_present
      expect(question.at_css('[itemprop="author"] [itemprop="name"]')).to be_present

      accepted = doc.at_css("#post_#{p2.post_number}")
      expect(accepted["itemprop"]).to eq("acceptedAnswer")
      expect(accepted["itemtype"]).to include("Answer")
      expect(accepted.at_css('[itemprop="text"]')).to be_present
      expect(accepted.at_css('[itemprop="datePublished"]')).to be_present
      expect(accepted.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
      expect(accepted.at_css('[itemprop="author"] [itemprop="url"]')["content"]).to include(
        p2.user.username,
      )
      expect(accepted.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p2.like_count.to_s)
      accepted_urls = accepted.css('meta[itemprop="url"]').map { |el| el["content"] }
      expect(accepted_urls).to include(p2.full_url)

      suggested = doc.at_css("#post_#{p3.post_number}")
      expect(suggested["itemprop"]).to eq("suggestedAnswer")
      expect(suggested["itemtype"]).to include("Answer")
      expect(suggested.at_css('[itemprop="text"]')).to be_present
      expect(suggested.at_css('[itemprop="datePublished"]')).to be_present
      expect(suggested.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
      expect(suggested.at_css('[itemprop="author"] [itemprop="url"]')["content"]).to include(
        p3.user.username,
      )
      expect(suggested.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p3.like_count.to_s)
      suggested_urls = suggested.css('meta[itemprop="url"]').map { |el| el["content"] }
      expect(suggested_urls).to include(p3.full_url)
    end

    it "does not leak microdata from ineligible posts into the Question scope" do
      ineligible =
        Fabricate(:post, topic:, user: Fabricate(:user), post_type: Post.types[:moderator_action])
      Fabricate(:solved_topic, topic:, answer_post: p2)

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      question = doc.at_css('[itemtype*="Question"]')
      ineligible_node = doc.at_css("#post_#{ineligible.post_number}")

      expect(ineligible_node).to be_present
      expect(question.xpath('./*[@itemprop="datePublished"]').size).to eq(1)
      expect(ineligible_node.css("[itemprop]")).to be_empty
    end

    describe "with multiple solutions enabled" do
      let(:p3) { Fabricate(:post, topic:, cooked: "p3 cooked") }
      let(:p4) { Fabricate(:post, topic:, cooked: "p4 cooked") }
      let(:solved_topic) { Fabricate(:solved_topic, topic:) }
      let!(:first_topic_answer) { Fabricate(:topic_answer, solved_topic:, post: p2) }
      let!(:second_topic_answer) { Fabricate(:topic_answer, solved_topic:, post: p3) }
      let!(:unaccepted_post) { p4 }

      before { SiteSetting.solved_allow_multiple_solutions = true }

      it "includes two acceptedAnswers and a suggestedAnswer in qaschema" do
        get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
        doc = parsed_crawler_body

        qa_page = doc.at_css('[itemtype*="QAPage"]')
        expect(qa_page).to be_present
        expect(qa_page.at_css('> [itemprop="name"]')["content"]).to eq(topic.title)

        question = doc.at_css('[itemtype*="Question"]')
        expect(question).to be_present
        expect(question.at_css('[itemprop="name"]')["content"]).to eq(topic.title)
        expect(question.at_css('[itemprop="datePublished"]')["content"]).to be_present
        expect(question.at_css('[itemprop="answerCount"]')["content"]).to eq("3")
        expect(question.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p1.like_count.to_s)
        expect(question.at_css('[itemprop="text"]')).to be_present
        expect(question.at_css('[itemprop="author"] [itemprop="name"]')).to be_present

        accepted = doc.at_css("#post_#{p2.post_number}")
        expect(accepted["itemprop"]).to eq("acceptedAnswer")
        expect(accepted["itemtype"]).to include("Answer")
        expect(accepted.at_css('[itemprop="text"]')).to be_present
        expect(accepted.at_css('[itemprop="datePublished"]')).to be_present
        expect(accepted.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
        expect(accepted.at_css('[itemprop="author"] [itemprop="url"]')["content"]).to include(
          p2.user.username,
        )
        expect(accepted.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p2.like_count.to_s)
        accepted_urls = accepted.css('meta[itemprop="url"]').map { |el| el["content"] }
        expect(accepted_urls).to include(p2.full_url)

        accepted = doc.at_css("#post_#{p3.post_number}")
        expect(accepted["itemprop"]).to eq("acceptedAnswer")
        expect(accepted["itemtype"]).to include("Answer")
        expect(accepted.at_css('[itemprop="text"]')).to be_present
        expect(accepted.at_css('[itemprop="datePublished"]')).to be_present
        expect(accepted.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
        expect(accepted.at_css('[itemprop="author"] [itemprop="url"]')["content"]).to include(
          p3.user.username,
        )
        expect(accepted.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p3.like_count.to_s)
        accepted_urls = accepted.css('meta[itemprop="url"]').map { |el| el["content"] }
        expect(accepted_urls).to include(p3.full_url)

        suggested = doc.at_css("#post_#{p4.post_number}")
        expect(suggested["itemprop"]).to eq("suggestedAnswer")
        expect(suggested["itemtype"]).to include("Answer")
        expect(suggested.at_css('[itemprop="text"]')).to be_present
        expect(suggested.at_css('[itemprop="datePublished"]')).to be_present
        expect(suggested.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
        expect(suggested.at_css('[itemprop="author"] [itemprop="url"]')["content"]).to include(
          p4.user.username,
        )
        expect(suggested.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p4.like_count.to_s)
        suggested_urls = suggested.css('meta[itemprop="url"]').map { |el| el["content"] }
        expect(suggested_urls).to include(p4.full_url)
      end
    end

    it "does not modify schema for topics without solved enabled" do
      SiteSetting.allow_solved_on_all_topics = false

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      expect(doc.css('[itemtype*="DiscussionForumPosting"]').size).to eq(1)
      expect(doc.css('[itemtype*="Question"]').size).to eq(0)
    end

    it "does not emit QAPage schema when schema markup is set to never" do
      SiteSetting.solved_add_schema_markup = "never"

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      expect(doc.css('[itemtype*="DiscussionForumPosting"]').size).to eq(1)
      expect(doc.css('[itemtype*="QAPage"]').size).to eq(0)
      expect(doc.css('[itemtype*="Question"]').size).to eq(0)
    end

    it "does not emit QAPage schema when set to 'answered only' without an accepted answer" do
      SiteSetting.solved_add_schema_markup = "answered only"

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      expect(doc.css('[itemtype*="DiscussionForumPosting"]').size).to eq(1)
      expect(doc.css('[itemtype*="QAPage"]').size).to eq(0)
    end

    it "emits QAPage schema when set to 'answered only' with an accepted answer" do
      SiteSetting.solved_add_schema_markup = "answered only"
      Fabricate(:solved_topic, topic:, answer_post: p2)

      get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
      doc = parsed_crawler_body

      expect(doc.css('[itemtype*="QAPage"]').size).to eq(1)
      expect(doc.css('[itemtype*="Question"]').size).to eq(1)
    end
  end

  context "with solved enabled for topics with specific tags" do
    let(:tag) { Fabricate(:tag) }

    before { SiteSetting.enable_solved_tags = tag.name }

    it "includes the correct schema information" do
      DiscourseTagging.add_or_create_tags_by_name(topic, [tag.name])
      Fabricate(:solved_topic, topic:, answer_post: p2)

      get "/t/#{topic.slug}/#{topic.id}"

      expect(response.body).to include(
        solved_schema_json(topic:, first_post: p1, answers_json: p2_single_answer_json),
      )
    end

    it "doesn't include solved schema information when the topic has a different tag" do
      another_tag = Fabricate(:tag)

      DiscourseTagging.add_or_create_tags_by_name(topic, [another_tag.name])
      Fabricate(:solved_topic, topic:, answer_post: p2)

      get "/t/#{topic.slug}/#{topic.id}"

      expect(response.body).not_to include(
        solved_schema_json(topic:, first_post: p1, answers_json: p2_single_answer_json),
      )
    end
  end
end