PageRenderTime 42ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/spec/support/helpers/test_env.rb

https://gitlab.com/wolfgang42/gitlab-ce
Ruby | 453 lines | 333 code | 85 blank | 35 comment | 14 complexity | f94c76c5cf67ef874e6f4705de827a90 MD5 | raw file
  1. # frozen_string_literal: true
  2. require 'rspec/mocks'
  3. require 'toml-rb'
  4. module TestEnv
  5. extend ActiveSupport::Concern
  6. extend self
  7. ComponentFailedToInstallError = Class.new(StandardError)
  8. # When developing the seed repository, comment out the branch you will modify.
  9. BRANCH_SHA = {
  10. 'signed-commits' => '6101e87',
  11. 'not-merged-branch' => 'b83d6e3',
  12. 'branch-merged' => '498214d',
  13. 'empty-branch' => '7efb185',
  14. 'ends-with.json' => '98b0d8b',
  15. 'flatten-dir' => 'e56497b',
  16. 'feature' => '0b4bc9a',
  17. 'feature_conflict' => 'bb5206f',
  18. 'fix' => '48f0be4',
  19. 'improve/awesome' => '5937ac0',
  20. 'merged-target' => '21751bf',
  21. 'markdown' => '0ed8c6c',
  22. 'lfs' => '55bc176',
  23. 'master' => 'b83d6e3',
  24. 'merge-test' => '5937ac0',
  25. "'test'" => 'e56497b',
  26. 'orphaned-branch' => '45127a9',
  27. 'binary-encoding' => '7b1cf43',
  28. 'gitattributes' => '5a62481',
  29. 'expand-collapse-diffs' => '4842455',
  30. 'symlink-expand-diff' => '81e6355',
  31. 'expand-collapse-files' => '025db92',
  32. 'expand-collapse-lines' => '238e82d',
  33. 'pages-deploy' => '7897d5b',
  34. 'pages-deploy-target' => '7975be0',
  35. 'audio' => 'c3c21fd',
  36. 'video' => '8879059',
  37. 'add-balsamiq-file' => 'b89b56d',
  38. 'crlf-diff' => '5938907',
  39. 'conflict-start' => '824be60',
  40. 'conflict-resolvable' => '1450cd6',
  41. 'conflict-binary-file' => '259a6fb',
  42. 'conflict-contains-conflict-markers' => '78a3086',
  43. 'conflict-missing-side' => 'eb227b3',
  44. 'conflict-non-utf8' => 'd0a293c',
  45. 'conflict-too-large' => '39fa04f',
  46. 'deleted-image-test' => '6c17798',
  47. 'wip' => 'b9238ee',
  48. 'csv' => '3dd0896',
  49. 'v1.1.0' => 'b83d6e3',
  50. 'add-ipython-files' => '93ee732',
  51. 'add-pdf-file' => 'e774ebd',
  52. 'squash-large-files' => '54cec52',
  53. 'add-pdf-text-binary' => '79faa7b',
  54. 'add_images_and_changes' => '010d106',
  55. 'update-gitlab-shell-v-6-0-1' => '2f61d70',
  56. 'update-gitlab-shell-v-6-0-3' => 'de78448',
  57. 'merge-commit-analyze-before' => '1adbdef',
  58. 'merge-commit-analyze-side-branch' => '8a99451',
  59. 'merge-commit-analyze-after' => '646ece5',
  60. '2-mb-file' => 'bf12d25',
  61. 'before-create-delete-modify-move' => '845009f',
  62. 'between-create-delete-modify-move' => '3f5f443',
  63. 'after-create-delete-modify-move' => 'ba3faa7',
  64. 'with-codeowners' => '219560e',
  65. 'submodule_inside_folder' => 'b491b92',
  66. 'png-lfs' => 'fe42f41',
  67. 'sha-starting-with-large-number' => '8426165',
  68. 'invalid-utf8-diff-paths' => '99e4853'
  69. }.freeze
  70. # gitlab-test-fork is a fork of gitlab-fork, but we don't necessarily
  71. # need to keep all the branches in sync.
  72. # We currently only need a subset of the branches
  73. FORKED_BRANCH_SHA = {
  74. 'add-submodule-version-bump' => '3f547c0',
  75. 'master' => '5937ac0',
  76. 'remove-submodule' => '2a33e0c',
  77. 'conflict-resolvable-fork' => '404fa3f'
  78. }.freeze
  79. TMP_TEST_PATH = Rails.root.join('tmp', 'tests', '**')
  80. REPOS_STORAGE = 'default'.freeze
  81. # Test environment
  82. #
  83. # See gitlab.yml.example test section for paths
  84. #
  85. def init(opts = {})
  86. unless Rails.env.test?
  87. puts "\nTestEnv.init can only be run if `RAILS_ENV` is set to 'test' not '#{Rails.env}'!\n"
  88. exit 1
  89. end
  90. # Disable mailer for spinach tests
  91. disable_mailer if opts[:mailer] == false
  92. clean_test_path
  93. setup_gitlab_shell
  94. setup_gitaly
  95. # Create repository for FactoryBot.create(:project)
  96. setup_factory_repo
  97. # Create repository for FactoryBot.create(:forked_project_with_submodules)
  98. setup_forked_repo
  99. end
  100. included do |config|
  101. config.append_before do
  102. set_current_example_group
  103. end
  104. end
  105. def disable_mailer
  106. allow_any_instance_of(NotificationService).to receive(:mailer)
  107. .and_return(double.as_null_object)
  108. end
  109. def enable_mailer
  110. allow_any_instance_of(NotificationService).to receive(:mailer)
  111. .and_call_original
  112. end
  113. # Clean /tmp/tests
  114. #
  115. # Keeps gitlab-shell and gitlab-test
  116. def clean_test_path
  117. Dir[TMP_TEST_PATH].each do |entry|
  118. unless test_dirs.include?(File.basename(entry))
  119. FileUtils.rm_rf(entry)
  120. end
  121. end
  122. FileUtils.mkdir_p(repos_path)
  123. FileUtils.mkdir_p(backup_path)
  124. FileUtils.mkdir_p(pages_path)
  125. FileUtils.mkdir_p(artifacts_path)
  126. end
  127. def setup_gitlab_shell
  128. FileUtils.mkdir_p(Gitlab.config.gitlab_shell.path)
  129. end
  130. def setup_gitaly
  131. install_gitaly_args = [gitaly_dir, repos_path, gitaly_url].compact.join(',')
  132. component_timed_setup('Gitaly',
  133. install_dir: gitaly_dir,
  134. version: Gitlab::GitalyClient.expected_server_version,
  135. task: "gitlab:gitaly:install[#{install_gitaly_args}]") do
  136. Gitlab::SetupHelper.create_gitaly_configuration(gitaly_dir, { 'default' => repos_path }, force: true)
  137. start_gitaly(gitaly_dir)
  138. end
  139. end
  140. def gitaly_socket_path
  141. Gitlab::GitalyClient.address('default').sub(/\Aunix:/, '')
  142. end
  143. def gitaly_dir
  144. File.dirname(gitaly_socket_path)
  145. end
  146. def start_gitaly(gitaly_dir)
  147. if ci?
  148. # Gitaly has been spawned outside this process already
  149. return
  150. end
  151. FileUtils.mkdir_p("tmp/tests/second_storage") unless File.exist?("tmp/tests/second_storage")
  152. spawn_script = Rails.root.join('scripts/gitaly-test-spawn').to_s
  153. Bundler.with_original_env do
  154. unless system(spawn_script)
  155. message = 'gitaly spawn failed'
  156. message += " (try `rm -rf #{gitaly_dir}` ?)" unless ci?
  157. raise message
  158. end
  159. end
  160. @gitaly_pid = Integer(File.read('tmp/tests/gitaly.pid'))
  161. Kernel.at_exit { stop_gitaly }
  162. wait_gitaly
  163. end
  164. def wait_gitaly
  165. sleep_time = 10
  166. sleep_interval = 0.1
  167. socket = Gitlab::GitalyClient.address('default').sub('unix:', '')
  168. Integer(sleep_time / sleep_interval).times do
  169. Socket.unix(socket)
  170. return
  171. rescue
  172. sleep sleep_interval
  173. end
  174. raise "could not connect to gitaly at #{socket.inspect} after #{sleep_time} seconds"
  175. end
  176. def stop_gitaly
  177. return unless @gitaly_pid
  178. Process.kill('KILL', @gitaly_pid)
  179. rescue Errno::ESRCH
  180. # The process can already be gone if the test run was INTerrupted.
  181. end
  182. def gitaly_url
  183. ENV.fetch('GITALY_REPO_URL', nil)
  184. end
  185. def setup_factory_repo
  186. setup_repo(factory_repo_path, factory_repo_path_bare, factory_repo_name,
  187. BRANCH_SHA)
  188. end
  189. # This repo has a submodule commit that is not present in the main test
  190. # repository.
  191. def setup_forked_repo
  192. setup_repo(forked_repo_path, forked_repo_path_bare, forked_repo_name,
  193. FORKED_BRANCH_SHA)
  194. end
  195. def setup_repo(repo_path, repo_path_bare, repo_name, refs)
  196. clone_url = "https://gitlab.com/gitlab-org/#{repo_name}.git"
  197. unless File.directory?(repo_path)
  198. system(*%W(#{Gitlab.config.git.bin_path} clone -q #{clone_url} #{repo_path}))
  199. end
  200. set_repo_refs(repo_path, refs)
  201. unless File.directory?(repo_path_bare)
  202. # We must copy bare repositories because we will push to them.
  203. system(git_env, *%W(#{Gitlab.config.git.bin_path} clone -q --bare #{repo_path} #{repo_path_bare}))
  204. end
  205. end
  206. def copy_repo(project, bare_repo:, refs:)
  207. target_repo_path = File.expand_path(repos_path + "/#{project.disk_path}.git")
  208. FileUtils.mkdir_p(target_repo_path)
  209. FileUtils.cp_r("#{File.expand_path(bare_repo)}/.", target_repo_path)
  210. FileUtils.chmod_R 0755, target_repo_path
  211. end
  212. def rm_storage_dir(storage, dir)
  213. Gitlab::GitalyClient::StorageSettings.allow_disk_access do
  214. repos_path = Gitlab.config.repositories.storages[storage].legacy_disk_path
  215. target_repo_refs_path = File.join(repos_path, dir)
  216. FileUtils.remove_dir(target_repo_refs_path)
  217. end
  218. rescue Errno::ENOENT
  219. end
  220. def storage_dir_exists?(storage, dir)
  221. Gitlab::GitalyClient::StorageSettings.allow_disk_access do
  222. repos_path = Gitlab.config.repositories.storages[storage].legacy_disk_path
  223. File.exist?(File.join(repos_path, dir))
  224. end
  225. end
  226. def create_bare_repository(path)
  227. FileUtils.mkdir_p(path)
  228. system(git_env, *%W(#{Gitlab.config.git.bin_path} -C #{path} init --bare),
  229. out: '/dev/null',
  230. err: '/dev/null')
  231. end
  232. def repos_path
  233. @repos_path ||= Gitlab.config.repositories.storages[REPOS_STORAGE].legacy_disk_path
  234. end
  235. def backup_path
  236. Gitlab.config.backup.path
  237. end
  238. def pages_path
  239. Gitlab.config.pages.path
  240. end
  241. def artifacts_path
  242. Gitlab.config.artifacts.storage_path
  243. end
  244. # When no cached assets exist, manually hit the root path to create them
  245. #
  246. # Otherwise they'd be created by the first test, often timing out and
  247. # causing a transient test failure
  248. def eager_load_driver_server
  249. return unless defined?(Capybara)
  250. puts "Starting the Capybara driver server..."
  251. Capybara.current_session.visit '/'
  252. end
  253. def factory_repo_path_bare
  254. "#{factory_repo_path}_bare"
  255. end
  256. def forked_repo_path_bare
  257. "#{forked_repo_path}_bare"
  258. end
  259. def with_empty_bare_repository(name = nil)
  260. path = Rails.root.join('tmp/tests', name || 'empty-bare-repository').to_s
  261. yield(Rugged::Repository.init_at(path, :bare))
  262. ensure
  263. FileUtils.rm_rf(path)
  264. end
  265. def current_example_group
  266. Thread.current[:current_example_group]
  267. end
  268. # looking for a top-level `describe`
  269. def topmost_example_group
  270. example_group = current_example_group
  271. example_group = example_group[:parent_example_group] until example_group[:parent_example_group].nil?
  272. example_group
  273. end
  274. private
  275. def set_current_example_group
  276. Thread.current[:current_example_group] = ::RSpec.current_example.metadata[:example_group]
  277. end
  278. # These are directories that should be preserved at cleanup time
  279. def test_dirs
  280. @test_dirs ||= %w[
  281. frontend
  282. gitaly
  283. gitlab-shell
  284. gitlab-test
  285. gitlab-test_bare
  286. gitlab-test-fork
  287. gitlab-test-fork_bare
  288. ]
  289. end
  290. def factory_repo_path
  291. @factory_repo_path ||= Rails.root.join('tmp', 'tests', factory_repo_name)
  292. end
  293. def factory_repo_name
  294. 'gitlab-test'
  295. end
  296. def forked_repo_path
  297. @forked_repo_path ||= Rails.root.join('tmp', 'tests', forked_repo_name)
  298. end
  299. def forked_repo_name
  300. 'gitlab-test-fork'
  301. end
  302. # Prevent developer git configurations from being persisted to test
  303. # repositories
  304. def git_env
  305. { 'GIT_TEMPLATE_DIR' => '' }
  306. end
  307. def set_repo_refs(repo_path, branch_sha)
  308. instructions = branch_sha.map { |branch, sha| "update refs/heads/#{branch}\x00#{sha}\x00" }.join("\x00") << "\x00"
  309. update_refs = %W(#{Gitlab.config.git.bin_path} update-ref --stdin -z)
  310. reset = proc do
  311. Dir.chdir(repo_path) do
  312. IO.popen(update_refs, "w") { |io| io.write(instructions) }
  313. $?.success?
  314. end
  315. end
  316. # Try to reset without fetching to avoid using the network.
  317. unless reset.call
  318. raise 'Could not fetch test seed repository.' unless system(*%W(#{Gitlab.config.git.bin_path} -C #{repo_path} fetch origin))
  319. raise "Could not update test seed repository, please delete #{repo_path} and try again" unless reset.call
  320. end
  321. end
  322. def component_timed_setup(component, install_dir:, version:, task:)
  323. puts "\n==> Setting up #{component}..."
  324. start = Time.now
  325. ensure_component_dir_name_is_correct!(component, install_dir)
  326. # On CI, once installed, components never need update
  327. return if File.exist?(install_dir) && ci?
  328. if component_needs_update?(install_dir, version)
  329. # Cleanup the component entirely to ensure we start fresh
  330. FileUtils.rm_rf(install_dir)
  331. unless system('rake', task)
  332. raise ComponentFailedToInstallError
  333. end
  334. end
  335. yield if block_given?
  336. rescue ComponentFailedToInstallError
  337. puts "\n#{component} failed to install, cleaning up #{install_dir}!\n"
  338. FileUtils.rm_rf(install_dir)
  339. exit 1
  340. ensure
  341. puts " #{component} set up in #{Time.now - start} seconds...\n"
  342. end
  343. def ci?
  344. ENV['CI'].present?
  345. end
  346. def ensure_component_dir_name_is_correct!(component, path)
  347. actual_component_dir_name = File.basename(path)
  348. expected_component_dir_name = component.parameterize
  349. unless actual_component_dir_name == expected_component_dir_name
  350. puts " #{component} install dir should be named '#{expected_component_dir_name}', not '#{actual_component_dir_name}' (full install path given was '#{path}')!\n"
  351. exit 1
  352. end
  353. end
  354. def component_needs_update?(component_folder, expected_version)
  355. # Allow local overrides of the component for tests during development
  356. return false if Rails.env.test? && File.symlink?(component_folder)
  357. version = File.read(File.join(component_folder, 'VERSION')).strip
  358. # Notice that this will always yield true when using branch versions
  359. # (`=branch_name`), but that actually makes sure the server is always based
  360. # on the latest branch revision.
  361. version != expected_version
  362. rescue Errno::ENOENT
  363. true
  364. end
  365. end
  366. require_relative('../../../ee/spec/support/helpers/ee/test_env') if Gitlab.ee?
  367. ::TestEnv.prepend_if_ee('::EE::TestEnv')
  368. ::TestEnv.extend_if_ee('::EE::TestEnv')