1# frozen_string_literal: true
2
3require 'spec_helper'
4
5RSpec.describe Gitlab::Search::AbuseValidators::NoAbusiveTermLengthValidator do
6  subject do
7    described_class.new({ attributes: { foo: :bar }, maximum: limit, maximum_for_url: url_limit })
8  end
9
10  let(:limit) { 100 }
11  let(:url_limit) { limit * 2 }
12  let(:instance) { double(:instance) }
13  let(:attribute) { :search }
14  let(:validation_msg) { 'abusive term length detected' }
15  let(:validate) { subject.validate_each(instance, attribute, search) }
16
17  context 'when a term is over the limit' do
18    let(:search) { "this search is too lo#{'n' * limit}g" }
19
20    it 'adds a validation error' do
21      expect(instance).to receive_message_chain(:errors, :add).with(attribute, validation_msg)
22      validate
23    end
24  end
25
26  context 'when all terms are under the limit' do
27    let(:search) { "what is love? baby don't hurt me" }
28
29    it 'does NOT add any validation errors' do
30      expect(instance).not_to receive(:errors)
31      validate
32    end
33  end
34
35  context 'when a URL is detected in a search term' do
36    let(:double_limit) { limit * 2 }
37    let(:terms) do
38      [
39        'http://' + 'x' * (double_limit - 12) + '.com',
40        'https://' + 'x' * (double_limit - 13) + '.com',
41        'sftp://' + 'x' * (double_limit - 12) + '.com',
42        'ftp://' + 'x' * (double_limit - 11) + '.com',
43        'http://' + 'x' * (double_limit - 8) # no tld is OK
44      ]
45    end
46
47    context 'when under twice the limit' do
48      let(:search) { terms.join(' ') }
49
50      it 'does NOT add any validation errors' do
51        search.split.each do |term|
52          expect(term.length).to be < url_limit
53        end
54
55        expect(instance).not_to receive(:errors)
56        validate
57      end
58    end
59
60    context 'when over twice the limit' do
61      let(:search) do
62        terms.map { |t| t + 'xxxxxxxx' }.join(' ')
63      end
64
65      it 'adds a validation error' do
66        expect(instance).to receive_message_chain(:errors, :add).with(attribute, validation_msg)
67        validate
68      end
69    end
70  end
71end
72