<commit_before>require "test_helper"
require "mocha/setup"
require "active_model"
require "action_view"
require "action_view/testing/resolvers"
require "active_support/cache"
require "bath"
require "rails/version"

BLOG_POST_PARTIAL = <<-JBUILDER
  json.extract! blog_post, :id, :body
  json.author do
    first_name, last_name = blog_post.author_name.split(nil, 2)
    json.first_name first_name
    json.last_name last_name
  end
JBUILDER

COLLECTION_PARTIAL = <<-JBUILDER
  json.extract! collection, :id, :name
JBUILDER

PROFILE_PARTIAL = <<-JBUILDER
  json.email email
JBUILDER

FOOTER_PARTIAL = <<-JBUILDER
  json.terms "You agree"
JBUILDER

BlogPost = Struct.new(:id, :body, :author_name)
Collection = Struct.new(:id, :name)
blog_authors = [ "<NAME>", "<NAME>" ].cycle
BLOG_POST_COLLECTION = Array.new(10){ |i| BlogPost.new(i+1, "post body #{i+1}", blog_authors.next) }
COLLECTION_COLLECTION = Array.new(5){ |i| Collection.new(i+1, "collection #{i+1}") }

ActionView::Template.register_template_handler :bath, Bath::Handler

PARTIALS = {
  "_partial.js.bath"  => "foo ||= 'hello'; json.content foo",
  "_blog_post.js.bath" => BLOG_POST_PARTIAL,
  "_profile.js.bath" => PROFILE_PARTIAL,
  "_footer.js.bath" => FOOTER_PARTIAL,
  "_collection.js.bath" => COLLECTION_PARTIAL
}

def strip_format(str)
  str.strip_heredoc.gsub(/\n\s*/, "")
end

class BathTemplateTest < ActionView::TestCase
  setup do
    self.request_forgery = false
    Relax.configuration.track_assets = []

    # this is a stub. Normally this would be set by the
    # controller locals
    self.relax = {}

    @context = self
    Rails.cache.clear
  end

  cattr_accessor :request_forgery, :relax
  self.request_forgery = false

  def relax_filter
    @relax_filter
  end

  def request
    @request
  end

  def jbuild(source, opts={})
    @relax_filter = opts[:relax_filter]
    @request = opts[:request] || action_controller_test_request
    @rendered = []
    partials = PARTIALS.clone
    partials["test.js.bath"] = source
    resolver = ActionView::FixtureResolver.new(partials)
    lookup_context.view_paths = [resolver]
    lookup_context.formats = [:js]
    template = ActionView::Template.new(source, "test", Bath::Handler, virtual_path: "test")
    template.render(self, {}).strip
  end

  def action_controller_test_request
    if ::Rails.version.start_with?('5')
      ::ActionController::TestRequest.create
    else
      ::ActionController::TestRequest.new
    end
  end

  def cache_keys
    major_v = Rails::VERSION::MAJOR
    minor_v = Rails::VERSION::MINOR
    rails_v = "rails#{major_v}#{minor_v}"
    path = File.expand_path("../fixtures/cache_keys.yaml", __FILE__)
    keys = YAML.load_file(path)
    keys[method_name][rails_v]
  end

  def undef_context_methods(*names)
    self.class_eval do
      names.each do |name|
        undef_method name.to_sym if method_defined?(name.to_sym)
      end
    end
  end

  def protect_against_forgery?
    self.request_forgery
  end

  def form_authenticity_token
    "secret"
  end

  test "rendering" do
    result = jbuild(<<-JBUILDER)
      json.content "hello"
    JBUILDER

    expected = strip_format(<<-JS)
      (function(){
        return ({"data":{"content":"hello"}});
      })()
    JS

    assert_equal expected, result
  end

  test "render with asset tracking" do
    Relax.configuration.track_assets = ['test.js', 'test.css']

    result = jbuild(<<-TEMPLATE)
      json.content "hello"
    TEMPLATE

    expected = strip_format(<<-JS)
      (function(){
        return ({"data":{"content":"hello"},"assets":["/test.js","/test.css"]});
      })()
    JS

    assert_equal expected, result
  end


  test "render with csrf token when request forgery is on" do
    self.request_forgery = true
    # csrf_meta_tags also delegate authenticity tokens to the controller
    # here we provide a simple mock to the context

    result = jbuild(<<-TEMPLATE)
      json.content "hello"<commit_msg>Add tests for duplicate set!<commit_after>require "test_helper"
require "mocha/setup"
require "active_model"
require "action_view"
require "action_view/testing/resolvers"
require "active_support/cache"
require "bath"
require "rails/version"

BLOG_POST_PARTIAL = <<-JBUILDER
  json.extract! blog_post, :id, :body
  json.author do
    first_name, last_name = blog_post.author_name.split(nil, 2)
    json.first_name first_name
    json.last_name last_name
  end
JBUILDER

COLLECTION_PARTIAL = <<-JBUILDER
  json.extract! collection, :id, :name
JBUILDER

PROFILE_PARTIAL = <<-JBUILDER
  json.email email
JBUILDER

FOOTER_PARTIAL = <<-JBUILDER
  json.terms "You agree"
JBUILDER

BlogPost = Struct.new(:id, :body, :author_name)
Collection = Struct.new(:id, :name)
blog_authors = [ "<NAME>", "<NAME>" ].cycle
BLOG_POST_COLLECTION = Array.new(10){ |i| BlogPost.new(i+1, "post body #{i+1}", blog_authors.next) }
COLLECTION_COLLECTION = Array.new(5){ |i| Collection.new(i+1, "collection #{i+1}") }

ActionView::Template.register_template_handler :bath, Bath::Handler

PARTIALS = {
  "_partial.js.bath"  => "foo ||= 'hello'; json.content foo",
  "_blog_post.js.bath" => BLOG_POST_PARTIAL,
  "_profile.js.bath" => PROFILE_PARTIAL,
  "_footer.js.bath" => FOOTER_PARTIAL,
  "_collection.js.bath" => COLLECTION_PARTIAL
}

def strip_format(str)
  str.strip_heredoc.gsub(/\n\s*/, "")
end

class BathTemplateTest < ActionView::TestCase
  setup do
    self.request_forgery = false
    Relax.configuration.track_assets = []

    # this is a stub. Normally this would be set by the
    # controller locals
    self.relax = {}

    @context = self
    Rails.cache.clear
  end

  cattr_accessor :request_forgery, :relax
  self.request_forgery = false

  def relax_filter
    @relax_filter
  end

  def request
    @request
  end

  def jbuild(source, opts={})
    @relax_filter = opts[:relax_filter]
    @request = opts[:request] || action_controller_test_request
    @rendered = []
    partials = PARTIALS.clone
    partials["test.js.bath"] = source
    resolver = ActionView::FixtureResolver.new(partials)
    lookup_context.view_paths = [resolver]
    lookup_context.formats = [:js]
    template = ActionView::Template.new(source, "test", Bath::Handler, virtual_path: "test")
    template.render(self, {}).strip
  end

  def action_controller_test_request
    if ::Rails.version.start_with?('5')
      ::ActionController::TestRequest.create
    else
      ::ActionController::TestRequest.new
    end
  end

  def cache_keys
    major_v = Rails::VERSION::MAJOR
    minor_v = Rails::VERSION::MINOR
    rails_v = "rails#{major_v}#{minor_v}"
    path = File.expand_path("../fixtures/cache_keys.yaml", __FILE__)
    keys = YAML.load_file(path)
    keys[method_name][rails_v]
  end

  def undef_context_methods(*names)
    self.class_eval do
      names.each do |name|
        undef_method name.to_sym if method_defined?(name.to_sym)
      end
    end
  end

  def protect_against_forgery?
    self.request_forgery
  end

  def form_authenticity_token
    "secret"
  end

  test "rendering" do
    result = jbuild(<<-JBUILDER)
      json.content "hello"
    JBUILDER

    expected = strip_format(<<-JS)
      (function(){
        return ({"data":{"content":"hello"}});
      })()
    JS

    assert_equal expected, result
  end

  test "rendering with duplicate sets" do
    result = jbuild(<<-JBUILDER)
      json.content do
        json.greeting 'miss'
      end

      json.content do
        json.greeting 'hit'
      end
    JBUILDER

    expected = strip_format(<<-JS)
      (function(){
        return ({"data":{"content":{"greeting":"hit"}}});
      })()
    JS

    assert_equal expected, result
  end

  test "render with asset tracking" do
    Relax.configuration.track_assets = ['test.js', 'test.css']

    result = jbuild(<<-TEMPLATE)
      json.content "hello"
    TEMPLATE

    expected = strip_format(<<-JS)
      (function(){
        return ({"data":{"content":"hello"},"assets":["/test.js","/test.css"]});
      })()
    JS

    assert_equal expected, result
  end


  test "render with csrf token when request forgery is on" do
    self.request_forgery = true
    # csrf_meta_tags also delegate authenticity tokens to the controller
    # here we provide a simple mock to the context

    result = jbuild(<<-TEMPLATE)
      json.content "hello"
{'fraction_non_alphanumeric': 0.1263895601739971, 'fraction_numerical': 0.0021749637506041568, 'mean_word_length': 3.5957801221543586, 'pattern_counts': {'":': 13, '<': 49, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6244491', 'n_tokens_mistral': 2916, 'n_tokens_neox': 2820, 'n_words': 606}