Search in sources :

Example 1 with ReviewResult

use of com.google.gerrit.extensions.api.changes.ReviewResult in project gerrit by GerritCodeReview.

the class PostReview method apply.

public Response<ReviewResult> apply(BatchUpdate.Factory updateFactory, RevisionResource revision, ReviewInput input, Timestamp ts) throws RestApiException, UpdateException, OrmException, IOException, PermissionBackendException {
    // Respect timestamp, but truncate at change created-on time.
    ts = Ordering.natural().max(ts, revision.getChange().getCreatedOn());
    if (revision.getEdit().isPresent()) {
        throw new ResourceConflictException("cannot post review on edit");
    }
    if (input.onBehalfOf != null) {
        revision = onBehalfOf(revision, input);
    } else if (input.drafts == null) {
        input.drafts = DraftHandling.DELETE;
    }
    if (input.labels != null) {
        checkLabels(revision, input.strictLabels, input.labels);
    }
    if (input.comments != null) {
        cleanUpComments(input.comments);
        checkComments(revision, input.comments);
    }
    if (input.robotComments != null) {
        if (!migration.readChanges()) {
            throw new MethodNotAllowedException("robot comments not supported");
        }
        checkRobotComments(revision, input.robotComments);
    }
    if (input.notify == null) {
        log.warn("notify = null; assuming notify = NONE");
        input.notify = NotifyHandling.NONE;
    }
    ListMultimap<RecipientType, Account.Id> accountsToNotify = notifyUtil.resolveAccounts(input.notifyDetails);
    Map<String, AddReviewerResult> reviewerJsonResults = null;
    List<PostReviewers.Addition> reviewerResults = Lists.newArrayList();
    boolean hasError = false;
    boolean confirm = false;
    if (input.reviewers != null) {
        reviewerJsonResults = Maps.newHashMap();
        for (AddReviewerInput reviewerInput : input.reviewers) {
            // Prevent notifications because setting reviewers is batched.
            reviewerInput.notify = NotifyHandling.NONE;
            PostReviewers.Addition result = postReviewers.prepareApplication(revision.getChangeResource(), reviewerInput, true);
            reviewerJsonResults.put(reviewerInput.reviewer, result.result);
            if (result.result.error != null) {
                hasError = true;
                continue;
            }
            if (result.result.confirm != null) {
                confirm = true;
                continue;
            }
            reviewerResults.add(result);
        }
    }
    ReviewResult output = new ReviewResult();
    output.reviewers = reviewerJsonResults;
    if (hasError || confirm) {
        return Response.withStatusCode(SC_BAD_REQUEST, output);
    }
    output.labels = input.labels;
    try (BatchUpdate bu = updateFactory.create(db.get(), revision.getChange().getProject(), revision.getUser(), ts)) {
        Account.Id id = revision.getUser().getAccountId();
        boolean ccOrReviewer = false;
        if (input.labels != null && !input.labels.isEmpty()) {
            ccOrReviewer = input.labels.values().stream().filter(v -> v != 0).findFirst().isPresent();
        }
        if (!ccOrReviewer) {
            // Check if user was already CCed or reviewing prior to this review.
            ReviewerSet currentReviewers = approvalsUtil.getReviewers(db.get(), revision.getChangeResource().getNotes());
            ccOrReviewer = currentReviewers.all().contains(id);
        }
        // themselves as a reviewer or to the CC list.
        for (PostReviewers.Addition reviewerResult : reviewerResults) {
            bu.addOp(revision.getChange().getId(), reviewerResult.op);
            if (!ccOrReviewer && reviewerResult.result.reviewers != null) {
                for (ReviewerInfo reviewerInfo : reviewerResult.result.reviewers) {
                    if (Objects.equals(id.get(), reviewerInfo._accountId)) {
                        ccOrReviewer = true;
                        break;
                    }
                }
            }
            if (!ccOrReviewer && reviewerResult.result.ccs != null) {
                for (AccountInfo accountInfo : reviewerResult.result.ccs) {
                    if (Objects.equals(id.get(), accountInfo._accountId)) {
                        ccOrReviewer = true;
                        break;
                    }
                }
            }
        }
        if (!ccOrReviewer) {
            // User posting this review isn't currently in the reviewer or CC list,
            // isn't being explicitly added, and isn't voting on any label.
            // Automatically CC them on this change so they receive replies.
            PostReviewers.Addition selfAddition = postReviewers.ccCurrentUser(revision.getUser(), revision);
            bu.addOp(revision.getChange().getId(), selfAddition.op);
        }
        bu.addOp(revision.getChange().getId(), new Op(revision.getPatchSet().getId(), input, accountsToNotify));
        bu.execute();
        for (PostReviewers.Addition reviewerResult : reviewerResults) {
            reviewerResult.gatherResults();
        }
        emailReviewers(revision.getChange(), reviewerResults, input.notify, accountsToNotify);
    }
    return Response.ok(output);
}
Also used : ON_BEHALF_OF(com.google.gerrit.server.permissions.LabelPermission.ForUser.ON_BEHALF_OF) ListMultimap(com.google.common.collect.ListMultimap) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) PatchSetApproval(com.google.gerrit.reviewdb.client.PatchSetApproval) ReviewerSet(com.google.gerrit.server.ReviewerSet) Config(org.eclipse.jgit.lib.Config) Map(java.util.Map) RetryHelper(com.google.gerrit.server.update.RetryHelper) DraftHandling(com.google.gerrit.extensions.api.changes.ReviewInput.DraftHandling) Side(com.google.gerrit.extensions.client.Side) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) ChangeMessage(com.google.gerrit.reviewdb.client.ChangeMessage) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) NotifyHandling(com.google.gerrit.extensions.api.changes.NotifyHandling) CommentAdded(com.google.gerrit.server.extensions.events.CommentAdded) AutoValue(com.google.auto.value.AutoValue) LabelId(com.google.gerrit.reviewdb.client.LabelId) NotesMigration(com.google.gerrit.server.notedb.NotesMigration) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Singleton(com.google.inject.Singleton) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) Change(com.google.gerrit.reviewdb.client.Change) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) CommentsUtil(com.google.gerrit.server.CommentsUtil) Response(com.google.gerrit.extensions.restapi.Response) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) REVIEWER(com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER) HashCode(com.google.common.hash.HashCode) PatchListCache(com.google.gerrit.server.patch.PatchListCache) TimeUtil(com.google.gerrit.common.TimeUtil) MoreObjects(com.google.common.base.MoreObjects) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) CommentsUtil.setCommentRevId(com.google.gerrit.server.CommentsUtil.setCommentRevId) RobotCommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.RobotCommentInput) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) LabelVote(com.google.gerrit.server.util.LabelVote) SC_BAD_REQUEST(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST) ChangeControl(com.google.gerrit.server.project.ChangeControl) AddReviewerResult(com.google.gerrit.extensions.api.changes.AddReviewerResult) OrmException(com.google.gwtorm.server.OrmException) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) UpdateException(com.google.gerrit.server.update.UpdateException) Comment(com.google.gerrit.reviewdb.client.Comment) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) Gson(com.google.gson.Gson) AuthException(com.google.gerrit.extensions.restapi.AuthException) Context(com.google.gerrit.server.update.Context) RetryingRestModifyView(com.google.gerrit.server.update.RetryingRestModifyView) Collectors.toSet(java.util.stream.Collectors.toSet) ReviewerInfo(com.google.gerrit.extensions.api.changes.ReviewerInfo) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) LabelType(com.google.gerrit.common.data.LabelType) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Objects(java.util.Objects) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Status(com.google.gerrit.reviewdb.client.PatchLineComment.Status) AccountsCollection(com.google.gerrit.server.account.AccountsCollection) LabelTypes(com.google.gerrit.common.data.LabelTypes) AddReviewerInput(com.google.gerrit.extensions.api.changes.AddReviewerInput) FixSuggestionInfo(com.google.gerrit.extensions.common.FixSuggestionInfo) Url(com.google.gerrit.extensions.restapi.Url) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) RobotComment(com.google.gerrit.reviewdb.client.RobotComment) LabelPermission(com.google.gerrit.server.permissions.LabelPermission) FixSuggestion(com.google.gerrit.reviewdb.client.FixSuggestion) ChangePermission(com.google.gerrit.server.permissions.ChangePermission) Hashing(com.google.common.hash.Hashing) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) Patch(com.google.gerrit.reviewdb.client.Patch) HashMap(java.util.HashMap) OptionalInt(java.util.OptionalInt) HashSet(java.util.HashSet) CommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput) Range(com.google.gerrit.extensions.client.Comment.Range) Account(com.google.gerrit.reviewdb.client.Account) ChangeUtil(com.google.gerrit.server.ChangeUtil) OutputFormat(com.google.gerrit.server.OutputFormat) ChangeContext(com.google.gerrit.server.update.ChangeContext) FixReplacementInfo(com.google.gerrit.extensions.common.FixReplacementInfo) CurrentUser(com.google.gerrit.server.CurrentUser) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) FixReplacement(com.google.gerrit.reviewdb.client.FixReplacement) Maps(com.google.common.collect.Maps) ApprovalsUtil(com.google.gerrit.server.ApprovalsUtil) Collectors.toList(java.util.stream.Collectors.toList) Address(com.google.gerrit.server.mail.Address) Provider(com.google.inject.Provider) Ordering(com.google.common.collect.Ordering) RecipientType(com.google.gerrit.extensions.api.changes.RecipientType) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) Collections(java.util.Collections) Account(com.google.gerrit.reviewdb.client.Account) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) RecipientType(com.google.gerrit.extensions.api.changes.RecipientType) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AddReviewerResult(com.google.gerrit.extensions.api.changes.AddReviewerResult) ReviewerSet(com.google.gerrit.server.ReviewerSet) LabelId(com.google.gerrit.reviewdb.client.LabelId) CommentsUtil.setCommentRevId(com.google.gerrit.server.CommentsUtil.setCommentRevId) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) AddReviewerInput(com.google.gerrit.extensions.api.changes.AddReviewerInput) ReviewerInfo(com.google.gerrit.extensions.api.changes.ReviewerInfo)

