diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2022-06-02 06:08:40 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2022-06-02 06:08:40 +0300 |
commit | 61d5cc9f2340b618b39ad3fdba6b3661646306a5 (patch) | |
tree | c78312cb7aae3d724887c002ae6cdf3447bb3f27 /spec | |
parent | e35ac5e805fcb47d43591f605a9d5abfb75f44b8 (diff) |
Add latest changes from gitlab-org/gitlab@master
Diffstat (limited to 'spec')
15 files changed, 486 insertions, 293 deletions
diff --git a/spec/controllers/projects/prometheus/alerts_controller_spec.rb b/spec/controllers/projects/prometheus/alerts_controller_spec.rb index af40eef6dda..2c2c8180143 100644 --- a/spec/controllers/projects/prometheus/alerts_controller_spec.rb +++ b/spec/controllers/projects/prometheus/alerts_controller_spec.rb @@ -53,57 +53,6 @@ RSpec.describe Projects::Prometheus::AlertsController do end end - describe 'GET #show' do - let(:alert) do - create(:prometheus_alert, - :with_runbook_url, - project: project, - environment: environment, - prometheus_metric: metric) - end - - def make_request(opts = {}) - get :show, params: request_params( - opts, - id: alert.prometheus_metric_id, - environment_id: environment - ) - end - - context 'when alert does not exist' do - it 'returns not_found' do - make_request(id: 0) - - expect(response).to have_gitlab_http_status(:not_found) - end - end - - context 'when alert exists' do - let(:alert_params) do - { - 'id' => alert.id, - 'title' => alert.title, - 'query' => alert.query, - 'operator' => alert.computed_operator, - 'threshold' => alert.threshold, - 'runbook_url' => alert.runbook_url, - 'alert_path' => alert_path(alert) - } - end - - it 'renders the alert' do - make_request - - expect(response).to have_gitlab_http_status(:ok) - expect(json_response).to include(alert_params) - end - - it_behaves_like 'unprivileged' - it_behaves_like 'project non-specific environment', :not_found - it_behaves_like 'project non-specific metric', :not_found - end - end - describe 'POST #notify' do let(:alert_1) { build(:alert_management_alert, :prometheus, project: project) } let(:alert_2) { build(:alert_management_alert, :prometheus, project: project) } diff --git a/spec/frontend/issuable/popover/components/__snapshots__/mr_popover_spec.js.snap b/spec/frontend/issuable/popover/components/__snapshots__/mr_popover_spec.js.snap deleted file mode 100644 index a03d8bf5bf4..00000000000 --- a/spec/frontend/issuable/popover/components/__snapshots__/mr_popover_spec.js.snap +++ /dev/null @@ -1,93 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`MR Popover loaded state matches the snapshot 1`] = ` -<gl-popover-stub - boundary="viewport" - cssclasses="" - placement="top" - show="" - target="" -> - <div - class="mr-popover" - > - <div - class="d-flex align-items-center justify-content-between" - > - <div - class="d-inline-flex align-items-center" - > - <gl-badge-stub - class="gl-mr-3" - size="md" - variant="success" - > - - Open - - </gl-badge-stub> - - <span - class="gl-text-secondary" - > - Opened - <time> - just now - </time> - </span> - </div> - - <ci-icon-stub - cssclasses="" - size="16" - status="[object Object]" - /> - </div> - - <h5 - class="my-2" - > - Updated Title - </h5> - - <div - class="gl-text-secondary" - > - - foo/bar!1 - - </div> - </div> -</gl-popover-stub> -`; - -exports[`MR Popover shows skeleton-loader while apollo is loading 1`] = ` -<gl-popover-stub - boundary="viewport" - cssclasses="" - placement="top" - show="" - target="" -> - <div - class="mr-popover" - > - <div> - <gl-skeleton-loading-stub - class="animation-container-small mt-1" - lines="1" - /> - </div> - - <!----> - - <div - class="gl-text-secondary" - > - - foo/bar!1 - - </div> - </div> -</gl-popover-stub> -`; diff --git a/spec/frontend/issuable/popover/components/mr_popover_spec.js b/spec/frontend/issuable/popover/components/mr_popover_spec.js index e66c6e22947..5fdd1e6e8fc 100644 --- a/spec/frontend/issuable/popover/components/mr_popover_spec.js +++ b/spec/frontend/issuable/popover/components/mr_popover_spec.js @@ -1,80 +1,119 @@ +import { GlSkeletonLoader } from '@gitlab/ui'; import { shallowMount } from '@vue/test-utils'; -import { nextTick } from 'vue'; +import Vue from 'vue'; +import VueApollo from 'vue-apollo'; +import createMockApollo from 'helpers/mock_apollo_helper'; +import waitForPromises from 'helpers/wait_for_promises'; import MRPopover from '~/issuable/popover/components/mr_popover.vue'; +import mergeRequestQuery from '~/issuable/popover/queries/merge_request.query.graphql'; import CiIcon from '~/vue_shared/components/ci_icon.vue'; describe('MR Popover', () => { let wrapper; - beforeEach(() => { + Vue.use(VueApollo); + + const mrQueryResponse = { + data: { + project: { + __typename: 'Project', + id: '1', + mergeRequest: { + __typename: 'Merge Request', + id: 'gid://gitlab/Merge_Request/1', + createdAt: '2020-07-01T04:08:01Z', + state: 'opened', + title: 'MR title', + headPipeline: { + id: '1', + detailedStatus: { + id: '1', + icon: 'status_success', + group: 'success', + }, + }, + }, + }, + }, + }; + + const mrQueryResponseWithoutDetailedStatus = { + data: { + project: { + __typename: 'Project', + id: '1', + mergeRequest: { + __typename: 'Merge Request', + id: 'gid://gitlab/Merge_Request/1', + createdAt: '2020-07-01T04:08:01Z', + state: 'opened', + title: 'MR title', + headPipeline: { + id: '1', + detailedStatus: null, + }, + }, + }, + }, + }; + + const mountComponent = ({ + queryResponse = jest.fn().mockResolvedValue(mrQueryResponse), + } = {}) => { wrapper = shallowMount(MRPopover, { + apolloProvider: createMockApollo([[mergeRequestQuery, queryResponse]]), propsData: { target: document.createElement('a'), projectPath: 'foo/bar', iid: '1', - cachedTitle: 'MR Title', - }, - mocks: { - $apollo: { - queries: { - mergeRequest: { - loading: false, - }, - }, - }, + cachedTitle: 'Cached Title', }, }); + }; + + afterEach(() => { + wrapper.destroy(); }); - it('shows skeleton-loader while apollo is loading', async () => { - wrapper.vm.$apollo.queries.mergeRequest.loading = true; + it('shows skeleton-loader while apollo is loading', () => { + mountComponent(); - await nextTick(); - expect(wrapper.element).toMatchSnapshot(); + expect(wrapper.findComponent(GlSkeletonLoader).exists()).toBe(true); }); - describe('loaded state', () => { - it('matches the snapshot', async () => { - // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details - // eslint-disable-next-line no-restricted-syntax - wrapper.setData({ - mergeRequest: { - title: 'Updated Title', - state: 'opened', - createdAt: new Date(), - headPipeline: { - detailedStatus: { - group: 'success', - status: 'status_success', - }, - }, - }, - }); + describe('when loaded', () => { + beforeEach(() => { + mountComponent(); + return waitForPromises(); + }); - await nextTick(); - expect(wrapper.element).toMatchSnapshot(); + it('shows opened time', () => { + expect(wrapper.text()).toContain('Opened 4 days ago'); }); - it('does not show CI Icon if there is no pipeline data', async () => { - // setData usage is discouraged. See https://gitlab.com/groups/gitlab-org/-/epics/7330 for details - // eslint-disable-next-line no-restricted-syntax - wrapper.setData({ - mergeRequest: { - state: 'opened', - headPipeline: null, - stateHumanName: 'Open', - title: 'Merge Request Title', - createdAt: new Date(), - }, - }); + it('shows title', () => { + expect(wrapper.find('h5').text()).toBe(mrQueryResponse.data.project.mergeRequest.title); + }); - await nextTick(); - expect(wrapper.find(CiIcon).exists()).toBe(false); + it('shows reference', () => { + expect(wrapper.text()).toContain('foo/bar!1'); + }); + + it('shows CI Icon if there is pipeline data', async () => { + expect(wrapper.findComponent(CiIcon).exists()).toBe(true); + }); + }); + + describe('without detailed status', () => { + beforeEach(() => { + mountComponent({ + queryResponse: jest.fn().mockResolvedValue(mrQueryResponseWithoutDetailedStatus), + }); + return waitForPromises(); }); - it('falls back to cached MR title when request fails', async () => { - await nextTick(); - expect(wrapper.text()).toContain('MR Title'); + it('does not show CI icon if there is no pipeline data', async () => { + expect(wrapper.findComponent(CiIcon).exists()).toBe(false); }); }); }); diff --git a/spec/lib/gitlab/metrics/dashboard/processor_spec.rb b/spec/lib/gitlab/metrics/dashboard/processor_spec.rb index 14a4c01fce3..52908a0b339 100644 --- a/spec/lib/gitlab/metrics/dashboard/processor_spec.rb +++ b/spec/lib/gitlab/metrics/dashboard/processor_spec.rb @@ -16,7 +16,6 @@ RSpec.describe Gitlab::Metrics::Dashboard::Processor do Gitlab::Metrics::Dashboard::Stages::CustomMetricsInserter, Gitlab::Metrics::Dashboard::Stages::CustomMetricsDetailsInserter, Gitlab::Metrics::Dashboard::Stages::MetricEndpointInserter, - Gitlab::Metrics::Dashboard::Stages::AlertsInserter, Gitlab::Metrics::Dashboard::Stages::PanelIdsInserter, Gitlab::Metrics::Dashboard::Stages::UrlValidator ] @@ -118,43 +117,6 @@ RSpec.describe Gitlab::Metrics::Dashboard::Processor do end end - context 'when the dashboard references persisted metrics with alerts' do - let!(:alert) do - create( - :prometheus_alert, - environment: environment, - project: project, - prometheus_metric: persisted_metric - ) - end - - shared_examples_for 'has saved alerts' do - it 'includes an alert path' do - target_metric = all_metrics.find { |metric| metric[:metric_id] == persisted_metric.id } - - expect(target_metric).to be_a Hash - expect(target_metric).to include(:alert_path) - expect(target_metric[:alert_path]).to include( - project.path, - persisted_metric.id.to_s, - environment.id.to_s - ) - end - end - - context 'that are shared across projects' do - let!(:persisted_metric) { create(:prometheus_metric, :common, identifier: 'metric_a1') } - - it_behaves_like 'has saved alerts' - end - - context 'when the project has associated metrics' do - let!(:persisted_metric) { create(:prometheus_metric, project: project, group: :business) } - - it_behaves_like 'has saved alerts' - end - end - context 'when there are no alerts' do let!(:persisted_metric) { create(:prometheus_metric, :common, identifier: 'metric_a1') } diff --git a/spec/models/hooks/web_hook_log_spec.rb b/spec/models/hooks/web_hook_log_spec.rb index 9cfbb14e087..e1fea3318f6 100644 --- a/spec/models/hooks/web_hook_log_spec.rb +++ b/spec/models/hooks/web_hook_log_spec.rb @@ -48,6 +48,62 @@ RSpec.describe WebHookLog do end end + describe '.delete_batch_for' do + let(:hook) { create(:project_hook) } + + before do + create_list(:web_hook_log, 3, web_hook: hook) + create_list(:web_hook_log, 3) + end + + subject { described_class.delete_batch_for(hook, batch_size: batch_size) } + + shared_examples 'deletes batch of web hook logs' do + it { is_expected.to be(batch_size <= 3) } + + it 'deletes min(batch_size, total) records' do + deleted = [batch_size, 3].min + + expect { subject }.to change(described_class, :count).by(-deleted) + end + end + + context 'when the batch size is less than one' do + let(:batch_size) { 0 } + + it 'raises an argument error' do + expect { subject }.to raise_error(ArgumentError) + end + end + + context 'when the batch size is smaller than the total' do + let(:batch_size) { 2 } + + include_examples 'deletes batch of web hook logs' + end + + context 'when the batch size is equal to the total' do + let(:batch_size) { 3 } + + include_examples 'deletes batch of web hook logs' + end + + context 'when the batch size is greater than the total' do + let(:batch_size) { 1000 } + + include_examples 'deletes batch of web hook logs' + end + + it 'does not loop forever' do + batches = 0 + batches += 1 while described_class.delete_batch_for(hook, batch_size: 1) + + expect(hook.web_hook_logs).to be_none + expect(described_class.count).to eq 3 + expect(batches).to eq 3 # true three times, stops at first false + end + end + describe '#success?' do let(:web_hook_log) { build(:web_hook_log, response_status: status) } diff --git a/spec/requests/api/internal/workhorse_spec.rb b/spec/requests/api/internal/workhorse_spec.rb new file mode 100644 index 00000000000..e6836d8fef5 --- /dev/null +++ b/spec/requests/api/internal/workhorse_spec.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Internal::Workhorse do + include WorkhorseHelpers + + context '/authorize_upload' do + let_it_be(:user) { create(:user) } + + let(:headers) { {} } + + subject { post(api('/internal/workhorse/authorize_upload'), headers: headers) } + + def expect_status(status) + subject + expect(response).to have_gitlab_http_status(status) + end + + context 'without workhorse internal header' do + it { expect_status(:forbidden) } + end + + context 'with workhorse internal header' do + let(:headers) { workhorse_internal_api_request_header } + + it { expect_status(:unauthorized) } + + context 'as a logged in user' do + before do + login_as(user) + end + + it { expect_status(:success) } + it 'returns the temp upload path' do + subject + expect(json_response['TempPath']).to eq(Rails.root.join('tmp/tests/public/uploads/tmp').to_s) + end + end + end + end +end diff --git a/spec/serializers/prometheus_alert_entity_spec.rb b/spec/serializers/prometheus_alert_entity_spec.rb index ae8c97401f8..91a1e3377c2 100644 --- a/spec/serializers/prometheus_alert_entity_spec.rb +++ b/spec/serializers/prometheus_alert_entity_spec.rb @@ -18,9 +18,5 @@ RSpec.describe PrometheusAlertEntity do it 'exposes prometheus_alert attributes' do expect(subject).to include(:id, :title, :query, :operator, :threshold, :runbook_url) end - - it 'exposes alert_path' do - expect(subject).to include(:alert_path) - end end end diff --git a/spec/services/metrics/dashboard/panel_preview_service_spec.rb b/spec/services/metrics/dashboard/panel_preview_service_spec.rb index 2877d22d1f3..787c61cc918 100644 --- a/spec/services/metrics/dashboard/panel_preview_service_spec.rb +++ b/spec/services/metrics/dashboard/panel_preview_service_spec.rb @@ -45,7 +45,6 @@ RSpec.describe Metrics::Dashboard::PanelPreviewService do ::Gitlab::Metrics::Dashboard::Stages::CommonMetricsInserter, ::Gitlab::Metrics::Dashboard::Stages::MetricEndpointInserter, ::Gitlab::Metrics::Dashboard::Stages::PanelIdsInserter, - ::Gitlab::Metrics::Dashboard::Stages::AlertsInserter, ::Gitlab::Metrics::Dashboard::Stages::UrlValidator ] processor_params = [project, dashboard, sequence, environment: environment] diff --git a/spec/services/projects/destroy_service_spec.rb b/spec/services/projects/destroy_service_spec.rb index adea79509b3..86e9a176798 100644 --- a/spec/services/projects/destroy_service_spec.rb +++ b/spec/services/projects/destroy_service_spec.rb @@ -492,7 +492,6 @@ RSpec.describe Projects::DestroyService, :aggregate_failures, :event_store_publi expect do destroy_project(project, user) end.to change(WebHook, :count).by(-2) - .and change(WebHookLog, :count).by(-1) end context 'when an error is raised deleting webhooks' do diff --git a/spec/services/service_response_spec.rb b/spec/services/service_response_spec.rb index 082ee4ddc67..3ede90fbc44 100644 --- a/spec/services/service_response_spec.rb +++ b/spec/services/service_response_spec.rb @@ -2,7 +2,10 @@ require 'fast_spec_helper' +require 're2' + require_relative '../../app/services/service_response' +require_relative '../../lib/gitlab/error_tracking' RSpec.describe ServiceResponse do describe '.success' do @@ -94,4 +97,76 @@ RSpec.describe ServiceResponse do expect(described_class.error(message: 'error message').errors).to eq(['error message']) end end + + describe '#track_and_raise_exception' do + context 'when successful' do + let(:response) { described_class.success } + + it 'returns self' do + expect(response.track_and_raise_exception).to be response + end + end + + context 'when an error' do + let(:response) { described_class.error(message: 'bang') } + + it 'tracks and raises' do + expect(::Gitlab::ErrorTracking).to receive(:track_and_raise_exception) + .with(StandardError.new('bang'), {}) + + response.track_and_raise_exception + end + + it 'allows specification of error class' do + error = Class.new(StandardError) + expect(::Gitlab::ErrorTracking).to receive(:track_and_raise_exception) + .with(error.new('bang'), {}) + + response.track_and_raise_exception(as: error) + end + + it 'allows extra data for tracking' do + expect(::Gitlab::ErrorTracking).to receive(:track_and_raise_exception) + .with(StandardError.new('bang'), { foo: 1, bar: 2 }) + + response.track_and_raise_exception(foo: 1, bar: 2) + end + end + end + + describe '#track_exception' do + context 'when successful' do + let(:response) { described_class.success } + + it 'returns self' do + expect(response.track_exception).to be response + end + end + + context 'when an error' do + let(:response) { described_class.error(message: 'bang') } + + it 'tracks' do + expect(::Gitlab::ErrorTracking).to receive(:track_exception) + .with(StandardError.new('bang'), {}) + + expect(response.track_exception).to be response + end + + it 'allows specification of error class' do + error = Class.new(StandardError) + expect(::Gitlab::ErrorTracking).to receive(:track_exception) + .with(error.new('bang'), {}) + + expect(response.track_exception(as: error)).to be response + end + + it 'allows extra data for tracking' do + expect(::Gitlab::ErrorTracking).to receive(:track_exception) + .with(StandardError.new('bang'), { foo: 1, bar: 2 }) + + expect(response.track_exception(foo: 1, bar: 2)).to be response + end + end + end end diff --git a/spec/services/web_hooks/destroy_service_spec.rb b/spec/services/web_hooks/destroy_service_spec.rb index 5269fe08ac0..4d9bb18e540 100644 --- a/spec/services/web_hooks/destroy_service_spec.rb +++ b/spec/services/web_hooks/destroy_service_spec.rb @@ -7,50 +7,46 @@ RSpec.describe WebHooks::DestroyService do subject { described_class.new(user) } - shared_examples 'batched destroys' do - it 'destroys all hooks in batches' do - stub_const("#{described_class}::BATCH_SIZE", 1) - expect(subject).to receive(:delete_web_hook_logs_in_batches).exactly(4).times.and_call_original - - expect do - status = subject.execute(hook) - expect(status[:async]).to be false - end - .to change { WebHook.count }.from(1).to(0) - .and change { WebHookLog.count }.from(3).to(0) - end - - it 'returns an error if sync destroy fails' do - expect(hook).to receive(:destroy).and_return(false) + describe '#execute' do + %i[system_hook project_hook].each do |factory| + context "deleting a #{factory}" do + let!(:hook) { create(factory) } # rubocop: disable Rails/SaveBang (false-positive!) + let!(:log) { create_list(:web_hook_log, 3, web_hook: hook) } - result = subject.sync_destroy(hook) - - expect(result[:status]).to eq(:error) - expect(result[:message]).to eq("Unable to destroy #{hook.model_name.human}") - end + it 'is successful' do + expect(subject.execute(hook)).to be_success + end - it 'schedules an async delete' do - stub_const('WebHooks::DestroyService::LOG_COUNT_THRESHOLD', 1) + it 'destroys the hook' do + expect { subject.execute(hook) }.to change(WebHook, :count).from(1).to(0) + end - expect(WebHooks::DestroyWorker).to receive(:perform_async).with(user.id, hook.id).and_call_original + it 'does not destroy logs' do + expect { subject.execute(hook) }.not_to change(WebHookLog, :count) + end - status = subject.execute(hook) + it 'schedules the destruction of logs' do + expect(WebHooks::LogDestroyWorker).to receive(:perform_async).with({ 'hook_id' => hook.id }) + expect(Gitlab::AppLogger).to receive(:info).with(match(/scheduled a deletion of logs/)) - expect(status[:async]).to be true - end - end + subject.execute(hook) + end - context 'with system hook' do - let!(:hook) { create(:system_hook, url: "http://example.com") } - let!(:log) { create_list(:web_hook_log, 3, web_hook: hook) } + context 'when the hook fails to destroy' do + before do + allow(hook).to receive(:destroy).and_return(false) + end - it_behaves_like 'batched destroys' - end + it 'is not a success' do + expect(WebHooks::LogDestroyWorker).not_to receive(:perform_async) - context 'with project hook' do - let!(:hook) { create(:project_hook) } - let!(:log) { create_list(:web_hook_log, 3, web_hook: hook) } + r = subject.execute(hook) - it_behaves_like 'batched destroys' + expect(r).to be_error + expect(r[:message]).to match %r{Unable to destroy} + end + end + end + end end end diff --git a/spec/services/web_hooks/log_destroy_service_spec.rb b/spec/services/web_hooks/log_destroy_service_spec.rb new file mode 100644 index 00000000000..7634726e5a4 --- /dev/null +++ b/spec/services/web_hooks/log_destroy_service_spec.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe WebHooks::LogDestroyService do + subject(:service) { described_class.new(hook.id) } + + describe '#execute' do + shared_examples 'deletes web hook logs for hook' do + before do + create_list(:web_hook_log, 3, web_hook: hook) + hook.destroy! # The LogDestroyService is expected to be called _after_ hook destruction + end + + it 'deletes the logs' do + expect { service.execute } + .to change(WebHookLog, :count).from(3).to(0) + end + + context 'when the data-set exceeds the batch size' do + before do + stub_const("#{described_class}::BATCH_SIZE", 2) + end + + it 'deletes the logs' do + expect { service.execute } + .to change(WebHookLog, :count).from(3).to(0) + end + end + + context 'when it encounters an error' do + before do + allow(WebHookLog).to receive(:delete_batch_for).and_raise(StandardError.new('bang')) + end + + it 'reports the error' do + expect(service.execute) + .to be_error + .and have_attributes(message: 'bang') + end + end + end + + context 'with system hook' do + let!(:hook) { create(:system_hook, url: "http://example.com") } + + it_behaves_like 'deletes web hook logs for hook' + end + + context 'with project hook' do + let!(:hook) { create(:project_hook) } + + it_behaves_like 'deletes web hook logs for hook' + end + end +end diff --git a/spec/workers/projects/inactive_projects_deletion_cron_worker_spec.rb b/spec/workers/projects/inactive_projects_deletion_cron_worker_spec.rb index 0e7b4ea504c..da9c5833926 100644 --- a/spec/workers/projects/inactive_projects_deletion_cron_worker_spec.rb +++ b/spec/workers/projects/inactive_projects_deletion_cron_worker_spec.rb @@ -44,7 +44,7 @@ RSpec.describe Projects::InactiveProjectsDeletionCronWorker do end it 'does not invoke Projects::InactiveProjectsDeletionNotificationWorker' do - expect(::Projects::InactiveProjectsDeletionNotificationWorker).not_to receive(:perform_in) + expect(::Projects::InactiveProjectsDeletionNotificationWorker).not_to receive(:perform_async) expect(::Projects::DestroyService).not_to receive(:new) worker.perform @@ -68,7 +68,7 @@ RSpec.describe Projects::InactiveProjectsDeletionCronWorker do end it 'does not invoke Projects::InactiveProjectsDeletionNotificationWorker' do - expect(::Projects::InactiveProjectsDeletionNotificationWorker).not_to receive(:perform_in) + expect(::Projects::InactiveProjectsDeletionNotificationWorker).not_to receive(:perform_async) expect(::Projects::DestroyService).not_to receive(:new) worker.perform @@ -82,8 +82,6 @@ RSpec.describe Projects::InactiveProjectsDeletionCronWorker do end context 'when feature flag is enabled', :clean_gitlab_redis_shared_state, :sidekiq_inline do - let_it_be(:delay) { anything } - before do stub_feature_flags(inactive_projects_deletion: true) end @@ -93,8 +91,8 @@ RSpec.describe Projects::InactiveProjectsDeletionCronWorker do expect(redis).to receive(:hset).with('inactive_projects_deletion_warning_email_notified', "project:#{inactive_large_project.id}", Date.current) end - expect(::Projects::InactiveProjectsDeletionNotificationWorker).to receive(:perform_in).with( - delay, inactive_large_project.id, deletion_date).and_call_original + expect(::Projects::InactiveProjectsDeletionNotificationWorker).to receive(:perform_async).with( + inactive_large_project.id, deletion_date).and_call_original expect(::Projects::DestroyService).not_to receive(:new) worker.perform @@ -106,7 +104,7 @@ RSpec.describe Projects::InactiveProjectsDeletionCronWorker do Date.current.to_s) end - expect(::Projects::InactiveProjectsDeletionNotificationWorker).not_to receive(:perform_in) + expect(::Projects::InactiveProjectsDeletionNotificationWorker).not_to receive(:perform_async) expect(::Projects::DestroyService).not_to receive(:new) worker.perform @@ -118,7 +116,7 @@ RSpec.describe Projects::InactiveProjectsDeletionCronWorker do 15.months.ago.to_date.to_s) end - expect(::Projects::InactiveProjectsDeletionNotificationWorker).not_to receive(:perform_in) + expect(::Projects::InactiveProjectsDeletionNotificationWorker).not_to receive(:perform_async) expect(::Projects::DestroyService).to receive(:new).with(inactive_large_project, admin_user, {}) .at_least(:once).and_call_original @@ -131,6 +129,34 @@ RSpec.describe Projects::InactiveProjectsDeletionCronWorker do "project:#{inactive_large_project.id}")).to be_nil end end + + context 'when the worker is running for more than 4 minutes' do + before do + subject.instance_variable_set(:@start_time, ::Gitlab::Metrics::System.monotonic_time - 5.minutes) + end + + it 'stores the last processed inactive project_id in redis cache' do + Gitlab::Redis::Cache.with do |redis| + expect { worker.perform } + .to change { redis.get('last_processed_inactive_project_id') }.to(inactive_large_project.id.to_s) + end + end + end + + context 'when the worker finishes processing in less than 4 minutes' do + before do + Gitlab::Redis::Cache.with do |redis| + redis.set('last_processed_inactive_project_id', inactive_large_project.id) + end + end + + it 'clears the last processed inactive project_id from redis cache' do + Gitlab::Redis::Cache.with do |redis| + expect { worker.perform } + .to change { redis.get('last_processed_inactive_project_id') }.to(nil) + end + end + end end it_behaves_like 'an idempotent worker' diff --git a/spec/workers/web_hooks/destroy_worker_spec.rb b/spec/workers/web_hooks/destroy_worker_spec.rb index fd26c8591ee..8e75610a031 100644 --- a/spec/workers/web_hooks/destroy_worker_spec.rb +++ b/spec/workers/web_hooks/destroy_worker_spec.rb @@ -3,6 +3,8 @@ require 'spec_helper' RSpec.describe WebHooks::DestroyWorker do + include AfterNextHelpers + let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } @@ -20,23 +22,26 @@ RSpec.describe WebHooks::DestroyWorker do let!(:other_log) { create(:web_hook_log, web_hook: other_hook) } it "deletes the Web hook and logs", :aggregate_failures do + expect(WebHooks::LogDestroyWorker).to receive(:perform_async) + expect { subject.perform(user.id, hook.id) } - .to change { WebHookLog.count }.from(2).to(1) - .and change { WebHook.count }.from(2).to(1) + .to change { WebHook.count }.from(2).to(1) expect(WebHook.find(other_hook.id)).to be_present expect(WebHookLog.find(other_log.id)).to be_present end it "raises and tracks an error if destroy failed" do - allow_next_instance_of(::WebHooks::DestroyService) do |instance| - expect(instance).to receive(:sync_destroy).with(anything).and_return({ status: :error, message: "failed" }) - end + expect_next(::WebHooks::DestroyService) + .to receive(:sync_destroy).with(anything) + .and_return(ServiceResponse.error(message: "failed")) + + expect(Gitlab::ErrorTracking) + .to receive(:track_and_raise_exception) + .with(an_instance_of(described_class::DestroyError), { web_hook_id: hook.id }) + .and_call_original - expect(Gitlab::ErrorTracking).to receive(:track_exception) - .with(an_instance_of(::WebHooks::DestroyService::DestroyError), web_hook_id: hook.id) - .and_call_original - expect { subject.perform(user.id, hook.id) }.to raise_error(::WebHooks::DestroyService::DestroyError) + expect { subject.perform(user.id, hook.id) }.to raise_error(described_class::DestroyError) end context 'with unknown hook' do diff --git a/spec/workers/web_hooks/log_destroy_worker_spec.rb b/spec/workers/web_hooks/log_destroy_worker_spec.rb new file mode 100644 index 00000000000..0c107c05360 --- /dev/null +++ b/spec/workers/web_hooks/log_destroy_worker_spec.rb @@ -0,0 +1,86 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe WebHooks::LogDestroyWorker do + include AfterNextHelpers + + let_it_be(:project) { create(:project) } + + subject { described_class.new } + + describe "#perform" do + let!(:hook) { create(:project_hook, project: project) } + let!(:other_hook) { create(:project_hook, project: project) } + let!(:log) { create(:web_hook_log, web_hook: hook) } + let!(:other_log) { create(:web_hook_log, web_hook: other_hook) } + + context 'with a Web hook' do + it "deletes the relevant logs", :aggregate_failures do + hook.destroy! # It does not depend on the presence of the hook + + expect { subject.perform({ 'hook_id' => hook.id }) } + .to change { WebHookLog.count }.by(-1) + + expect(WebHook.find(other_hook.id)).to be_present + expect(WebHookLog.find(other_log.id)).to be_present + end + + it 'is idempotent' do + subject.perform({ 'hook_id' => hook.id }) + subject.perform({ 'hook_id' => hook.id }) + + expect(hook.web_hook_logs).to be_none + end + + it "raises and tracks an error if destroy failed" do + expect_next(::WebHooks::LogDestroyService) + .to receive(:execute).and_return(ServiceResponse.error(message: "failed")) + + expect(Gitlab::ErrorTracking) + .to receive(:track_and_raise_exception) + .with(an_instance_of(described_class::DestroyError), { web_hook_id: hook.id }) + .and_call_original + + expect { subject.perform({ 'hook_id' => hook.id }) } + .to raise_error(described_class::DestroyError) + end + + context 'with extra arguments' do + it 'does not raise an error' do + expect { subject.perform({ 'hook_id' => hook.id, 'extra' => true }) }.not_to raise_error + + expect(WebHook.count).to eq(2) + expect(WebHookLog.count).to eq(1) + end + end + end + + context 'with no arguments' do + it 'does not raise an error' do + expect { subject.perform }.not_to raise_error + + expect(WebHook.count).to eq(2) + expect(WebHookLog.count).to eq(2) + end + end + + context 'with empty arguments' do + it 'does not raise an error' do + expect { subject.perform({}) }.not_to raise_error + + expect(WebHook.count).to eq(2) + expect(WebHookLog.count).to eq(2) + end + end + + context 'with unknown hook' do + it 'does not raise an error' do + expect { subject.perform({ 'hook_id' => non_existing_record_id }) }.not_to raise_error + + expect(WebHook.count).to eq(2) + expect(WebHookLog.count).to eq(2) + end + end + end +end |