From c6a96bc5fd8ad2315c6572363ae8ef71b0f97484 Mon Sep 17 00:00:00 2001
From: Gabriel Mazetto <gabriel@gitlab.com>
Date: Mon, 8 Apr 2024 23:36:38 +0200
Subject: [PATCH] Allow running backup against the test environment

---
 .../lib/gitlab/backup/cli/source_context.rb               | 5 +++++
 .../gitlab-backup-cli/lib/gitlab/backup/cli/tasks/task.rb | 3 +++
 gems/gitlab-backup-cli/spec/support/helpers.rb            | 8 ++++++--
 3 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/gems/gitlab-backup-cli/lib/gitlab/backup/cli/source_context.rb b/gems/gitlab-backup-cli/lib/gitlab/backup/cli/source_context.rb
index 354f3068c7f46..4299f2eb2dd3c 100644
--- a/gems/gitlab-backup-cli/lib/gitlab/backup/cli/source_context.rb
+++ b/gems/gitlab-backup-cli/lib/gitlab/backup/cli/source_context.rb
@@ -71,6 +71,11 @@ def upload_path
           # TODO: Use configuration solver
           File.join(Gitlab.config.uploads.storage_path, 'uploads')
         end
+
+        def env
+          @env ||= ActiveSupport::EnvironmentInquirer.new(
+            ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || "development")
+        end
       end
     end
   end
diff --git a/gems/gitlab-backup-cli/lib/gitlab/backup/cli/tasks/task.rb b/gems/gitlab-backup-cli/lib/gitlab/backup/cli/tasks/task.rb
index 995703ee1f1a1..6c6033563311e 100644
--- a/gems/gitlab-backup-cli/lib/gitlab/backup/cli/tasks/task.rb
+++ b/gems/gitlab-backup-cli/lib/gitlab/backup/cli/tasks/task.rb
@@ -24,6 +24,9 @@ def initialize(context:, options:)
           def backup!(backup_path, backup_id)
             backup_output = backup_path.join(destination_path)
 
+            # During test, we ensure storage exists so we can run against `RAILS_ENV=test` environment
+            FileUtils.mkdir_p(storage_path) if context.env.test? && respond_to?(:storage_path, true)
+
             target.dump(backup_output, backup_id)
           end
 
diff --git a/gems/gitlab-backup-cli/spec/support/helpers.rb b/gems/gitlab-backup-cli/spec/support/helpers.rb
index e4ffa4604145b..654e90802c834 100644
--- a/gems/gitlab-backup-cli/spec/support/helpers.rb
+++ b/gems/gitlab-backup-cli/spec/support/helpers.rb
@@ -1,6 +1,6 @@
 # frozen_string_literal: true
 
-FakeContext = Struct.new(:gitlab_version, :backup_basedir, keyword_init: true)
+FakeContext = Struct.new(:gitlab_version, :backup_basedir, :env, keyword_init: true)
 
 def spec_path
   Pathname.new(__dir__).join('..').expand_path
@@ -15,5 +15,9 @@ def stub_env(var, return_value)
 end
 
 def build_fake_context
-  FakeContext.new(gitlab_version: '16.10', backup_basedir: temp_path.join('backups'))
+  FakeContext.new(
+    gitlab_version: '16.10',
+    backup_basedir: temp_path.join('backups'),
+    env: ActiveSupport::EnvironmentInquirer.new('test')
+  )
 end
-- 
GitLab