Example 2 with ReviewResult

use of com.google.gerrit.extensions.api.changes.ReviewResult in project gerrit by GerritCodeReview.

the class PostReviewIT method addingAndDeletingReviewers.

@Test
public void addingAndDeletingReviewers() throws Exception {
    PushOneCommit.Result r = createChange();
    TestAccount user2 = accountCreator.user2();
    TestAccount user3 = accountCreator.create("user3", "user3@email.com", "user3", "user3");
    TestAccount user4 = accountCreator.create("user4", "user4@email.com", "user4", "user4");
    // add user and user2
    gApi.changes().id(r.getChangeId()).current().review(ReviewInput.create().reviewer(user.email()).reviewer(user2.email()));
    sender.clear();
    TestReviewerAddedListener testReviewerAddedListener = new TestReviewerAddedListener();
    TestReviewerDeletedListener testReviewerDeletedListener = new TestReviewerDeletedListener();
    try (Registration registration = extensionRegistry.newRegistration().add(testReviewerAddedListener).add(testReviewerDeletedListener)) {
        // remove user and user2 while adding user3 and user4
        ReviewResult reviewResult = gApi.changes().id(r.getChangeId()).current().review(ReviewInput.create().reviewer(user.email(), ReviewerState.REMOVED, /* confirmed= */
        true).reviewer(user2.email(), ReviewerState.REMOVED, /* confirmed= */
        true).reviewer(user3.email()).reviewer(user4.email()));
        assertThat(reviewResult.reviewers.values().stream().filter(a -> a.removed != null).map(a -> a.removed.name).collect(toImmutableSet())).containsExactly(user.fullName(), user2.fullName());
        assertThat(reviewResult.reviewers.values().stream().filter(a -> a.reviewers != null).map(a -> Iterables.getOnlyElement(a.reviewers).name).collect(toImmutableSet())).containsExactly(user3.fullName(), user4.fullName());
    }
    assertThat(gApi.changes().id(r.getChangeId()).reviewers().stream().map(a -> a.name).collect(toImmutableSet())).containsExactly(user3.fullName(), user4.fullName());
    // Ensure only one batch email was sent for this operation
    FakeEmailSender.Message message = Iterables.getOnlyElement(sender.getMessages());
    assertThat(message.body()).containsMatch(Pattern.quote("Hello ") + "(" + Pattern.quote(String.format("%s, %s", user3.fullName(), user4.fullName())) + "|" + Pattern.quote(String.format("%s, %s", user4.fullName(), user3.fullName())) + ")");
    assertThat(message.htmlBody()).containsMatch("(" + Pattern.quote(String.format("%s and %s", user3.fullName(), user4.fullName())) + "|" + Pattern.quote(String.format("%s and %s", user4.fullName(), user3.fullName())) + ")" + Pattern.quote(" to <strong>review</strong> this change"));
    assertThat(message.body()).containsMatch(Pattern.quote("removed ") + "(" + Pattern.quote(String.format("%s, %s", user.fullName(), user2.fullName())) + "|" + Pattern.quote(String.format("%s, %s", user2.fullName(), user.fullName())) + ")");
    assertThat(message.htmlBody()).containsMatch(Pattern.quote("removed ") + "(" + Pattern.quote(String.format("%s and %s", user.fullName(), user2.fullName())) + "|" + Pattern.quote(String.format("%s and %s", user2.fullName(), user.fullName())) + ")");
    // Ensure that events have been sent:
    // * 1 batch event for adding user3 and user4 as reviewers
    // * 2 events for removing user and user2 as reviewers (one event per removed reviewer, batch
    // event not available for reviewer removal)
    assertThat(testReviewerAddedListener.receivedEvents).hasSize(1);
    assertThat(testReviewerAddedListener.getReviewerIds()).containsExactly(user3.id(), user4.id());
    assertThat(testReviewerDeletedListener.receivedEvents).hasSize(2);
    assertThat(testReviewerDeletedListener.getReviewerIds()).containsExactly(user.id(), user2.id());
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Module(com.google.inject.Module) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) TestAccount(com.google.gerrit.acceptance.TestAccount) Inject(com.google.inject.Inject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) ReviewerDeletedListener(com.google.gerrit.extensions.events.ReviewerDeletedListener) Registration(com.google.gerrit.acceptance.ExtensionRegistry.Registration) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) Map(java.util.Map) DraftHandling(com.google.gerrit.extensions.api.changes.ReviewInput.DraftHandling) Side(com.google.gerrit.extensions.client.Side) PostReview(com.google.gerrit.server.restapi.change.PostReview) ImmutableSet(com.google.common.collect.ImmutableSet) Mockito.clearInvocations(org.mockito.Mockito.clearInvocations) ImmutableMap(com.google.common.collect.ImmutableMap) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) SubmitRecord(com.google.gerrit.entities.SubmitRecord) RequestScopeOperations(com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Optional(java.util.Optional) GerritJUnit.assertThrows(com.google.gerrit.testing.GerritJUnit.assertThrows) Exports(com.google.gerrit.extensions.annotations.Exports) Pattern(java.util.regex.Pattern) Mockito.mock(org.mockito.Mockito.mock) FactoryModule(com.google.gerrit.extensions.config.FactoryModule) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) MockitoAnnotations.initMocks(org.mockito.MockitoAnnotations.initMocks) Iterables(com.google.common.collect.Iterables) CommentValidationContext(com.google.gerrit.extensions.validators.CommentValidationContext) LabelId(com.google.gerrit.entities.LabelId) DraftInput(com.google.gerrit.extensions.api.changes.DraftInput) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) CommentAddedListener(com.google.gerrit.extensions.events.CommentAddedListener) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) Captor(org.mockito.Captor) ReviewerAddedListener(com.google.gerrit.extensions.events.ReviewerAddedListener) ArrayList(java.util.ArrayList) CommentsRejectedException(com.google.gerrit.server.update.CommentsRejectedException) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) CommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput) TestCommentHelper(com.google.gerrit.testing.TestCommentHelper) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) OnPostReview(com.google.gerrit.server.restapi.change.OnPostReview) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) FakeEmailSender(com.google.gerrit.testing.FakeEmailSender) ExtensionRegistry(com.google.gerrit.acceptance.ExtensionRegistry) Before(org.junit.Before) SubmitRule(com.google.gerrit.server.rules.SubmitRule) ChangeMessageInfo(com.google.gerrit.extensions.common.ChangeMessageInfo) RobotCommentInfo(com.google.gerrit.extensions.common.RobotCommentInfo) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Correspondence(com.google.common.truth.Correspondence) Collectors.toList(java.util.stream.Collectors.toList) RobotCommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.RobotCommentInput) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) GerritConfig(com.google.gerrit.acceptance.config.GerritConfig) CommentValidator(com.google.gerrit.extensions.validators.CommentValidator) Registration(com.google.gerrit.acceptance.ExtensionRegistry.Registration) FakeEmailSender(com.google.gerrit.testing.FakeEmailSender) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) TestAccount(com.google.gerrit.acceptance.TestAccount) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 3 with ReviewResult

use of com.google.gerrit.extensions.api.changes.ReviewResult in project gerrit by GerritCodeReview.

the class ChangeReviewersIT method removingReviewerRemovesTheirVote.

@Test
public void removingReviewerRemovesTheirVote() throws Exception {
    String crLabel = LabelId.CODE_REVIEW;
    PushOneCommit.Result r = createChange();
    ReviewInput input = ReviewInput.approve().reviewer(admin.email());
    ReviewResult addResult = review(r.getChangeId(), r.getCommit().name(), input);
    assertThat(addResult.reviewers).isNotNull();
    assertThat(addResult.reviewers).hasSize(1);
    Map<String, LabelInfo> changeLabels = getChangeLabels(r.getChangeId());
    assertThat(changeLabels.get(crLabel).all).hasSize(1);
    RestResponse deleteResult = deleteReviewer(r.getChangeId(), admin);
    deleteResult.assertNoContent();
    changeLabels = getChangeLabels(r.getChangeId());
    assertThat(changeLabels.get(crLabel).all).isNull();
    // Check that the vote is gone even after the reviewer is added back
    addReviewer(r.getChangeId(), admin.email());
    changeLabels = getChangeLabels(r.getChangeId());
    assertThat(changeLabels.get(crLabel).all).isNull();
}
Also used : LabelInfo(com.google.gerrit.extensions.common.LabelInfo) RestResponse(com.google.gerrit.acceptance.RestResponse) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 4 with ReviewResult

use of com.google.gerrit.extensions.api.changes.ReviewResult in project gerrit by GerritCodeReview.

the class ChangeIT method pendingReviewers.

@Test
public void pendingReviewers() throws Exception {
    ConfigInput conf = new ConfigInput();
    conf.enableReviewerByEmail = InheritableBoolean.TRUE;
    gApi.projects().name(project.get()).config(conf);
    PushOneCommit.Result r = createWorkInProgressChange();
    String changeId = r.getChangeId();
    assertThat(gApi.changes().id(changeId).get().pendingReviewers).isEmpty();
    // Add some pending reviewers.
    String email1 = name("user1") + "@example.com";
    String email2 = name("user2") + "@example.com";
    String email3 = name("user3") + "@example.com";
    String email4 = name("user4") + "@example.com";
    accountOperations.newAccount().username(name("user1")).preferredEmail(email1).fullname("User1").create();
    accountOperations.newAccount().username(name("user2")).preferredEmail(email2).fullname("User2").create();
    accountOperations.newAccount().username(name("user3")).preferredEmail(email3).fullname("User3").create();
    accountOperations.newAccount().username(name("user4")).preferredEmail(email4).fullname("User4").create();
    ReviewInput in = ReviewInput.noScore().reviewer(email1).reviewer(email2).reviewer(email3, CC, false).reviewer(email4, CC, false).reviewer("byemail1@example.com").reviewer("byemail2@example.com").reviewer("byemail3@example.com", CC, false).reviewer("byemail4@example.com", CC, false);
    ReviewResult result = gApi.changes().id(changeId).current().review(in);
    assertThat(result.reviewers).isNotEmpty();
    ChangeInfo info = gApi.changes().id(changeId).get();
    Function<Collection<AccountInfo>, Collection<String>> toEmails = ais -> ais.stream().map(ai -> ai.email).collect(toSet());
    assertThat(toEmails.apply(info.pendingReviewers.get(REVIEWER))).containsExactly(email1, email2, "byemail1@example.com", "byemail2@example.com");
    assertThat(toEmails.apply(info.pendingReviewers.get(CC))).containsExactly(email3, email4, "byemail3@example.com", "byemail4@example.com");
    assertThat(info.pendingReviewers.get(REMOVED)).isNull();
    // Stage some pending reviewer removals.
    gApi.changes().id(changeId).reviewer(email1).remove();
    gApi.changes().id(changeId).reviewer(email3).remove();
    gApi.changes().id(changeId).reviewer("byemail1@example.com").remove();
    gApi.changes().id(changeId).reviewer("byemail3@example.com").remove();
    info = gApi.changes().id(changeId).get();
    assertThat(toEmails.apply(info.pendingReviewers.get(REVIEWER))).containsExactly(email2, "byemail2@example.com");
    assertThat(toEmails.apply(info.pendingReviewers.get(CC))).containsExactly(email4, "byemail4@example.com");
    assertThat(toEmails.apply(info.pendingReviewers.get(REMOVED))).containsExactly(email1, email3, "byemail1@example.com", "byemail3@example.com");
    // "Undo" a removal.
    in = ReviewInput.noScore().reviewer(email1);
    gApi.changes().id(changeId).current().review(in);
    info = gApi.changes().id(changeId).get();
    assertThat(toEmails.apply(info.pendingReviewers.get(REVIEWER))).containsExactly(email1, email2, "byemail2@example.com");
    assertThat(toEmails.apply(info.pendingReviewers.get(CC))).containsExactly(email4, "byemail4@example.com");
    assertThat(toEmails.apply(info.pendingReviewers.get(REMOVED))).containsExactly(email3, "byemail1@example.com", "byemail3@example.com");
    // "Commit" by moving out of WIP.
    gApi.changes().id(changeId).setReadyForReview();
    info = gApi.changes().id(changeId).get();
    assertThat(info.pendingReviewers).isEmpty();
    assertThat(toEmails.apply(info.reviewers.get(REVIEWER))).containsExactly(email1, email2, "byemail2@example.com");
    assertThat(toEmails.apply(info.reviewers.get(CC))).containsExactly(email4, "byemail4@example.com");
    assertThat(info.reviewers.get(REMOVED)).isNull();
}
Also used : NotifyInfo(com.google.gerrit.extensions.api.changes.NotifyInfo) MERGED(com.google.gerrit.extensions.client.ChangeStatus.MERGED) CHANGE_OWNER(com.google.gerrit.server.group.SystemGroupBackend.CHANGE_OWNER) CommentInfo(com.google.gerrit.extensions.common.CommentInfo) SystemGroupBackend(com.google.gerrit.server.group.SystemGroupBackend) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TestProjectUpdate.blockLabel(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.blockLabel) PROJECT_OWNERS(com.google.gerrit.server.group.SystemGroupBackend.PROJECT_OWNERS) Map(java.util.Map) DraftHandling(com.google.gerrit.extensions.api.changes.ReviewInput.DraftHandling) Side(com.google.gerrit.extensions.client.Side) ThrowableSubject(com.google.common.truth.ThrowableSubject) EnumSet(java.util.EnumSet) FILE_NAME(com.google.gerrit.acceptance.PushOneCommit.FILE_NAME) DeleteVoteInput(com.google.gerrit.extensions.api.changes.DeleteVoteInput) Result(org.eclipse.jgit.lib.RefUpdate.Result) Constants(org.eclipse.jgit.lib.Constants) Collectors.joining(java.util.stream.Collectors.joining) NoHttpd(com.google.gerrit.acceptance.NoHttpd) RequestScopeOperations(com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations) PersonIdent(org.eclipse.jgit.lib.PersonIdent) UseClockStep(com.google.gerrit.acceptance.UseClockStep) Stream(java.util.stream.Stream) DeleteReviewerInput(com.google.gerrit.extensions.api.changes.DeleteReviewerInput) MESSAGES(com.google.gerrit.extensions.client.ListChangesOption.MESSAGES) PushResult(org.eclipse.jgit.transport.PushResult) ProjectInput(com.google.gerrit.extensions.api.projects.ProjectInput) DiffSummary(com.google.gerrit.server.patch.DiffSummary) GerritJUnit.assertThrows(com.google.gerrit.testing.GerritJUnit.assertThrows) Exports(com.google.gerrit.extensions.annotations.Exports) IndexPreloadingUtil(com.google.gerrit.httpd.raw.IndexPreloadingUtil) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) RawInputUtil(com.google.gerrit.common.RawInputUtil) AccountOperations(com.google.gerrit.acceptance.testsuite.account.AccountOperations) ReviewerInput(com.google.gerrit.extensions.api.changes.ReviewerInput) Lists(com.google.common.collect.Lists) LabelFunction(com.google.gerrit.entities.LabelFunction) ExtensionRegistry(com.google.gerrit.acceptance.ExtensionRegistry) TestRepository(org.eclipse.jgit.junit.TestRepository) CURRENT_ACTIONS(com.google.gerrit.extensions.client.ListChangesOption.CURRENT_ACTIONS) ObjectIds.abbreviateName(com.google.gerrit.git.ObjectIds.abbreviateName) IOException(java.io.IOException) Test(org.junit.Test) AccountTemplateUtil(com.google.gerrit.server.util.AccountTemplateUtil) Project(com.google.gerrit.entities.Project) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) Named(com.google.inject.name.Named) FooterConstants(com.google.gerrit.common.FooterConstants) GitUtil.assertPushOk(com.google.gerrit.acceptance.GitUtil.assertPushOk) AbstractModule(com.google.inject.AbstractModule) RefNames.changeMetaRef(com.google.gerrit.entities.RefNames.changeMetaRef) Inject(com.google.inject.Inject) REVIEWER(com.google.gerrit.extensions.client.ReviewerState.REVIEWER) FILE_CONTENT(com.google.gerrit.acceptance.PushOneCommit.FILE_CONTENT) InheritableBoolean(com.google.gerrit.extensions.client.InheritableBoolean) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) LabelType(com.google.gerrit.entities.LabelType) REVIEWED(com.google.gerrit.extensions.client.ListChangesOption.REVIEWED) AuthException(com.google.gerrit.extensions.restapi.AuthException) ChangeInput(com.google.gerrit.extensions.common.ChangeInput) CHECK(com.google.gerrit.extensions.client.ListChangesOption.CHECK) IntraLineDiffKey(com.google.gerrit.server.patch.IntraLineDiffKey) ImmutableSet(com.google.common.collect.ImmutableSet) SubmitType(com.google.gerrit.extensions.client.SubmitType) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ChangeData(com.google.gerrit.server.query.change.ChangeData) RebaseInput(com.google.gerrit.extensions.api.changes.RebaseInput) TestProjectUpdate.block(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.block) LabelId(com.google.gerrit.entities.LabelId) DraftInput(com.google.gerrit.extensions.api.changes.DraftInput) Function(java.util.function.Function) MessageFormat(java.text.MessageFormat) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult) ImmutableList(com.google.common.collect.ImmutableList) Change(com.google.gerrit.entities.Change) Truth8.assertThat(com.google.common.truth.Truth8.assertThat) ChangeContext(com.google.gerrit.server.update.ChangeContext) TestProjectUpdate.allowCapability(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allowCapability) UTF_8(java.nio.charset.StandardCharsets.UTF_8) CHANGE_ACTIONS(com.google.gerrit.extensions.client.ListChangesOption.CHANGE_ACTIONS) Truth.assertThat(com.google.common.truth.Truth.assertThat) Collectors.toList(java.util.stream.Collectors.toList) Message(com.google.gerrit.testing.FakeEmailSender.Message) GerritConfig(com.google.gerrit.acceptance.config.GerritConfig) COMMIT_FOOTERS(com.google.gerrit.extensions.client.ListChangesOption.COMMIT_FOOTERS) Cache(com.google.common.cache.Cache) StarredChangesUtil(com.google.gerrit.server.StarredChangesUtil) TestProjectUpdate.labelPermissionKey(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.labelPermissionKey) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Arrays(java.util.Arrays) LabelInfo(com.google.gerrit.extensions.common.LabelInfo) GlobalCapability(com.google.gerrit.common.data.GlobalCapability) TrackingIdInfo(com.google.gerrit.extensions.common.TrackingIdInfo) TestAccount(com.google.gerrit.acceptance.TestAccount) REGISTERED_USERS(com.google.gerrit.server.group.SystemGroupBackend.REGISTERED_USERS) CommitReceivedEvent(com.google.gerrit.server.events.CommitReceivedEvent) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) DiffSummaryKey(com.google.gerrit.server.patch.DiffSummaryKey) Registration(com.google.gerrit.acceptance.ExtensionRegistry.Registration) ConfigInput(com.google.gerrit.extensions.api.projects.ConfigInput) GroupOperations(com.google.gerrit.acceptance.testsuite.group.GroupOperations) TestProjectUpdate.allow(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allow) DeleteDraftCommentsInput(com.google.gerrit.extensions.api.accounts.DeleteDraftCommentsInput) ApprovalInfo(com.google.gerrit.extensions.common.ApprovalInfo) ChangeMessages(com.google.gerrit.server.change.ChangeMessages) ChangeOperatorFactory(com.google.gerrit.server.query.change.ChangeQueryBuilder.ChangeOperatorFactory) Set(java.util.Set) RefUpdate(org.eclipse.jgit.lib.RefUpdate) TestLabels.label(com.google.gerrit.server.project.testing.TestLabels.label) TestLabels.value(com.google.gerrit.server.project.testing.TestLabels.value) BranchNameKey(com.google.gerrit.entities.BranchNameKey) NotifyHandling(com.google.gerrit.extensions.api.changes.NotifyHandling) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) CacheStats(com.google.common.cache.CacheStats) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Iterables(com.google.common.collect.Iterables) BranchInput(com.google.gerrit.extensions.api.projects.BranchInput) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) TestChangeETagComputation(com.google.gerrit.server.change.testing.TestChangeETagComputation) TestLabels(com.google.gerrit.server.project.testing.TestLabels) ArrayList(java.util.ArrayList) CURRENT_COMMIT(com.google.gerrit.extensions.client.ListChangesOption.CURRENT_COMMIT) ChangeMessageModifier(com.google.gerrit.server.git.ChangeMessageModifier) PatchSet(com.google.gerrit.entities.PatchSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) GitUtil(com.google.gerrit.acceptance.GitUtil) Address(com.google.gerrit.entities.Address) WorkInProgressStateChangedListener(com.google.gerrit.extensions.events.WorkInProgressStateChangedListener) AccountGroup(com.google.gerrit.entities.AccountGroup) CommitValidationMessage(com.google.gerrit.server.git.validators.CommitValidationMessage) CacheStatsSubject.assertThat(com.google.gerrit.truth.CacheStatsSubject.assertThat) StorageException(com.google.gerrit.exceptions.StorageException) ChangeIndexedCounter(com.google.gerrit.acceptance.ChangeIndexedCounter) ANONYMOUS_USERS(com.google.gerrit.server.group.SystemGroupBackend.ANONYMOUS_USERS) CommitValidationListener(com.google.gerrit.server.git.validators.CommitValidationListener) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) ChangeKind(com.google.gerrit.extensions.client.ChangeKind) ChangeIndexCollection(com.google.gerrit.server.index.change.ChangeIndexCollection) Repository(org.eclipse.jgit.lib.Repository) REMOVED(com.google.gerrit.extensions.client.ReviewerState.REMOVED) ALL_REVISIONS(com.google.gerrit.extensions.client.ListChangesOption.ALL_REVISIONS) RevisionInfo(com.google.gerrit.extensions.common.RevisionInfo) GroupApi(com.google.gerrit.extensions.api.groups.GroupApi) PUSH_CERTIFICATES(com.google.gerrit.extensions.client.ListChangesOption.PUSH_CERTIFICATES) IntraLineDiff(com.google.gerrit.server.patch.IntraLineDiff) PostFilterPredicate(com.google.gerrit.index.query.PostFilterPredicate) DraftApi(com.google.gerrit.extensions.api.changes.DraftApi) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) DEFAULT_LABEL(com.google.gerrit.server.StarredChangesUtil.DEFAULT_LABEL) RefNames(com.google.gerrit.entities.RefNames) Collectors.toSet(java.util.stream.Collectors.toSet) PostReview(com.google.gerrit.server.restapi.change.PostReview) ReviewerInfo(com.google.gerrit.extensions.api.changes.ReviewerInfo) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) ImmutableMap(com.google.common.collect.ImmutableMap) VerifyNoPiiInChangeNotes(com.google.gerrit.acceptance.VerifyNoPiiInChangeNotes) RevisionApi(com.google.gerrit.extensions.api.changes.RevisionApi) DETAILED_LABELS(com.google.gerrit.extensions.client.ListChangesOption.DETAILED_LABELS) Account(com.google.gerrit.entities.Account) CommitInfo(com.google.gerrit.extensions.common.CommitInfo) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) List(java.util.List) Optional(java.util.Optional) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) GitPerson(com.google.gerrit.extensions.common.GitPerson) TestProjectUpdate.allowLabel(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allowLabel) IndexConfig(com.google.gerrit.index.IndexConfig) CC(com.google.gerrit.extensions.client.ReviewerState.CC) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) RelatedChangeAndCommitInfo(com.google.gerrit.extensions.api.changes.RelatedChangeAndCommitInfo) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) HashMap(java.util.HashMap) TestProjectInput(com.google.gerrit.acceptance.TestProjectInput) UseTimezone(com.google.gerrit.acceptance.UseTimezone) ChangeResource(com.google.gerrit.server.change.ChangeResource) SUBJECT(com.google.gerrit.acceptance.PushOneCommit.SUBJECT) Range(com.google.gerrit.extensions.client.Comment.Range) CURRENT_REVISION(com.google.gerrit.extensions.client.ListChangesOption.CURRENT_REVISION) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) ListChangesOption(com.google.gerrit.extensions.client.ListChangesOption) GitUtil.pushHead(com.google.gerrit.acceptance.GitUtil.pushHead) TRACKING_IDS(com.google.gerrit.extensions.client.ListChangesOption.TRACKING_IDS) CommitValidationException(com.google.gerrit.server.git.validators.CommitValidationException) Iterator(java.util.Iterator) Permission(com.google.gerrit.entities.Permission) ChangeMessageInfo(com.google.gerrit.extensions.common.ChangeMessageInfo) IndexedChangeQuery(com.google.gerrit.server.index.change.IndexedChangeQuery) TestProjectUpdate.permissionKey(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.permissionKey) ProjectOperations(com.google.gerrit.acceptance.testsuite.project.ProjectOperations) RecipientType(com.google.gerrit.extensions.api.changes.RecipientType) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AttentionSetInput(com.google.gerrit.extensions.api.changes.AttentionSetInput) ChangeIndex(com.google.gerrit.server.index.change.ChangeIndex) CacheStatsSubject.cloneStats(com.google.gerrit.truth.CacheStatsSubject.cloneStats) ChangeStatus(com.google.gerrit.extensions.client.ChangeStatus) ConfigInput(com.google.gerrit.extensions.api.projects.ConfigInput) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) Collection(java.util.Collection) ChangeIndexCollection(com.google.gerrit.server.index.change.ChangeIndexCollection) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 5 with ReviewResult

