# frozen_string_literal: true require File.expand_path('../../spec_helper', __FILE__) module Danger describe Danger::DangerWCC do before do @dangerfile = testing_dangerfile @my_plugin = @dangerfile.wcc @git = @dangerfile.git @github = @dangerfile.github allow(@github).to receive(:pr_json) .and_return(JSON.parse(load_fixture('github_pr.json'))) end describe 'utils#find_in_diff' do it 'returns empty list when no files in diff' do allow(@git).to receive(:diff) .and_return([]) # act lines = @my_plugin.find_in_diff(/.*/i) # assert expect(lines).to eq([]) end it 'returns list with matching added lines' do allow(@git).to receive(:diff) .and_return([load_diff('spec/fixtures/todo.rb', 'no_todo')]) # act lines = @my_plugin.find_in_diff(/(module|def|end)/i) # assert expect(lines.map(&:content)).to eq( [ '+module Todo', '+ def this_should_not_trigger_todo', '+ end', '+end' ] ) end it 'executes block for each matching line' do allow(@git).to receive(:diff) .and_return( [ load_diff('spec/fixtures/todo.rb', 'no_todo'), load_diff('spec/fixtures/find_in_diff.rb', 'find_in_diff_2_chunks') ] ) lines = [] # act @my_plugin.find_in_diff(/\#\s*(.+)$/i) do |match, line, hunk, file| lines.push({ group: match.captures[0], line: line, hunk: hunk, file: file }) end # assert expect(lines.map { |l| l[:line].content }).to eq( [ '+# frozen_string_literal: true', '+ # This should appear in hunk 1', '+ # This should appear in hunk 2' ] ) expect(lines.map { |l| l[:group] }).to eq( [ 'frozen_string_literal: true', 'This should appear in hunk 1', 'This should appear in hunk 2' ] ) expect(lines.map { |l| l[:hunk].range_info.new_range.start }).to eq( [ 1, 1, 14 ] ) end end describe 'utils#run_and_diff' do it 'runs command and builds diff' do # setup File.write('README.md', 'something else') begin # act diff = @my_plugin.run_and_diff('cat README.md') diff = GitDiff.from_string(diff) # assert expect(diff.files[0].hunks[0].lines.size).to be > 1 additions = diff.files[0].hunks[0].lines.select(&:addition?) expect(additions.length).to eq(1) expect(additions[0].content).to eq('+something else') ensure `git checkout HEAD -- README.md` end end it 'runs command from block' do # setup dir = Dir.pwd # act diff = @my_plugin.run_and_diff { Dir.pwd } diff = GitDiff.from_string(diff) # assert expect(diff.files[0].hunks[0].lines.size).to be > 1 additions = diff.files[0].hunks[0].lines.select(&:addition?) expect(additions.length).to eq(1) expect(additions[0].content).to eq("+#{dir}") deletions = diff.files[0].hunks[0].lines.select(&:deletion?) expect(deletions.length).to eq(1) expect(deletions[0].content).to_not include(dir) end end end end