summaryrefslogtreecommitdiffstats
path: root/javatests/com/google/gerrit/acceptance/server/git/receive/ReceiveCommitsCommentValidationIT.java
blob: 13e2f2448dbd99c011e59c8a978a6e22b3dbc73e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Copyright (C) 2019 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.acceptance.server.git.receive;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.PushOneCommit.Result;
import com.google.gerrit.acceptance.config.GerritConfig;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.entities.AttentionSetUpdate;
import com.google.gerrit.extensions.annotations.Exports;
import com.google.gerrit.extensions.api.changes.AttentionSetInput;
import com.google.gerrit.extensions.api.changes.DraftInput;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.client.Side;
import com.google.gerrit.extensions.config.FactoryModule;
import com.google.gerrit.extensions.validators.CommentForValidation;
import com.google.gerrit.extensions.validators.CommentValidationContext;
import com.google.gerrit.extensions.validators.CommentValidator;
import com.google.gerrit.testing.FakeEmailSender;
import com.google.gerrit.testing.TestCommentHelper;
import com.google.inject.Inject;
import com.google.inject.Module;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;

/**
 * Tests for comment validation when publishing drafts via the {@code --publish-comments} option.
 */
public class ReceiveCommitsCommentValidationIT extends AbstractDaemonTest {
  @Inject private CommentValidator mockCommentValidator;
  @Inject private TestCommentHelper testCommentHelper;
  @Inject private RequestScopeOperations requestScopeOperations;

  private static final int COMMENT_SIZE_LIMIT = 666;

  private static final String COMMENT_TEXT = "The comment text";
  private static final CommentForValidation COMMENT_FOR_VALIDATION =
      CommentForValidation.create(
          CommentForValidation.CommentSource.HUMAN,
          CommentForValidation.CommentType.FILE_COMMENT,
          COMMENT_TEXT,
          COMMENT_TEXT.length());

  @Captor private ArgumentCaptor<ImmutableList<CommentForValidation>> capture;
  @Captor private ArgumentCaptor<CommentValidationContext> captureCtx;

  @Override
  public Module createModule() {
    return new FactoryModule() {
      @Override
      public void configure() {
        CommentValidator mockCommentValidator = mock(CommentValidator.class);
        bind(CommentValidator.class)
            .annotatedWith(Exports.named(mockCommentValidator.getClass()))
            .toInstance(mockCommentValidator);
        bind(CommentValidator.class).toInstance(mockCommentValidator);
      }
    };
  }

  @Before
  public void resetMock() {
    initMocks(this);
    clearInvocations(mockCommentValidator);
  }