use of com.google.gerrit.extensions.api.changes.ReviewResult in project gerrit by GerritCodeReview.

the class ChangeIT method deleteGroupFromReviewersFails.

@Test
public void deleteGroupFromReviewersFails() throws Exception {
    PushOneCommit.Result r = createChange();
    // create a group named "kobe" with one user: lee
    String myGroupUserEmail = "lee@example.com";
    String myGroupUserFullname = "lee";
    accountOperations.newAccount().username("lee").preferredEmail(myGroupUserEmail).fullname(myGroupUserFullname).create();
    String groupName = "kobe";
    String testGroup = groupOperations.newGroup().name(groupName).create().get();
    GroupApi groupApi = gApi.groups().id(testGroup);
    groupApi.description("test group");
    groupApi.addMembers(myGroupUserFullname);
    // add the user as reviewer.
    gApi.changes().id(r.getChangeId()).addReviewer(myGroupUserFullname);
    // fail to remove that user via group.
    ReviewResult reviewResult = gApi.changes().id(r.getChangeId()).current().review(ReviewInput.create().reviewer(testGroup, REMOVED, /* confirmed= */
    true));
    assertThat(reviewResult.error).isEqualTo("error adding reviewer");
    ReviewerInput in = new ReviewerInput();
    in.reviewer = testGroup;
    in.state = REMOVED;
    ReviewerResult reviewerResult = gApi.changes().id(r.getChangeId()).addReviewer(in);
    assertThat(reviewerResult.error).isEqualTo(MessageFormat.format(ChangeMessages.get().groupRemovalIsNotAllowed, groupName));
}
Also used : GroupApi(com.google.gerrit.extensions.api.groups.GroupApi) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) DeleteReviewerInput(com.google.gerrit.extensions.api.changes.DeleteReviewerInput) ReviewerInput(com.google.gerrit.extensions.api.changes.ReviewerInput) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Aggregations

ReviewResult (com.google.gerrit.extensions.api.changes.ReviewResult)19 ReviewInput (com.google.gerrit.extensions.api.changes.ReviewInput)18 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)17 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)17 Test (org.junit.Test)17 TestAccount (com.google.gerrit.acceptance.TestAccount)7 ChangeInfo (com.google.gerrit.extensions.common.ChangeInfo)7 ArrayList (java.util.ArrayList)7 DraftHandling (com.google.gerrit.extensions.api.changes.ReviewInput.DraftHandling)6 ReviewerState (com.google.gerrit.extensions.client.ReviewerState)6 Side (com.google.gerrit.extensions.client.Side)6 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)6 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)6 ChangeData (com.google.gerrit.server.query.change.ChangeData)6 Inject (com.google.inject.Inject)6 Timestamp (java.sql.Timestamp)6 Collection (java.util.Collection)6 List (java.util.List)6 Map (java.util.Map)6 Collectors.toList (java.util.stream.Collectors.toList)6