BigW Consortium Gitlab

javascript_fixtures_helpers.rb 1.95 KB
Newer Older
1
require 'action_dispatch/testing/test_request'
2 3 4 5 6 7
require 'fileutils'
require 'gitlab/popen'

module JavaScriptFixturesHelpers
  include Gitlab::Popen

8
  FIXTURE_PATH = 'spec/javascripts/fixtures'.freeze
9 10 11 12 13 14 15

  # Public: Removes all fixture files from given directory
  #
  # directory_name - directory of the fixtures (relative to FIXTURE_PATH)
  #
  def clean_frontend_fixtures(directory_name)
    directory_name = File.expand_path(directory_name, FIXTURE_PATH)
16
    Dir[File.expand_path('*.html.raw', directory_name)].each do |file_name|
17 18 19 20 21 22
      FileUtils.rm(file_name)
    end
  end

  # Public: Store a response object as fixture file
  #
23
  # response - string or response object to store
24 25 26 27
  # fixture_file_name - file name to store the fixture in (relative to FIXTURE_PATH)
  #
  def store_frontend_fixture(response, fixture_file_name)
    fixture_file_name = File.expand_path(fixture_file_name, FIXTURE_PATH)
28 29 30 31 32 33
    fixture = response.respond_to?(:body) ? parse_response(response) : response

    FileUtils.mkdir_p(File.dirname(fixture_file_name))
    File.write(fixture_file_name, fixture)
  end

34 35 36 37
  def remove_repository(project)
    Gitlab::Shell.new.remove_repository(project.repository_storage_path, project.disk_path)
  end

38 39 40 41 42 43 44
  private

  # Private: Prepare a response object for use as a frontend fixture
  #
  # response - response object to prepare
  #
  def parse_response(response)
45
    fixture = response.body
46
    fixture.force_encoding("utf-8")
47 48 49 50 51

    response_mime_type = Mime::Type.lookup(response.content_type)
    if response_mime_type.html?
      doc = Nokogiri::HTML::DocumentFragment.parse(fixture)

52 53 54
      link_tags = doc.css('link')
      link_tags.remove

55
      scripts = doc.css("script:not([type='text/template']):not([type='text/x-template'])")
56 57 58 59 60
      scripts.remove

      fixture = doc.to_html

      # replace relative links
61 62
      test_host = ActionDispatch::TestRequest::DEFAULT_ENV['HTTP_HOST']
      fixture.gsub!(%r{="/}, "=\"http://#{test_host}/")
63 64
    end

65
    fixture
66 67
  end
end