  @Test
  public void validateComments_commentOK() throws Exception {
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    String revId = result.getCommit().getName();
    when(mockCommentValidator.validateComments(captureCtx.capture(), capture.capture()))
        .thenReturn(ImmutableList.of());
    DraftInput comment = testCommentHelper.newDraft(COMMENT_TEXT);
    testCommentHelper.addDraft(changeId, revId, comment);
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).isEmpty();
    Result amendResult = amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    amendResult.assertOkStatus();
    amendResult.assertNotMessage("Comment validation failure:");
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).hasSize(1);

    assertThat(captureCtx.getAllValues()).hasSize(1);
    assertThat(captureCtx.getValue().getProject()).isEqualTo(result.getChange().project().get());
    assertThat(captureCtx.getValue().getChangeId()).isEqualTo(result.getChange().getId().get());
    assertThat(captureCtx.getValue().getRefName()).isEqualTo("refs/heads/master");
    assertThat(capture.getValue()).containsExactly(COMMENT_FOR_VALIDATION);
  }

  @Test
  public void emailsSentOnPublishCommentsHaveDifferentMessageIds() throws Exception {
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    gApi.changes().id(changeId).addReviewer(user.email());
    sender.clear();

    String revId = result.getCommit().getName();
    DraftInput comment = testCommentHelper.newDraft(COMMENT_TEXT);
    testCommentHelper.addDraft(changeId, revId, comment);
    amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);

    List<FakeEmailSender.Message> messages = sender.getMessages();
    assertThat(messages).hasSize(2);

    FakeEmailSender.Message newPatchsetMessage = messages.get(0);
    assertThat(newPatchsetMessage.body()).contains("new patch set");
    assertThat(newPatchsetMessage.headers().get("Message-ID").toString())
        .doesNotContain("EmailReviewComments");

    FakeEmailSender.Message newCommentsMessage = messages.get(1);
    assertThat(newCommentsMessage.body()).contains("has posted comments on this change");
    assertThat(newCommentsMessage.headers().get("Message-ID").toString())
        .contains("EmailReviewComments");
  }

  @Test
  public void publishCommentsAddsAllUsersInCommentThread() throws Exception {
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    String revId = result.getCommit().getName();

    requestScopeOperations.setApiUser(user.id());
    DraftInput comment = testCommentHelper.newDraft(COMMENT_TEXT);
    testCommentHelper.addDraft(changeId, revId, comment);
    ReviewInput reviewInput = new ReviewInput().blockAutomaticAttentionSetRules();
    reviewInput.drafts = ReviewInput.DraftHandling.PUBLISH;
    change(result).current().review(reviewInput);

    requestScopeOperations.setApiUser(admin.id());
    comment =
        testCommentHelper.newDraft(
            COMMENT_TEXT,
            Iterables.getOnlyElement(gApi.changes().id(changeId).current().commentsAsList()).id);

    testCommentHelper.addDraft(changeId, revId, comment);
    Result amendResult = amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    AttentionSetUpdate attentionSetUpdate =
        Iterables.getOnlyElement(amendResult.getChange().attentionSet());
    assertThat(attentionSetUpdate.account()).isEqualTo(user.id());
    assertThat(attentionSetUpdate.reason())
        .isEqualTo("Someone else replied on a comment you posted");
    assertThat(attentionSetUpdate.operation()).isEqualTo(AttentionSetUpdate.Operation.ADD);
  }

  @Test
  public void attentionSetNotUpdatedWhenNoCommentsPublished() throws Exception {
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    gApi.changes().id(changeId).addReviewer(user.email());
    gApi.changes().id(changeId).attention(user.email()).remove(new AttentionSetInput("removed"));
    ImmutableSet<AttentionSetUpdate> attentionSet = result.getChange().attentionSet();
    Result amendResult = amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    assertThat(attentionSet).isEqualTo(amendResult.getChange().attentionSet());
  }

  @Test
  public void validateComments_commentRejected() throws Exception {
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    String revId = result.getCommit().getName();
    when(mockCommentValidator.validateComments(
            CommentValidationContext.create(
                result.getChange().getId().get(),
                result.getChange().project().get(),
                result.getChange().change().getDest().branch()),
            ImmutableList.of(COMMENT_FOR_VALIDATION)))
        .thenReturn(ImmutableList.of(COMMENT_FOR_VALIDATION.failValidation("Oh no!")));
    DraftInput comment = testCommentHelper.newDraft(COMMENT_TEXT);
    testCommentHelper.addDraft(changeId, revId, comment);
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).isEmpty();
    Result amendResult = amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    amendResult.assertOkStatus();
    amendResult.assertMessage("Comment validation failure:");
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).isEmpty();
  }

  @Test
  public void validateComments_inlineVsFileComments_allOK() throws Exception {
    when(mockCommentValidator.validateComments(captureCtx.capture(), capture.capture()))
        .thenReturn(ImmutableList.of());
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    String revId = result.getCommit().getName();
    DraftInput draftFile = testCommentHelper.newDraft(COMMENT_TEXT);
    testCommentHelper.addDraft(changeId, revId, draftFile);
    DraftInput draftInline =
        testCommentHelper.newDraft(
            result.getChange().currentFilePaths().get(0), Side.REVISION, 1, COMMENT_TEXT);
    testCommentHelper.addDraft(changeId, revId, draftInline);
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).isEmpty();
    amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).hasSize(2);

    assertThat(capture.getAllValues()).hasSize(1);

    assertThat(captureCtx.getValue().getProject()).isEqualTo(result.getChange().project().get());
    assertThat(captureCtx.getValue().getChangeId()).isEqualTo(result.getChange().getId().get());
    assertThat(captureCtx.getValue().getRefName()).isEqualTo("refs/heads/master");

    assertThat(capture.getAllValues().get(0))
        .containsExactly(
            CommentForValidation.create(
                CommentForValidation.CommentSource.HUMAN,
                CommentForValidation.CommentType.INLINE_COMMENT,
                draftInline.message,
                draftInline.message.length()),
            CommentForValidation.create(
                CommentForValidation.CommentSource.HUMAN,
                CommentForValidation.CommentType.FILE_COMMENT,
                draftFile.message,
                draftFile.message.length()));
  }

  @Test
  @GerritConfig(name = "change.commentSizeLimit", value = "" + COMMENT_SIZE_LIMIT)
  public void validateComments_enforceLimits_commentTooLarge() throws Exception {
    when(mockCommentValidator.validateComments(any(), any())).thenReturn(ImmutableList.of());
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    int commentLength = COMMENT_SIZE_LIMIT + 1;
    DraftInput comment =
        testCommentHelper.newDraft(new String(new char[commentLength]).replace("\0", "x"));
    testCommentHelper.addDraft(changeId, result.getCommit().getName(), comment);

    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).isEmpty();
    Result amendResult = amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    amendResult.assertOkStatus();
    amendResult.assertMessage(
        String.format("Comment size exceeds limit (%d > %d)", commentLength, COMMENT_SIZE_LIMIT));
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).isEmpty();
  }

  @Test
  @GerritConfig(name = "change.maxComments", value = "8")
  public void countComments_limitNumberOfComments() throws Exception {
    when(mockCommentValidator.validateComments(any(), any())).thenReturn(ImmutableList.of());
    // Start out with 1 change message.
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    String revId = result.getCommit().getName();
    String filePath = result.getChange().currentFilePaths().get(0);
    DraftInput draftInline = testCommentHelper.newDraft(filePath, Side.REVISION, 1, COMMENT_TEXT);
    testCommentHelper.addDraft(changeId, revId, draftInline);
    // Publishes the 1 draft and adds 2 change messages.
    amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).hasSize(1);

    for (int i = 0; i < 2; ++i) {
      // Adds 1 robot comment and 1 change message.
      testCommentHelper.addRobotComment(
          changeId,
          TestCommentHelper.createRobotCommentInput(result.getChange().currentFilePaths().get(0)));
    }
    // We now have 1 comment, 2 robot comments, 5 change messages.

    draftInline = testCommentHelper.newDraft(filePath, Side.REVISION, 1, COMMENT_TEXT);
    testCommentHelper.addDraft(changeId, revId, draftInline);
    // Publishes the 1 draft and adds 2 change messages. The latter 2 are autogenerated and are not
    // subject to validation.
    Result amendResult = amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).hasSize(1);
    amendResult.assertMessage("exceeding maximum number of comments");
  }

  @Test
  @GerritConfig(name = "change.cumulativeCommentSizeLimit", value = "500")
  public void limitCumulativeCommentSize() throws Exception {
    when(mockCommentValidator.validateComments(any(), any())).thenReturn(ImmutableList.of());
    PushOneCommit.Result result = createChange();
    String changeId = result.getChangeId();
    String revId = result.getCommit().getName();
    String filePath = result.getChange().currentFilePaths().get(0);
    String commentText400Bytes = new String(new char[400]).replace("\0", "x");
    DraftInput draftInline =
        testCommentHelper.newDraft(filePath, Side.REVISION, 1, commentText400Bytes);
    testCommentHelper.addDraft(changeId, revId, draftInline);
    amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).hasSize(1);

    draftInline = testCommentHelper.newDraft(filePath, Side.REVISION, 1, commentText400Bytes);
    testCommentHelper.addDraft(changeId, revId, draftInline);
    Result amendResult = amendChange(changeId, "refs/for/master%publish-comments", admin, testRepo);
    assertThat(testCommentHelper.getPublishedComments(result.getChangeId())).hasSize(1);
    amendResult.assertMessage("exceeding maximum cumulative size of comments");
  }
}