Commit 7f78a78a authored by Rémy Coutable's avatar Rémy Coutable

Merge branch '5971-webhook-testing' into 'master'

Wrong data type when testing webhooks

Closes #5971

See merge request !11728
parents 020b6a0b e0ab5618
...@@ -10,9 +10,9 @@ class Admin::HookLogsController < Admin::ApplicationController ...@@ -10,9 +10,9 @@ class Admin::HookLogsController < Admin::ApplicationController
end end
def retry def retry
status, message = hook.execute(hook_log.request_data, hook_log.trigger) result = hook.execute(hook_log.request_data, hook_log.trigger)
set_hook_execution_notice(status, message) set_hook_execution_notice(result)
redirect_to edit_admin_hook_path(@hook) redirect_to edit_admin_hook_path(@hook)
end end
......
...@@ -38,9 +38,9 @@ class Admin::HooksController < Admin::ApplicationController ...@@ -38,9 +38,9 @@ class Admin::HooksController < Admin::ApplicationController
end end
def test def test
status, message = hook.execute(sample_hook_data, 'system_hooks') result = TestHooks::SystemService.new(hook, current_user, params[:trigger]).execute
set_hook_execution_notice(status, message) set_hook_execution_notice(result)
redirect_back_or_default redirect_back_or_default
end end
...@@ -66,15 +66,4 @@ class Admin::HooksController < Admin::ApplicationController ...@@ -66,15 +66,4 @@ class Admin::HooksController < Admin::ApplicationController
:url :url
) )
end end
def sample_hook_data
{
event_name: "project_create",
name: "Ruby",
path: "ruby",
project_id: 1,
owner_name: "Someone",
owner_email: "example@gitlabhq.com"
}
end
end end
...@@ -3,11 +3,14 @@ module HooksExecution ...@@ -3,11 +3,14 @@ module HooksExecution
private private
def set_hook_execution_notice(status, message) def set_hook_execution_notice(result)
if status && status >= 200 && status < 400 http_status = result[:http_status]
flash[:notice] = "Hook executed successfully: HTTP #{status}" message = result[:message]
elsif status
flash[:alert] = "Hook executed successfully but returned HTTP #{status} #{message}" if http_status && http_status >= 200 && http_status < 400
flash[:notice] = "Hook executed successfully: HTTP #{http_status}"
elsif http_status
flash[:alert] = "Hook executed successfully but returned HTTP #{http_status} #{message}"
else else
flash[:alert] = "Hook execution failed: #{message}" flash[:alert] = "Hook execution failed: #{message}"
end end
......
...@@ -14,9 +14,9 @@ class Projects::HookLogsController < Projects::ApplicationController ...@@ -14,9 +14,9 @@ class Projects::HookLogsController < Projects::ApplicationController
end end
def retry def retry
status, message = hook.execute(hook_log.request_data, hook_log.trigger) result = hook.execute(hook_log.request_data, hook_log.trigger)
set_hook_execution_notice(status, message) set_hook_execution_notice(result)
redirect_to edit_project_hook_path(@project, @hook) redirect_to edit_project_hook_path(@project, @hook)
end end
......
...@@ -9,6 +9,10 @@ class Projects::HooksController < Projects::ApplicationController ...@@ -9,6 +9,10 @@ class Projects::HooksController < Projects::ApplicationController
layout "project_settings" layout "project_settings"
def index
redirect_to project_settings_integrations_path(@project)
end
def create def create
@hook = @project.hooks.new(hook_params) @hook = @project.hooks.new(hook_params)
@hook.save @hook.save
...@@ -33,13 +37,9 @@ class Projects::HooksController < Projects::ApplicationController ...@@ -33,13 +37,9 @@ class Projects::HooksController < Projects::ApplicationController
end end
def test def test
if !@project.empty_repo? result = TestHooks::ProjectService.new(hook, current_user, params[:trigger]).execute
status, message = TestHookService.new.execute(hook, current_user)
set_hook_execution_notice(status, message) set_hook_execution_notice(result)
else
flash[:alert] = 'Hook execution failed. Ensure the project has commits.'
end
redirect_back_or_default(default: { action: 'index' }) redirect_back_or_default(default: { action: 'index' })
end end
......
module HooksHelper
def link_to_test_hook(hook, trigger)
path = case hook
when ProjectHook
project = hook.project
test_project_hook_path(project, hook, trigger: trigger)
when SystemHook
test_admin_hook_path(hook, trigger: trigger)
end
trigger_human_name = trigger.to_s.tr('_', ' ').camelize
link_to path, rel: 'nofollow' do
content_tag(:span, trigger_human_name)
end
end
end
class ProjectHook < WebHook class ProjectHook < WebHook
belongs_to :project TRIGGERS = {
push_hooks: :push_events,
tag_push_hooks: :tag_push_events,
issue_hooks: :issues_events,
confidential_issue_hooks: :confidential_issues_events,
note_hooks: :note_events,
merge_request_hooks: :merge_requests_events,
job_hooks: :job_events,
pipeline_hooks: :pipeline_events,
wiki_page_hooks: :wiki_page_events
}.freeze
TRIGGERS.each do |trigger, event|
scope trigger, -> { where(event => true) }
end
scope :issue_hooks, -> { where(issues_events: true) } belongs_to :project
scope :confidential_issue_hooks, -> { where(confidential_issues_events: true) } validates :project, presence: true
scope :note_hooks, -> { where(note_events: true) }
scope :merge_request_hooks, -> { where(merge_requests_events: true) }
scope :job_hooks, -> { where(job_events: true) }
scope :pipeline_hooks, -> { where(pipeline_events: true) }
scope :wiki_page_hooks, -> { where(wiki_page_events: true) }
end end
class ServiceHook < WebHook class ServiceHook < WebHook
belongs_to :service belongs_to :service
validates :service, presence: true
def execute(data) def execute(data)
WebHookService.new(self, data, 'service_hook').execute WebHookService.new(self, data, 'service_hook').execute
......
class SystemHook < WebHook class SystemHook < WebHook
scope :repository_update_hooks, -> { where(repository_update_events: true) } TRIGGERS = {
repository_update_hooks: :repository_update_events,
push_hooks: :push_events,
tag_push_hooks: :tag_push_events
}.freeze
TRIGGERS.each do |trigger, event|
scope trigger, -> { where(event => true) }
end
default_value_for :push_events, false default_value_for :push_events, false
default_value_for :repository_update_events, true default_value_for :repository_update_events, true
......
class WebHook < ActiveRecord::Base class WebHook < ActiveRecord::Base
include Sortable include Sortable
default_value_for :push_events, true
default_value_for :issues_events, false
default_value_for :confidential_issues_events, false
default_value_for :note_events, false
default_value_for :merge_requests_events, false
default_value_for :tag_push_events, false
default_value_for :job_events, false
default_value_for :pipeline_events, false
default_value_for :repository_update_events, false
default_value_for :enable_ssl_verification, true
has_many :web_hook_logs, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent has_many :web_hook_logs, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
scope :push_hooks, -> { where(push_events: true) }
scope :tag_push_hooks, -> { where(tag_push_events: true) }
validates :url, presence: true, url: true validates :url, presence: true, url: true
def execute(data, hook_name) def execute(data, hook_name)
......
...@@ -4,7 +4,7 @@ class SystemHooksService ...@@ -4,7 +4,7 @@ class SystemHooksService
end end
def execute_hooks(data, hooks_scope = :all) def execute_hooks(data, hooks_scope = :all)
SystemHook.send(hooks_scope).each do |hook| SystemHook.public_send(hooks_scope).find_each do |hook|
hook.async_execute(data, 'system_hooks') hook.async_execute(data, 'system_hooks')
end end
end end
......
class TestHookService
def execute(hook, current_user)
data = Gitlab::DataBuilder::Push.build_sample(hook.project, current_user)
hook.execute(data, 'push_hooks')
end
end
module TestHooks
class BaseService
attr_accessor :hook, :current_user, :trigger
def initialize(hook, current_user, trigger)
@hook = hook
@current_user = current_user
@trigger = trigger
end
def execute
trigger_data_method = "#{trigger}_data"
if !self.respond_to?(trigger_data_method, true) ||
!hook.class::TRIGGERS.value?(trigger.to_sym)
return error('Testing not available for this hook')
end
error_message = catch(:validation_error) do
sample_data = self.__send__(trigger_data_method)
return hook.execute(sample_data, trigger)
end
error(error_message)
end
private
def error(message, http_status = nil)
result = {
message: message,
status: :error
}
result[:http_status] = http_status if http_status
result
end
end
end
module TestHooks
class ProjectService < TestHooks::BaseService
private
def project
@project ||= hook.project
end
def push_events_data
throw(:validation_error, 'Ensure the project has at least one commit.') if project.empty_repo?
Gitlab::DataBuilder::Push.build_sample(project, current_user)
end
alias_method :tag_push_events_data, :push_events_data
def note_events_data
note = project.notes.first
throw(:validation_error, 'Ensure the project has notes.') unless note.present?
Gitlab::DataBuilder::Note.build(note, current_user)
end
def issues_events_data
issue = project.issues.first
throw(:validation_error, 'Ensure the project has issues.') unless issue.present?
issue.to_hook_data(current_user)
end
alias_method :confidential_issues_events_data, :issues_events_data
def merge_requests_events_data
merge_request = project.merge_requests.first
throw(:validation_error, 'Ensure the project has merge requests.') unless merge_request.present?
merge_request.to_hook_data(current_user)
end
def job_events_data
build = project.builds.first
throw(:validation_error, 'Ensure the project has CI jobs.') unless build.present?
Gitlab::DataBuilder::Build.build(build)
end
def pipeline_events_data
pipeline = project.pipelines.first
throw(:validation_error, 'Ensure the project has CI pipelines.') unless pipeline.present?
Gitlab::DataBuilder::Pipeline.build(pipeline)
end
def wiki_page_events_data
page = project.wiki.pages.first
if !project.wiki_enabled? || page.blank?
throw(:validation_error, 'Ensure the wiki is enabled and has pages.')
end
Gitlab::DataBuilder::WikiPage.build(page, current_user, 'create')
end
end
end
module TestHooks
class SystemService < TestHooks::BaseService
private
def project
@project ||= begin
project = Project.first
throw(:validation_error, 'Ensure that at least one project exists.') unless project
project
end
end
def push_events_data
if project.empty_repo?
throw(:validation_error, "Ensure project \"#{project.human_name}\" has commits.")
end
Gitlab::DataBuilder::Push.build_sample(project, current_user)
end
def tag_push_events_data
if project.repository.tags.empty?
throw(:validation_error, "Ensure project \"#{project.human_name}\" has tags.")
end
Gitlab::DataBuilder::Push.build_sample(project, current_user)
end
def repository_update_events_data
commit = project.commit
ref = "#{Gitlab::Git::BRANCH_REF_PREFIX}#{project.default_branch}"
unless commit
throw(:validation_error, "Ensure project \"#{project.human_name}\" has commits.")
end
change = Gitlab::DataBuilder::Repository.single_change(
commit.parent_id || Gitlab::Git::BLANK_SHA,
commit.id,
ref
)
Gitlab::DataBuilder::Repository.update(project, current_user, [change], [ref])
end
end
end
...@@ -39,7 +39,11 @@ class WebHookService ...@@ -39,7 +39,11 @@ class WebHookService
execution_duration: Time.now - start_time execution_duration: Time.now - start_time
) )
[response.code, response.to_s] {
status: :success,
http_status: response.code,
message: response.to_s
}
rescue SocketError, OpenSSL::SSL::SSLError, Errno::ECONNRESET, Errno::ECONNREFUSED, Net::OpenTimeout => e rescue SocketError, OpenSSL::SSL::SSLError, Errno::ECONNRESET, Errno::ECONNREFUSED, Net::OpenTimeout => e
log_execution( log_execution(
trigger: hook_name, trigger: hook_name,
...@@ -52,7 +56,10 @@ class WebHookService ...@@ -52,7 +56,10 @@ class WebHookService
Rails.logger.error("WebHook Error => #{e}") Rails.logger.error("WebHook Error => #{e}")
[nil, e.to_s] {
status: :error,
message: e.to_s
}
end end
def async_execute def async_execute
......
module WikiPages module WikiPages
class BaseService < ::BaseService class BaseService < ::BaseService
def hook_data(page, action)
hook_data = {
object_kind: page.class.name.underscore,
user: current_user.hook_attrs,
project: @project.hook_attrs,
wiki: @project.wiki.hook_attrs,
object_attributes: page.hook_attrs
}
page_url = Gitlab::UrlBuilder.build(page)
hook_data[:object_attributes].merge!(url: page_url, action: action)
hook_data
end
private private
def execute_hooks(page, action = 'create') def execute_hooks(page, action = 'create')
page_data = hook_data(page, action) page_data = Gitlab::DataBuilder::WikiPage.build(page, current_user, action)
@project.execute_hooks(page_data, :wiki_page_hooks) @project.execute_hooks(page_data, :wiki_page_hooks)
@project.execute_services(page_data, :wiki_page_hooks) @project.execute_services(page_data, :wiki_page_hooks)
end end
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
= render partial: 'form', locals: { form: f, hook: @hook } = render partial: 'form', locals: { form: f, hook: @hook }
.form-actions .form-actions
= f.submit 'Save changes', class: 'btn btn-create' = f.submit 'Save changes', class: 'btn btn-create'
= link_to 'Test hook', test_admin_hook_path(@hook), class: 'btn btn-default' = render 'shared/web_hooks/test_button', triggers: SystemHook::TRIGGERS, hook: @hook
= link_to 'Remove', admin_hook_path(@hook), method: :delete, class: 'btn btn-remove pull-right', data: { confirm: 'Are you sure?' } = link_to 'Remove', admin_hook_path(@hook), method: :delete, class: 'btn btn-remove pull-right', data: { confirm: 'Are you sure?' }
%hr %hr
......
...@@ -22,12 +22,12 @@ ...@@ -22,12 +22,12 @@
- @hooks.each do |hook| - @hooks.each do |hook|
%li %li
.controls .controls
= link_to 'Test hook', test_admin_hook_path(hook), class: 'btn btn-sm' = render 'shared/web_hooks/test_button', triggers: SystemHook::TRIGGERS, hook: hook, button_class: 'btn-small'
= link_to 'Edit', edit_admin_hook_path(hook), class: 'btn btn-sm' = link_to 'Edit', edit_admin_hook_path(hook), class: 'btn btn-sm'
= link_to 'Remove', admin_hook_path(hook), data: { confirm: 'Are you sure?' }, method: :delete, class: 'btn btn-remove btn-sm' = link_to 'Remove', admin_hook_path(hook), data: { confirm: 'Are you sure?' }, method: :delete, class: 'btn btn-remove btn-sm'
.monospace= hook.url .monospace= hook.url
%div %div
- %w(repository_update_events push_events tag_push_events issues_events note_events merge_requests_events job_events).each do |trigger| - SystemHook::TRIGGERS.each_value do |event|
- if hook.send(trigger) - if hook.public_send(event)
%span.label.label-gray= trigger.titleize %span.label.label-gray= event.to_s.titleize
%span.label.label-gray SSL Verification: #{hook.enable_ssl_verification ? 'enabled' : 'disabled'} %span.label.label-gray SSL Verification: #{hook.enable_ssl_verification ? 'enabled' : 'disabled'}
...@@ -13,9 +13,10 @@ ...@@ -13,9 +13,10 @@
= render partial: 'shared/web_hooks/form', locals: { form: f, hook: @hook } = render partial: 'shared/web_hooks/form', locals: { form: f, hook: @hook }
= f.submit 'Save changes', class: 'btn btn-create' = f.submit 'Save changes', class: 'btn btn-create'
= link_to 'Test hook', test_project_hook_path(@project, @hook), class: 'btn btn-default' = render 'shared/web_hooks/test_button', triggers: ProjectHook::TRIGGERS, hook: @hook
= link_to 'Remove', project_hook_path(@project, @hook), method: :delete, class: 'btn btn-remove pull-right', data: { confirm: 'Are you sure?' } = link_to 'Remove', project_hook_path(@project, @hook), method: :delete, class: 'btn btn-remove pull-right', data: { confirm: 'Are you sure?' }
%hr %hr
= render partial: 'projects/hook_logs/index', locals: { hook: @hook, hook_logs: @hook_logs, project: @project } = render partial: 'projects/hook_logs/index', locals: { hook: @hook, hook_logs: @hook_logs, project: @project }
...@@ -3,14 +3,14 @@ ...@@ -3,14 +3,14 @@
.col-md-8.col-lg-7 .col-md-8.col-lg-7
%strong.light-header= hook.url %strong.light-header= hook.url
%div %div
- %w(push_events tag_push_events issues_events confidential_issues_events note_events merge_requests_events job_events pipeline_events wiki_page_events).each do |trigger| - ProjectHook::TRIGGERS.each_value do |event|
- if hook.send(trigger) - if hook.public_send(event)
%span.label.label-gray.deploy-project-label= trigger.titleize %span.label.label-gray.deploy-project-label= event.to_s.titleize
.col-md-4.col-lg-5.text-right-lg.prepend-top-5 .col-md-4.col-lg-5.text-right-lg.prepend-top-5
%span.append-right-10.inline %span.append-right-10.inline
SSL Verification: #{hook.enable_ssl_verification ? "enabled" : "disabled"} SSL Verification: #{hook.enable_ssl_verification ? 'enabled' : 'disabled'}
= link_to "Edit", edit_project_hook_path(@project, hook), class: "btn btn-sm" = link_to 'Edit', edit_project_hook_path(@project, hook), class: 'btn btn-sm'
= link_to "Test", test_project_hook_path(@project, hook), class: "btn btn-sm" = render 'shared/web_hooks/test_button', triggers: ProjectHook::TRIGGERS, hook: hook, button_class: 'btn-small'
= link_to project_hook_path(@project, hook), data: { confirm: 'Are you sure?'}, method: :delete, class: "btn btn-transparent" do = link_to project_hook_path(@project, hook), data: { confirm: 'Are you sure?'}, method: :delete, class: 'btn btn-transparent' do
%span.sr-only Remove %span.sr-only Remove
= icon('trash') = icon('trash')
- triggers = local_assigns.fetch(:triggers)
- button_class = local_assigns.fetch(:button_class, '')
- hook = local_assigns.fetch(:hook)
.hook-test-button.dropdown.inline
%button.btn{ 'data-toggle' => 'dropdown', class: button_class }
Test
= icon('caret-down')
%ul.dropdown-menu.dropdown-menu-align-right{ role: 'menu' }
- triggers.each_value do |event|
%li
= link_to_test_hook(hook, event)
---
title: Allow testing any events for project hooks and system hooks
merge_request: 11728
author: Alexander Randa (@randaalex)
...@@ -1014,6 +1014,13 @@ X-Gitlab-Event: Build Hook ...@@ -1014,6 +1014,13 @@ X-Gitlab-Event: Build Hook
} }
``` ```
## Testing webhooks
You can trigger the webhook manually. Sample data from the project will be used.Sample data will take from the project.
> For example: for triggering `Push Events` your project should have at least one commit.
![Webhook testing](img/webhook_testing.png)
## Troubleshoot webhooks ## Troubleshoot webhooks
Gitlab stores each perform of the webhook. Gitlab stores each perform of the webhook.
...@@ -1056,7 +1063,7 @@ Pick an unused port (e.g. 8000) and start the script: `ruby print_http_body.rb ...@@ -1056,7 +1063,7 @@ Pick an unused port (e.g. 8000) and start the script: `ruby print_http_body.rb
8000`. Then add your server as a webhook receiver in GitLab as 8000`. Then add your server as a webhook receiver in GitLab as
`http://my.host:8000/`. `http://my.host:8000/`.
When you press 'Test Hook' in GitLab, you should see something like this in the When you press 'Test' in GitLab, you should see something like this in the
console: console:
``` ```
......
...@@ -74,6 +74,8 @@ module Gitlab ...@@ -74,6 +74,8 @@ module Gitlab
build(project, user, commits.last&.id, commits.first&.id, ref, commits) build(project, user, commits.last&.id, commits.first&.id, ref, commits)
end end
private
def checkout_sha(repository, newrev, ref) def checkout_sha(repository, newrev, ref)
# Checkout sha is nil when we remove branch or tag # Checkout sha is nil when we remove branch or tag
return if Gitlab::Git.blank_ref?(newrev) return if Gitlab::Git.blank_ref?(newrev)
......
module Gitlab
module DataBuilder
module WikiPage
extend self
def build(wiki_page, user, action)
wiki = wiki_page.wiki
{
object_kind: wiki_page.class.name.underscore,
user: user.hook_attrs,
project: wiki.project.hook_attrs,
wiki: wiki.hook_attrs,
object_attributes: wiki_page.hook_attrs.merge(
url: Gitlab::UrlBuilder.build(wiki_page),
action: action
)
}
end
end
end
end
require 'spec_helper'
describe Projects::HooksController do
let(:project) { create(:empty_project) }
let(:user) { create(:user) }
before do
project.team << [user, :master]
sign_in(user)
end
describe '#index' do
it 'redirects to settings/integrations page' do
get(:index, namespace_id: project.namespace, project_id: project)
expect(response).to redirect_to(
project_settings_integrations_path(project)
)
end
end
end
...@@ -110,7 +110,7 @@ FactoryGirl.define do ...@@ -110,7 +110,7 @@ FactoryGirl.define do
end end
after(:build) do |build, evaluator| after(:build) do |build, evaluator|
build.project = build.pipeline.project build.project ||= build.pipeline.project
end end
factory :ci_not_started_build do factory :ci_not_started_build do
......
...@@ -2,6 +2,7 @@ FactoryGirl.define do ...@@ -2,6 +2,7 @@ FactoryGirl.define do
factory :project_hook do factory :project_hook do
url { generate(:url) } url { generate(:url) }
enable_ssl_verification false enable_ssl_verification false
project factory: :empty_project
trait :token do trait :token do
token { SecureRandom.hex(10) } token { SecureRandom.hex(10) }
......
...@@ -74,11 +74,13 @@ describe 'Admin::Hooks', feature: true do ...@@ -74,11 +74,13 @@ describe 'Admin::Hooks', feature: true do
end end
end end
describe 'Test' do describe 'Test', js: true do
before do before do
WebMock.stub_request(:post, @system_hook.url) WebMock.stub_request(:post, @system_hook.url)
visit admin_hooks_path visit admin_hooks_path
click_link 'Test hook'
find('.hook-test-button.dropdown').click
click_link 'Push events'
end end
it { expect(current_path).to eq(admin_hooks_path) } it { expect(current_path).to eq(admin_hooks_path) }
......
...@@ -36,14 +36,14 @@ feature 'Integration settings', feature: true do ...@@ -36,14 +36,14 @@ feature 'Integration settings', feature: true do
expect(page.status_code).to eq(200) expect(page.status_code).to eq(200)
expect(page).to have_content(hook.url) expect(page).to have_content(hook.url)
expect(page).to have_content('SSL Verification: enabled') expect(page).to have_content('SSL Verification: enabled')
expect(page).to have_content('Push Events') expect(page).to have_content('Push events')
expect(page).to have_content('Tag Push Events') expect(page).to have_content('Tag push events')
expect(page).to have_content('Issues Events') expect(page).to have_content('Issues events')
expect(page).to have_content('Confidential Issues Events') expect(page).to have_content('Confidential issues events')
expect(page).to have_content('Note Events') expect(page).to have_content('Note events')
expect(page).to have_content('Merge Requests Events') expect(page).to have_content('Merge requests events')
expect(page).to have_content('Pipeline Events') expect(page).to have_content('Pipeline events')
expect(page).to have_content('Wiki Page Events') expect(page).to have_content('Wiki page events')
end end
scenario 'create webhook' do scenario 'create webhook' do
...@@ -58,8 +58,8 @@ feature 'Integration settings', feature: true do ...@@ -58,8 +58,8 @@ feature 'Integration settings', feature: true do
expect(page).to have_content(url) expect(page).to have_content(url)
expect(page).to have_content('SSL Verification: enabled') expect(page).to have_content('SSL Verification: enabled')
expect(page).to have_content('Push Events') expect(page).to have_content('Push events')
expect(page).to have_content('Tag Push Events') expect(page).to have_content('Tag push events')
expect(page).to have_content('Job events') expect(page).to have_content('Job events')
end end
...@@ -76,11 +76,12 @@ feature 'Integration settings', feature: true do ...@@ -76,11 +76,12 @@ feature 'Integration settings', feature: true do
expect(page).to have_content(url) expect(page).to have_content(url)
end end
scenario 'test existing webhook' do scenario 'test existing webhook', js: true do
WebMock.stub_request(:post, hook.url) WebMock.stub_request(:post, hook.url)
visit integrations_path visit integrations_path
click_link 'Test' find('.hook-test-button.dropdown').click
click_link 'Push events'
expect(current_path).to eq(integrations_path) expect(current_path).to eq(integrations_path)
end end
......
require 'spec_helper'
describe HooksHelper do
let(:project) { create(:empty_project) }
let(:project_hook) { create(:project_hook, project: project) }
let(:system_hook) { create(:system_hook) }
let(:trigger) { 'push_events' }
describe '#link_to_test_hook' do
it 'returns project namespaced link' do
expect(helper.link_to_test_hook(project_hook, trigger))
.to include("href=\"#{test_project_hook_path(project, project_hook, trigger: trigger)}\"")
end
it 'returns admin namespaced link' do
expect(helper.link_to_test_hook(system_hook, trigger))
.to include("href=\"#{test_admin_hook_path(system_hook, trigger: trigger)}\"")
end
end
end
require 'spec_helper'
describe Gitlab::DataBuilder::WikiPage do
let(:project) { create(:project, :repository) }
let(:wiki_page) { create(:wiki_page, wiki: project.wiki) }
let(:user) { create(:user) }
describe '.build' do
let(:data) { described_class.build(wiki_page, user, 'create') }
it { expect(data).to be_a(Hash) }
it { expect(data[:object_kind]).to eq('wiki_page') }
it { expect(data[:user]).to eq(user.hook_attrs) }
it { expect(data[:project]).to eq(project.hook_attrs) }
it { expect(data[:wiki]).to eq(project.wiki.hook_attrs) }
it { expect(data[:object_attributes]).to include(wiki_page.hook_attrs) }
it { expect(data[:object_attributes]).to include(url: Gitlab::UrlBuilder.build(wiki_page)) }
it { expect(data[:object_attributes]).to include(action: 'create') }
end
end
require 'spec_helper' require 'spec_helper'
describe ProjectHook, models: true do describe ProjectHook, models: true do
describe "Associations" do describe 'associations' do
it { is_expected.to belong_to :project } it { is_expected.to belong_to :project }
end end
describe 'validations' do
it { is_expected.to validate_presence_of(:project) }
end
describe '.push_hooks' do describe '.push_hooks' do
it 'returns hooks for push events only' do it 'returns hooks for push events only' do
hook = create(:project_hook, push_events: true) hook = create(:project_hook, push_events: true)
......
...@@ -5,6 +5,10 @@ describe ServiceHook, models: true do ...@@ -5,6 +5,10 @@ describe ServiceHook, models: true do
it { is_expected.to belong_to :service } it { is_expected.to belong_to :service }
end end
describe 'validations' do
it { is_expected.to validate_presence_of(:service) }
end
describe 'execute' do describe 'execute' do
let(:hook) { build(:service_hook) } let(:hook) { build(:service_hook) }
let(:data) { { key: 'value' } } let(:data) { { key: 'value' } }
......
...@@ -7,8 +7,7 @@ describe SystemHook, models: true do ...@@ -7,8 +7,7 @@ describe SystemHook, models: true do
it 'sets defined default parameters' do it 'sets defined default parameters' do
attrs = { attrs = {
push_events: false, push_events: false,
repository_update_events: true, repository_update_events: true
enable_ssl_verification: true
} }
expect(system_hook).to have_attributes(attrs) expect(system_hook).to have_attributes(attrs)
end end
......
...@@ -112,7 +112,7 @@ describe MicrosoftTeamsService, models: true do ...@@ -112,7 +112,7 @@ describe MicrosoftTeamsService, models: true do
let(:wiki_page_sample_data) do let(:wiki_page_sample_data) do
service = WikiPages::CreateService.new(project, user, opts) service = WikiPages::CreateService.new(project, user, opts)
wiki_page = service.execute wiki_page = service.execute
service.hook_data(wiki_page, 'create') Gitlab::DataBuilder::WikiPage.build(wiki_page, user, 'create')
end end
it "calls Microsoft Teams API" do it "calls Microsoft Teams API" do
......
...@@ -309,10 +309,14 @@ describe Project, models: true do ...@@ -309,10 +309,14 @@ describe Project, models: true do
end end
describe 'delegation' do describe 'delegation' do
it { is_expected.to delegate_method(:add_guest).to(:team) } [:add_guest, :add_reporter, :add_developer, :add_master, :add_user, :add_users].each do |method|
it { is_expected.to delegate_method(:add_reporter).to(:team) } it { is_expected.to delegate_method(method).to(:team) }
it { is_expected.to delegate_method(:add_developer).to(:team) } end
it { is_expected.to delegate_method(:add_master).to(:team) }
it { is_expected.to delegate_method(:empty_repo?).to(:repository) }
it { is_expected.to delegate_method(:members).to(:team).with_prefix(true) }
it { is_expected.to delegate_method(:count).to(:forks).with_prefix(true) }
it { is_expected.to delegate_method(:name).to(:owner).with_prefix(true).with_arguments(allow_nil: true) }
end end
describe '#to_reference' do describe '#to_reference' do
......
require 'spec_helper'
describe TestHookService, services: true do
let(:user) { create(:user) }
let(:project) { create(:project, :repository) }
let(:hook) { create(:project_hook, project: project) }
describe '#execute' do
it "executes successfully" do
stub_request(:post, hook.url).to_return(status: 200)
expect(TestHookService.new.execute(hook, user)).to be_truthy
end
end
end
require 'spec_helper'
describe TestHooks::ProjectService do
let(:current_user) { create(:user) }
describe '#execute' do
let(:project) { create(:project, :repository) }
let(:hook) { create(:project_hook, project: project) }
let(:service) { described_class.new(hook, current_user, trigger) }
let(:sample_data) { { data: 'sample' } }
let(:success_result) { { status: :success, http_status: 200, message: 'ok' } }
context 'hook with not implemented test' do
let(:trigger) { 'not_implemented_events' }
it 'returns error message' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Testing not available for this hook' })
end
end
context 'push_events' do
let(:trigger) { 'push_events' }
it 'returns error message if not enough data' do
allow(project).to receive(:empty_repo?).and_return(true)
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the project has at least one commit.' })
end
it 'executes hook' do
allow(project).to receive(:empty_repo?).and_return(false)
allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'tag_push_events' do
let(:trigger) { 'tag_push_events' }
it 'returns error message if not enough data' do
allow(project).to receive(:empty_repo?).and_return(true)
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the project has at least one commit.' })
end
it 'executes hook' do
allow(project).to receive(:empty_repo?).and_return(false)
allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'note_events' do
let(:trigger) { 'note_events' }
it 'returns error message if not enough data' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the project has notes.' })
end
it 'executes hook' do
allow(project).to receive(:notes).and_return([Note.new])
allow(Gitlab::DataBuilder::Note).to receive(:build).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'issues_events' do
let(:trigger) { 'issues_events' }
let(:issue) { build(:issue) }
it 'returns error message if not enough data' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the project has issues.' })
end
it 'executes hook' do
allow(project).to receive(:issues).and_return([issue])
allow(issue).to receive(:to_hook_data).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'confidential_issues_events' do
let(:trigger) { 'confidential_issues_events' }
let(:issue) { build(:issue) }
it 'returns error message if not enough data' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the project has issues.' })
end
it 'executes hook' do
allow(project).to receive(:issues).and_return([issue])
allow(issue).to receive(:to_hook_data).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'merge_requests_events' do
let(:trigger) { 'merge_requests_events' }
it 'returns error message if not enough data' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the project has merge requests.' })
end
it 'executes hook' do
create(:merge_request, source_project: project)
allow_any_instance_of(MergeRequest).to receive(:to_hook_data).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'job_events' do
let(:trigger) { 'job_events' }
it 'returns error message if not enough data' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the project has CI jobs.' })
end
it 'executes hook' do
create(:ci_build, project: project)
allow(Gitlab::DataBuilder::Build).to receive(:build).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'pipeline_events' do
let(:trigger) { 'pipeline_events' }
it 'returns error message if not enough data' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the project has CI pipelines.' })
end
it 'executes hook' do
create(:ci_empty_pipeline, project: project)
allow(Gitlab::DataBuilder::Pipeline).to receive(:build).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'wiki_page_events' do
let(:trigger) { 'wiki_page_events' }
it 'returns error message if wiki disabled' do
allow(project).to receive(:wiki_enabled?).and_return(false)
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the wiki is enabled and has pages.' })
end
it 'returns error message if not enough data' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Ensure the wiki is enabled and has pages.' })
end
it 'executes hook' do
create(:wiki_page, wiki: project.wiki)
allow(Gitlab::DataBuilder::WikiPage).to receive(:build).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
end
end
require 'spec_helper'
describe TestHooks::SystemService do
let(:current_user) { create(:user) }
describe '#execute' do
let(:project) { create(:project, :repository) }
let(:hook) { create(:system_hook) }
let(:service) { described_class.new(hook, current_user, trigger) }
let(:sample_data) { { data: 'sample' }}
let(:success_result) { { status: :success, http_status: 200, message: 'ok' } }
before do
allow(Project).to receive(:first).and_return(project)
end
context 'hook with not implemented test' do
let(:trigger) { 'not_implemented_events' }
it 'returns error message' do
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: 'Testing not available for this hook' })
end
end
context 'push_events' do
let(:trigger) { 'push_events' }
it 'returns error message if not enough data' do
allow(project).to receive(:empty_repo?).and_return(true)
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: "Ensure project \"#{project.human_name}\" has commits." })
end
it 'executes hook' do
allow(project).to receive(:empty_repo?).and_return(false)
allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'tag_push_events' do
let(:trigger) { 'tag_push_events' }
it 'returns error message if not enough data' do
allow(project.repository).to receive(:tags).and_return([])
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: "Ensure project \"#{project.human_name}\" has tags." })
end
it 'executes hook' do
allow(project.repository).to receive(:tags).and_return(['tag'])
allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
context 'repository_update_events' do
let(:trigger) { 'repository_update_events' }
it 'returns error message if not enough data' do
allow(project).to receive(:commit).and_return(nil)
expect(hook).not_to receive(:execute)
expect(service.execute).to include({ status: :error, message: "Ensure project \"#{project.human_name}\" has commits." })
end
it 'executes hook' do
allow(project).to receive(:empty_repo?).and_return(false)
allow(Gitlab::DataBuilder::Repository).to receive(:update).and_return(sample_data)
expect(hook).to receive(:execute).with(sample_data, trigger).and_return(success_result)
expect(service.execute).to include(success_result)
end
end
end
end
...@@ -58,7 +58,7 @@ describe WebHookService, services: true do ...@@ -58,7 +58,7 @@ describe WebHookService, services: true do
exception = exception_class.new('Exception message') exception = exception_class.new('Exception message')
WebMock.stub_request(:post, project_hook.url).to_raise(exception) WebMock.stub_request(:post, project_hook.url).to_raise(exception)
expect(service_instance.execute).to eq([nil, exception.message]) expect(service_instance.execute).to eq({ status: :error, message: exception.message })
expect { service_instance.execute }.not_to raise_error expect { service_instance.execute }.not_to raise_error
end end
end end
...@@ -66,13 +66,13 @@ describe WebHookService, services: true do ...@@ -66,13 +66,13 @@ describe WebHookService, services: true do
it 'handles 200 status code' do it 'handles 200 status code' do
WebMock.stub_request(:post, project_hook.url).to_return(status: 200, body: 'Success') WebMock.stub_request(:post, project_hook.url).to_return(status: 200, body: 'Success')
expect(service_instance.execute).to eq([200, 'Success']) expect(service_instance.execute).to include({ status: :success, http_status: 200, message: 'Success' })
end end
it 'handles 2xx status codes' do it 'handles 2xx status codes' do
WebMock.stub_request(:post, project_hook.url).to_return(status: 201, body: 'Success') WebMock.stub_request(:post, project_hook.url).to_return(status: 201, body: 'Success')
expect(service_instance.execute).to eq([201, 'Success']) expect(service_instance.execute).to include({ status: :success, http_status: 201, message: 'Success' })
end end
context 'execution logging' do context 'execution logging' do
......
...@@ -78,7 +78,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do ...@@ -78,7 +78,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do
wiki_page_service = WikiPages::CreateService.new(project, user, opts) wiki_page_service = WikiPages::CreateService.new(project, user, opts)
@wiki_page = wiki_page_service.execute @wiki_page = wiki_page_service.execute
@wiki_page_sample_data = wiki_page_service.hook_data(@wiki_page, 'create') @wiki_page_sample_data = Gitlab::DataBuilder::WikiPage.build(@wiki_page, user, 'create')
end end
it "calls Slack/Mattermost API for push events" do it "calls Slack/Mattermost API for push events" do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment