PageRenderTime 2ms CodeModel.GetById 26ms app.highlight 14ms RepoModel.GetById 0ms app.codeStats 0ms

/javatests/com/google/gerrit/server/notedb/AbstractChangeNotesTest.java

https://gitlab.com/chenfengxu/gerrit
Java | 299 lines | 253 code | 32 blank | 14 comment | 1 complexity | edf909f9eb51816647dcd875dcc1208f MD5 | raw file
  1// Copyright (C) 2014 The Android Open Source Project
  2//
  3// Licensed under the Apache License, Version 2.0 (the "License");
  4// you may not use this file except in compliance with the License.
  5// You may obtain a copy of the License at
  6//
  7// http://www.apache.org/licenses/LICENSE-2.0
  8//
  9// Unless required by applicable law or agreed to in writing, software
 10// distributed under the License is distributed on an "AS IS" BASIS,
 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12// See the License for the specific language governing permissions and
 13// limitations under the License.
 14
 15package com.google.gerrit.server.notedb;
 16
 17import static com.google.inject.Scopes.SINGLETON;
 18import static java.util.concurrent.TimeUnit.SECONDS;
 19
 20import com.google.common.collect.ImmutableList;
 21import com.google.gerrit.common.TimeUtil;
 22import com.google.gerrit.common.data.SubmitRecord;
 23import com.google.gerrit.extensions.config.FactoryModule;
 24import com.google.gerrit.metrics.DisabledMetricMaker;
 25import com.google.gerrit.metrics.MetricMaker;
 26import com.google.gerrit.reviewdb.client.Account;
 27import com.google.gerrit.reviewdb.client.Change;
 28import com.google.gerrit.reviewdb.client.Comment;
 29import com.google.gerrit.reviewdb.client.CommentRange;
 30import com.google.gerrit.reviewdb.client.PatchSet;
 31import com.google.gerrit.reviewdb.client.Project;
 32import com.google.gerrit.reviewdb.server.ReviewDb;
 33import com.google.gerrit.server.CurrentUser;
 34import com.google.gerrit.server.GerritPersonIdent;
 35import com.google.gerrit.server.IdentifiedUser;
 36import com.google.gerrit.server.InternalUser;
 37import com.google.gerrit.server.account.AccountCache;
 38import com.google.gerrit.server.account.FakeRealm;
 39import com.google.gerrit.server.account.GroupBackend;
 40import com.google.gerrit.server.account.Realm;
 41import com.google.gerrit.server.config.AllUsersName;
 42import com.google.gerrit.server.config.AllUsersNameProvider;
 43import com.google.gerrit.server.config.AnonymousCowardName;
 44import com.google.gerrit.server.config.AnonymousCowardNameProvider;
 45import com.google.gerrit.server.config.CanonicalWebUrl;
 46import com.google.gerrit.server.config.DisableReverseDnsLookup;
 47import com.google.gerrit.server.config.GerritServerConfig;
 48import com.google.gerrit.server.config.GerritServerId;
 49import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
 50import com.google.gerrit.server.git.GitModule;
 51import com.google.gerrit.server.git.GitRepositoryManager;
 52import com.google.gerrit.server.group.SystemGroupBackend;
 53import com.google.gerrit.server.project.ProjectCache;
 54import com.google.gerrit.testing.ConfigSuite;
 55import com.google.gerrit.testing.FakeAccountCache;
 56import com.google.gerrit.testing.GerritBaseTests;
 57import com.google.gerrit.testing.InMemoryRepositoryManager;
 58import com.google.gerrit.testing.TestChanges;
 59import com.google.gerrit.testing.TestTimeUtil;
 60import com.google.gwtorm.server.OrmException;
 61import com.google.gwtorm.server.SchemaFactory;
 62import com.google.inject.Guice;
 63import com.google.inject.Inject;
 64import com.google.inject.Injector;
 65import com.google.inject.TypeLiteral;
 66import com.google.inject.util.Providers;
 67import java.sql.Timestamp;
 68import java.util.TimeZone;
 69import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
 70import org.eclipse.jgit.junit.TestRepository;
 71import org.eclipse.jgit.lib.Config;
 72import org.eclipse.jgit.lib.PersonIdent;
 73import org.eclipse.jgit.revwalk.RevWalk;
 74import org.junit.After;
 75import org.junit.Before;
 76import org.junit.Ignore;
 77import org.junit.runner.RunWith;
 78
 79@Ignore
 80@RunWith(ConfigSuite.class)
 81public abstract class AbstractChangeNotesTest extends GerritBaseTests {
 82  @ConfigSuite.Default
 83  public static Config changeNotesLegacy() {
 84    Config cfg = new Config();
 85    cfg.setBoolean("notedb", null, "writeJson", false);
 86    return cfg;
 87  }
 88
 89  @ConfigSuite.Config
 90  public static Config changeNotesJson() {
 91    Config cfg = new Config();
 92    cfg.setBoolean("notedb", null, "writeJson", true);
 93    return cfg;
 94  }
 95
 96  @ConfigSuite.Parameter public Config testConfig;
 97
 98  private static final TimeZone TZ = TimeZone.getTimeZone("America/Los_Angeles");
 99
100  protected Account.Id otherUserId;
101  protected FakeAccountCache accountCache;
102  protected IdentifiedUser changeOwner;
103  protected IdentifiedUser otherUser;
104  protected InMemoryRepository repo;
105  protected InMemoryRepositoryManager repoManager;
106  protected PersonIdent serverIdent;
107  protected InternalUser internalUser;
108  protected Project.NameKey project;
109  protected RevWalk rw;
110  protected TestRepository<InMemoryRepository> tr;
111
112  @Inject protected IdentifiedUser.GenericFactory userFactory;
113
114  @Inject protected NoteDbUpdateManager.Factory updateManagerFactory;
115
116  @Inject protected AllUsersName allUsers;
117
118  @Inject protected AbstractChangeNotes.Args args;
119
120  @Inject @GerritServerId private String serverId;
121
122  protected Injector injector;
123  private String systemTimeZone;
124
125  @Before
126  public void setUpTestEnvironment() throws Exception {
127    setTimeForTesting();
128
129    serverIdent = new PersonIdent("Gerrit Server", "noreply@gerrit.com", TimeUtil.nowTs(), TZ);
130    project = new Project.NameKey("test-project");
131    repoManager = new InMemoryRepositoryManager();
132    repo = repoManager.createRepository(project);
133    tr = new TestRepository<>(repo);
134    rw = tr.getRevWalk();
135    accountCache = new FakeAccountCache();
136    Account co = new Account(new Account.Id(1), TimeUtil.nowTs());
137    co.setFullName("Change Owner");
138    co.setPreferredEmail("change@owner.com");
139    accountCache.put(co);
140    Account ou = new Account(new Account.Id(2), TimeUtil.nowTs());
141    ou.setFullName("Other Account");
142    ou.setPreferredEmail("other@account.com");
143    accountCache.put(ou);
144
145    injector =
146        Guice.createInjector(
147            new FactoryModule() {
148              @Override
149              public void configure() {
150                install(new GitModule());
151                install(NoteDbModule.forTest(testConfig));
152                bind(AllUsersName.class).toProvider(AllUsersNameProvider.class);
153                bind(String.class).annotatedWith(GerritServerId.class).toInstance("gerrit");
154                bind(GitRepositoryManager.class).toInstance(repoManager);
155                bind(ProjectCache.class).toProvider(Providers.<ProjectCache>of(null));
156                bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(testConfig);
157                bind(String.class)
158                    .annotatedWith(AnonymousCowardName.class)
159                    .toProvider(AnonymousCowardNameProvider.class);
160                bind(String.class)
161                    .annotatedWith(CanonicalWebUrl.class)
162                    .toInstance("http://localhost:8080/");
163                bind(Boolean.class)
164                    .annotatedWith(DisableReverseDnsLookup.class)
165                    .toInstance(Boolean.FALSE);
166                bind(Realm.class).to(FakeRealm.class);
167                bind(GroupBackend.class).to(SystemGroupBackend.class).in(SINGLETON);
168                bind(AccountCache.class).toInstance(accountCache);
169                bind(PersonIdent.class)
170                    .annotatedWith(GerritPersonIdent.class)
171                    .toInstance(serverIdent);
172                bind(GitReferenceUpdated.class).toInstance(GitReferenceUpdated.DISABLED);
173                bind(MetricMaker.class).to(DisabledMetricMaker.class);
174                bind(ReviewDb.class).toProvider(Providers.<ReviewDb>of(null));
175
176                MutableNotesMigration migration = MutableNotesMigration.newDisabled();
177                migration.setFrom(NotesMigrationState.FINAL);
178                bind(MutableNotesMigration.class).toInstance(migration);
179                bind(NotesMigration.class).to(MutableNotesMigration.class);
180
181                // Tests don't support ReviewDb at all, but bindings are required via NoteDbModule.
182                bind(new TypeLiteral<SchemaFactory<ReviewDb>>() {})
183                    .toInstance(
184                        () -> {
185                          throw new UnsupportedOperationException();
186                        });
187                bind(ChangeBundleReader.class)
188                    .toInstance(
189                        (db, id) -> {
190                          throw new UnsupportedOperationException();
191                        });
192              }
193            });
194
195    injector.injectMembers(this);
196    repoManager.createRepository(allUsers);
197    changeOwner = userFactory.create(co.getId());
198    otherUser = userFactory.create(ou.getId());
199    otherUserId = otherUser.getAccountId();
200    internalUser = new InternalUser();
201  }
202
203  private void setTimeForTesting() {
204    systemTimeZone = System.setProperty("user.timezone", "US/Eastern");
205    TestTimeUtil.resetWithClockStep(1, SECONDS);
206  }
207
208  @After
209  public void resetTime() {
210    TestTimeUtil.useSystemTime();
211    System.setProperty("user.timezone", systemTimeZone);
212  }
213
214  protected Change newChange(boolean workInProgress) throws Exception {
215    Change c = TestChanges.newChange(project, changeOwner.getAccountId());
216    ChangeUpdate u = newUpdate(c, changeOwner);
217    u.setChangeId(c.getKey().get());
218    u.setBranch(c.getDest().get());
219    u.setWorkInProgress(workInProgress);
220    u.commit();
221    return c;
222  }
223
224  protected Change newWorkInProgressChange() throws Exception {
225    return newChange(true);
226  }
227
228  protected Change newChange() throws Exception {
229    return newChange(false);
230  }
231
232  protected ChangeUpdate newUpdate(Change c, CurrentUser user) throws Exception {
233    ChangeUpdate update = TestChanges.newUpdate(injector, c, user);
234    update.setPatchSetId(c.currentPatchSetId());
235    update.setAllowWriteToNewRef(true);
236    return update;
237  }
238
239  protected ChangeNotes newNotes(Change c) throws OrmException {
240    return new ChangeNotes(args, c).load();
241  }
242
243  protected static SubmitRecord submitRecord(
244      String status, String errorMessage, SubmitRecord.Label... labels) {
245    SubmitRecord rec = new SubmitRecord();
246    rec.status = SubmitRecord.Status.valueOf(status);
247    rec.errorMessage = errorMessage;
248    if (labels.length > 0) {
249      rec.labels = ImmutableList.copyOf(labels);
250    }
251    return rec;
252  }
253
254  protected static SubmitRecord.Label submitLabel(
255      String name, String status, Account.Id appliedBy) {
256    SubmitRecord.Label label = new SubmitRecord.Label();
257    label.label = name;
258    label.status = SubmitRecord.Label.Status.valueOf(status);
259    label.appliedBy = appliedBy;
260    return label;
261  }
262
263  protected Comment newComment(
264      PatchSet.Id psId,
265      String filename,
266      String UUID,
267      CommentRange range,
268      int line,
269      IdentifiedUser commenter,
270      String parentUUID,
271      Timestamp t,
272      String message,
273      short side,
274      String commitSHA1,
275      boolean unresolved) {
276    Comment c =
277        new Comment(
278            new Comment.Key(UUID, filename, psId.get()),
279            commenter.getAccountId(),
280            t,
281            side,
282            message,
283            serverId,
284            unresolved);
285    c.lineNbr = line;
286    c.parentUuid = parentUUID;
287    c.revId = commitSHA1;
288    c.setRange(range);
289    return c;
290  }
291
292  protected static Timestamp truncate(Timestamp ts) {
293    return new Timestamp((ts.getTime() / 1000) * 1000);
294  }
295
296  protected static Timestamp after(Change c, long millis) {
297    return new Timestamp(c.getCreatedOn().getTime() + millis);
298  }
299}