summaryrefslogtreecommitdiffstats
path: root/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbChecker.java
blob: 5ce08100e1ec43ee34b17edddbb11a0ec49acae0 (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
// Copyright (C) 2016 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.testutil;

import static com.google.common.truth.Truth.assertThat;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.reviewdb.server.ReviewDbUtil;
import com.google.gerrit.server.CommentsUtil;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.notedb.ChangeBundle;
import com.google.gerrit.server.notedb.ChangeBundleReader;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.notedb.MutableNotesMigration;
import com.google.gerrit.server.notedb.rebuild.ChangeRebuilder;
import com.google.gwtorm.client.IntKey;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.OrmRuntimeException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class NoteDbChecker {
  static final Logger log = LoggerFactory.getLogger(NoteDbChecker.class);

  private final Provider<ReviewDb> dbProvider;
  private final GitRepositoryManager repoManager;
  private final MutableNotesMigration notesMigration;
  private final ChangeBundleReader bundleReader;
  private final ChangeNotes.Factory notesFactory;
  private final ChangeRebuilder changeRebuilder;
  private final CommentsUtil commentsUtil;

  @Inject
  NoteDbChecker(
      Provider<ReviewDb> dbProvider,
      GitRepositoryManager repoManager,
      MutableNotesMigration notesMigration,
      ChangeBundleReader bundleReader,
      ChangeNotes.Factory notesFactory,
      ChangeRebuilder changeRebuilder,
      CommentsUtil commentsUtil) {
    this.dbProvider = dbProvider;
    this.repoManager = repoManager;
    this.bundleReader = bundleReader;
    this.notesMigration = notesMigration;
    this.notesFactory = notesFactory;
    this.changeRebuilder = changeRebuilder;
    this.commentsUtil = commentsUtil;
  }

  public void rebuildAndCheckAllChanges() throws Exception {
    rebuildAndCheckChanges(
        getUnwrappedDb().changes().all().toList().stream().map(Change::getId),
        ImmutableListMultimap.of());
  }

  public void rebuildAndCheckChanges(Change.Id... changeIds) throws Exception {
    rebuildAndCheckChanges(Arrays.stream(changeIds), ImmutableListMultimap.of());
  }

  private void rebuildAndCheckChanges(
      Stream<Change.Id> changeIds, ListMultimap<Change.Id, String> expectedDiffs) throws Exception {
    ReviewDb db = getUnwrappedDb();

    List<ChangeBundle> allExpected = readExpected(changeIds);

    boolean oldWrite = notesMigration.rawWriteChangesSetting();
    boolean oldRead = notesMigration.readChanges();
    try {
      notesMigration.setWriteChanges(true);
      notesMigration.setReadChanges(true);
      List<String> msgs = new ArrayList<>();
      for (ChangeBundle expected : allExpected) {
        Change c = expected.getChange();
        try {
          changeRebuilder.rebuild(db, c.getId());
        } catch (RepositoryNotFoundException e) {
          msgs.add("Repository not found for change, cannot convert: " + c);
        }
      }

      checkActual(allExpected, expectedDiffs, msgs);
    } finally {
      notesMigration.setReadChanges(oldRead);
      notesMigration.setWriteChanges(oldWrite);
    }
  }

  public void checkChanges(Change.Id... changeIds) throws Exception {
    checkActual(
        readExpected(Arrays.stream(changeIds)), ImmutableListMultimap.of(), new ArrayList<>());
  }

  public void rebuildAndCheckChange(Change.Id changeId, String... expectedDiff) throws Exception {
    ImmutableListMultimap.Builder<Change.Id, String> b = ImmutableListMultimap.builder();
    b.putAll(changeId, Arrays.asList(expectedDiff));
    rebuildAndCheckChanges(Stream.of(changeId), b.build());
  }

  public void assertNoChangeRef(Project.NameKey project, Change.Id changeId) throws Exception {
    try (Repository repo = repoManager.openRepository(project)) {
      assertThat(repo.exactRef(RefNames.changeMetaRef(changeId))).isNull();
    }
  }

  public void assertNoReviewDbChanges(Description desc) throws Exception {
    ReviewDb db = getUnwrappedDb();
    assertThat(db.changes().all().toList()).named("Changes in " + desc.getTestClass()).isEmpty();
    assertThat(db.changeMessages().all().toList())
        .named("ChangeMessages in " + desc.getTestClass())
        .isEmpty();
    assertThat(db.patchSets().all().toList())
        .named("PatchSets in " + desc.getTestClass())
        .isEmpty();
    assertThat(db.patchSetApprovals().all().toList())
        .named("PatchSetApprovals in " + desc.getTestClass())
        .isEmpty();
    assertThat(db.patchComments().all().toList())
        .named("PatchLineComments in " + desc.getTestClass())
        .isEmpty();
  }

  private List<ChangeBundle> readExpected(Stream<Change.Id> changeIds) throws Exception {
    boolean old = notesMigration.readChanges();
    try {
      notesMigration.setReadChanges(false);
      return changeIds
          .sorted(comparing(IntKey::get))
          .map(this::readBundleUnchecked)
          .collect(toList());
    } finally {
      notesMigration.setReadChanges(old);
    }
  }

  private ChangeBundle readBundleUnchecked(Change.Id id) {
    try {
      return bundleReader.fromReviewDb(getUnwrappedDb(), id);
    } catch (OrmException e) {
      throw new OrmRuntimeException(e);
    }
  }

  private void checkActual(
      List<ChangeBundle> allExpected,
      ListMultimap<Change.Id, String> expectedDiffs,
      List<String> msgs)
      throws Exception {
    ReviewDb db = getUnwrappedDb();
    boolean oldRead = notesMigration.readChanges();
    boolean oldWrite = notesMigration.rawWriteChangesSetting();
    try {
      notesMigration.setWriteChanges(true);
      notesMigration.setReadChanges(true);
      for (ChangeBundle expected : allExpected) {
        Change c = expected.getChange();
        ChangeBundle actual;
        try {
          actual =
              ChangeBundle.fromNotes(
                  commentsUtil, notesFactory.create(db, c.getProject(), c.getId()));
        } catch (Throwable t) {
          String msg = "Error converting change: " + c;
          msgs.add(msg);
          log.error(msg, t);
          continue;
        }
        List<String> diff = expected.differencesFrom(actual);
        List<String> expectedDiff = expectedDiffs.get(c.getId());
        if (!diff.equals(expectedDiff)) {
          msgs.add("Differences between ReviewDb and NoteDb for " + c + ":");
          msgs.addAll(diff);
          if (!expectedDiff.isEmpty()) {
            msgs.add("Expected differences:");
            msgs.addAll(expectedDiff);
          }
          msgs.add("");
        } else {
          System.err.println("NoteDb conversion of change " + c.getId() + " successful");
        }
      }
    } finally {
      notesMigration.setReadChanges(oldRead);
      notesMigration.setWriteChanges(oldWrite);
    }
    if (!msgs.isEmpty()) {
      throw new AssertionError(Joiner.on('\n').join(msgs));
    }
  }

  private ReviewDb getUnwrappedDb() {
    ReviewDb db = dbProvider.get();
    return ReviewDbUtil.unwrapDb(db);
  }
}