Custom Truth subjects: use new Subject#check approach

Truth has evolved since we first started to write custom Truth subjects
and the recommended way to create chained subjects has changed.
According to [1], the recommended way is to use Subject#check as thus
the FailureStrategy is retained and (most importantly for us) a nice
failure message listing the complete chain of objects/methods is
generated.

Example for a reference in a failure message
before this change:
  path

with this change:
  robotCommentInfos.onlyElement().fixSuggestions().onlyElement()
    .replacements().onlyElement().path()

[1] https://google.github.io/truth/extension

Change-Id: I9a3b7a877af48a7e5f7d334cf210aa4a5867abb5
This commit is contained in:
Alice Kober-Sotzek
2019-03-22 15:11:12 +01:00
parent 633b812c58
commit a8f3719dc4
26 changed files with 272 additions and 188 deletions

View File

@@ -20,14 +20,17 @@ import com.google.common.truth.ComparableSubject;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.common.data.GroupReference; import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.reviewdb.client.AccountGroup; import com.google.gerrit.reviewdb.client.AccountGroup;
public class GroupReferenceSubject extends Subject<GroupReferenceSubject, GroupReference> { public class GroupReferenceSubject extends Subject<GroupReferenceSubject, GroupReference> {
public static GroupReferenceSubject assertThat(GroupReference group) { public static GroupReferenceSubject assertThat(GroupReference group) {
return assertAbout(GroupReferenceSubject::new).that(group); return assertAbout(groupReferences()).that(group);
}
public static Subject.Factory<GroupReferenceSubject, GroupReference> groupReferences() {
return GroupReferenceSubject::new;
} }
private GroupReferenceSubject(FailureMetadata metadata, GroupReference group) { private GroupReferenceSubject(FailureMetadata metadata, GroupReference group) {
@@ -37,12 +40,12 @@ public class GroupReferenceSubject extends Subject<GroupReferenceSubject, GroupR
public ComparableSubject<?, AccountGroup.UUID> groupUuid() { public ComparableSubject<?, AccountGroup.UUID> groupUuid() {
isNotNull(); isNotNull();
GroupReference group = actual(); GroupReference group = actual();
return Truth.assertThat(group.getUUID()).named("groupUuid"); return check("groupUuid()").that(group.getUUID());
} }
public StringSubject name() { public StringSubject name() {
isNotNull(); isNotNull();
GroupReference group = actual(); GroupReference group = actual();
return Truth.assertThat(group.getName()).named("name"); return check("name()").that(group.getName());
} }
} }

View File

@@ -6,6 +6,7 @@ java_library(
deps = [ deps = [
"//java/com/google/gerrit/extensions:api", "//java/com/google/gerrit/extensions:api",
"//java/com/google/gerrit/truth", "//java/com/google/gerrit/truth",
"//lib:guava",
"//lib/jgit/org.eclipse.jgit:jgit", "//lib/jgit/org.eclipse.jgit:jgit",
"//lib/truth", "//lib/truth",
], ],

View File

@@ -15,18 +15,23 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static com.google.gerrit.extensions.common.testing.GitPersonSubject.gitPersons;
import static com.google.gerrit.truth.ListSubject.elements;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.common.CommitInfo; import com.google.gerrit.extensions.common.CommitInfo;
import com.google.gerrit.truth.ListSubject; import com.google.gerrit.truth.ListSubject;
public class CommitInfoSubject extends Subject<CommitInfoSubject, CommitInfo> { public class CommitInfoSubject extends Subject<CommitInfoSubject, CommitInfo> {
public static CommitInfoSubject assertThat(CommitInfo commitInfo) { public static CommitInfoSubject assertThat(CommitInfo commitInfo) {
return assertAbout(CommitInfoSubject::new).that(commitInfo); return assertAbout(commits()).that(commitInfo);
}
public static Subject.Factory<CommitInfoSubject, CommitInfo> commits() {
return CommitInfoSubject::new;
} }
private CommitInfoSubject(FailureMetadata failureMetadata, CommitInfo commitInfo) { private CommitInfoSubject(FailureMetadata failureMetadata, CommitInfo commitInfo) {
@@ -36,31 +41,30 @@ public class CommitInfoSubject extends Subject<CommitInfoSubject, CommitInfo> {
public StringSubject commit() { public StringSubject commit() {
isNotNull(); isNotNull();
CommitInfo commitInfo = actual(); CommitInfo commitInfo = actual();
return Truth.assertThat(commitInfo.commit).named("commit"); return check("commit()").that(commitInfo.commit);
} }
public ListSubject<CommitInfoSubject, CommitInfo> parents() { public ListSubject<CommitInfoSubject, CommitInfo> parents() {
isNotNull(); isNotNull();
CommitInfo commitInfo = actual(); CommitInfo commitInfo = actual();
return ListSubject.assertThat(commitInfo.parents, CommitInfoSubject::assertThat) return check("parents()").about(elements()).thatCustom(commitInfo.parents, commits());
.named("parents");
} }
public GitPersonSubject committer() { public GitPersonSubject committer() {
isNotNull(); isNotNull();
CommitInfo commitInfo = actual(); CommitInfo commitInfo = actual();
return GitPersonSubject.assertThat(commitInfo.committer).named("committer"); return check("committer()").about(gitPersons()).that(commitInfo.committer);
} }
public GitPersonSubject author() { public GitPersonSubject author() {
isNotNull(); isNotNull();
CommitInfo commitInfo = actual(); CommitInfo commitInfo = actual();
return GitPersonSubject.assertThat(commitInfo.author).named("author"); return check("author()").about(gitPersons()).that(commitInfo.author);
} }
public StringSubject message() { public StringSubject message() {
isNotNull(); isNotNull();
CommitInfo commitInfo = actual(); CommitInfo commitInfo = actual();
return Truth.assertThat(commitInfo.message).named("message"); return check("message").that(commitInfo.message);
} }
} }

View File

@@ -14,21 +14,27 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.truth.Fact.simpleFact;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static com.google.gerrit.truth.ListSubject.elements;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.IntegerSubject; import com.google.common.truth.IntegerSubject;
import com.google.common.truth.IterableSubject; import com.google.common.truth.IterableSubject;
import com.google.common.truth.StandardSubjectBuilder;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.common.DiffInfo.ContentEntry; import com.google.gerrit.extensions.common.DiffInfo.ContentEntry;
import com.google.gerrit.truth.ListSubject; import com.google.gerrit.truth.ListSubject;
public class ContentEntrySubject extends Subject<ContentEntrySubject, ContentEntry> { public class ContentEntrySubject extends Subject<ContentEntrySubject, ContentEntry> {
public static ContentEntrySubject assertThat(ContentEntry contentEntry) { public static ContentEntrySubject assertThat(ContentEntry contentEntry) {
return assertAbout(ContentEntrySubject::new).that(contentEntry); return assertAbout(contentEntries()).that(contentEntry);
}
public static Subject.Factory<ContentEntrySubject, ContentEntry> contentEntries() {
return ContentEntrySubject::new;
} }
private ContentEntrySubject(FailureMetadata failureMetadata, ContentEntry contentEntry) { private ContentEntrySubject(FailureMetadata failureMetadata, ContentEntry contentEntry) {
@@ -38,54 +44,54 @@ public class ContentEntrySubject extends Subject<ContentEntrySubject, ContentEnt
public void isDueToRebase() { public void isDueToRebase() {
isNotNull(); isNotNull();
ContentEntry contentEntry = actual(); ContentEntry contentEntry = actual();
Truth.assertWithMessage("Entry should be marked 'dueToRebase'") if (contentEntry.dueToRebase == null || !contentEntry.dueToRebase) {
.that(contentEntry.dueToRebase) failWithActual(simpleFact("expected entry to be marked 'dueToRebase'"));
.named("dueToRebase") }
.isTrue();
} }
public void isNotDueToRebase() { public void isNotDueToRebase() {
isNotNull(); isNotNull();
ContentEntry contentEntry = actual(); ContentEntry contentEntry = actual();
Truth.assertWithMessage("Entry should not be marked 'dueToRebase'") if (contentEntry.dueToRebase != null && contentEntry.dueToRebase) {
.that(contentEntry.dueToRebase) failWithActual(simpleFact("expected entry not to be marked 'dueToRebase'"));
.named("dueToRebase") }
.isNull();
} }
public ListSubject<StringSubject, String> commonLines() { public ListSubject<StringSubject, String> commonLines() {
isNotNull(); isNotNull();
ContentEntry contentEntry = actual(); ContentEntry contentEntry = actual();
return ListSubject.assertThat(contentEntry.ab, Truth::assertThat).named("common lines"); return check("commonLines()")
.about(elements())
.that(contentEntry.ab, StandardSubjectBuilder::that);
} }
public ListSubject<StringSubject, String> linesOfA() { public ListSubject<StringSubject, String> linesOfA() {
isNotNull(); isNotNull();
ContentEntry contentEntry = actual(); ContentEntry contentEntry = actual();
return ListSubject.assertThat(contentEntry.a, Truth::assertThat).named("lines of 'a'"); return check("linesOfA()").about(elements()).that(contentEntry.a, StandardSubjectBuilder::that);
} }
public ListSubject<StringSubject, String> linesOfB() { public ListSubject<StringSubject, String> linesOfB() {
isNotNull(); isNotNull();
ContentEntry contentEntry = actual(); ContentEntry contentEntry = actual();
return ListSubject.assertThat(contentEntry.b, Truth::assertThat).named("lines of 'b'"); return check("linesOfB()").about(elements()).that(contentEntry.b, StandardSubjectBuilder::that);
} }
public IterableSubject intralineEditsOfA() { public IterableSubject intralineEditsOfA() {
isNotNull(); isNotNull();
ContentEntry contentEntry = actual(); ContentEntry contentEntry = actual();
return Truth.assertThat(contentEntry.editA).named("intraline edits of 'a'"); return check("intralineEditsOfA()").that(contentEntry.editA);
} }
public IterableSubject intralineEditsOfB() { public IterableSubject intralineEditsOfB() {
isNotNull(); isNotNull();
ContentEntry contentEntry = actual(); ContentEntry contentEntry = actual();
return Truth.assertThat(contentEntry.editB).named("intraline edits of 'b'"); return check("intralineEditsOfB()").that(contentEntry.editB);
} }
public IntegerSubject numberOfSkippedLines() { public IntegerSubject numberOfSkippedLines() {
isNotNull(); isNotNull();
ContentEntry contentEntry = actual(); ContentEntry contentEntry = actual();
return Truth.assertThat(contentEntry.skip).named("number of skipped lines"); return check("numberOfSkippedLines()").that(contentEntry.skip);
} }
} }

View File

@@ -15,11 +15,12 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static com.google.gerrit.extensions.common.testing.FileMetaSubject.fileMetas;
import static com.google.gerrit.truth.ListSubject.elements;
import com.google.common.truth.ComparableSubject; import com.google.common.truth.ComparableSubject;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.common.ChangeType; import com.google.gerrit.extensions.common.ChangeType;
import com.google.gerrit.extensions.common.DiffInfo; import com.google.gerrit.extensions.common.DiffInfo;
import com.google.gerrit.extensions.common.DiffInfo.ContentEntry; import com.google.gerrit.extensions.common.DiffInfo.ContentEntry;
@@ -38,25 +39,26 @@ public class DiffInfoSubject extends Subject<DiffInfoSubject, DiffInfo> {
public ListSubject<ContentEntrySubject, ContentEntry> content() { public ListSubject<ContentEntrySubject, ContentEntry> content() {
isNotNull(); isNotNull();
DiffInfo diffInfo = actual(); DiffInfo diffInfo = actual();
return ListSubject.assertThat(diffInfo.content, ContentEntrySubject::assertThat) return check("content()")
.named("content"); .about(elements())
.thatCustom(diffInfo.content, ContentEntrySubject.contentEntries());
} }
public ComparableSubject<?, ChangeType> changeType() { public ComparableSubject<?, ChangeType> changeType() {
isNotNull(); isNotNull();
DiffInfo diffInfo = actual(); DiffInfo diffInfo = actual();
return Truth.assertThat(diffInfo.changeType).named("changeType"); return check("changeType()").that(diffInfo.changeType);
} }
public FileMetaSubject metaA() { public FileMetaSubject metaA() {
isNotNull(); isNotNull();
DiffInfo diffInfo = actual(); DiffInfo diffInfo = actual();
return FileMetaSubject.assertThat(diffInfo.metaA).named("metaA"); return check("metaA()").about(fileMetas()).that(diffInfo.metaA);
} }
public FileMetaSubject metaB() { public FileMetaSubject metaB() {
isNotNull(); isNotNull();
DiffInfo diffInfo = actual(); DiffInfo diffInfo = actual();
return FileMetaSubject.assertThat(diffInfo.metaB).named("metaB"); return check("metaB()").about(fileMetas()).that(diffInfo.metaB);
} }
} }

View File

@@ -15,11 +15,11 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static com.google.gerrit.extensions.common.testing.CommitInfoSubject.commits;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.common.EditInfo; import com.google.gerrit.extensions.common.EditInfo;
import com.google.gerrit.truth.OptionalSubject; import com.google.gerrit.truth.OptionalSubject;
import java.util.Optional; import java.util.Optional;
@@ -27,12 +27,16 @@ import java.util.Optional;
public class EditInfoSubject extends Subject<EditInfoSubject, EditInfo> { public class EditInfoSubject extends Subject<EditInfoSubject, EditInfo> {
public static EditInfoSubject assertThat(EditInfo editInfo) { public static EditInfoSubject assertThat(EditInfo editInfo) {
return assertAbout(EditInfoSubject::new).that(editInfo); return assertAbout(edits()).that(editInfo);
}
private static Subject.Factory<EditInfoSubject, EditInfo> edits() {
return EditInfoSubject::new;
} }
public static OptionalSubject<EditInfoSubject, EditInfo> assertThat( public static OptionalSubject<EditInfoSubject, EditInfo> assertThat(
Optional<EditInfo> editInfoOptional) { Optional<EditInfo> editInfoOptional) {
return OptionalSubject.assertThat(editInfoOptional, EditInfoSubject::assertThat); return OptionalSubject.assertThat(editInfoOptional, edits());
} }
private EditInfoSubject(FailureMetadata failureMetadata, EditInfo editInfo) { private EditInfoSubject(FailureMetadata failureMetadata, EditInfo editInfo) {
@@ -42,12 +46,12 @@ public class EditInfoSubject extends Subject<EditInfoSubject, EditInfo> {
public CommitInfoSubject commit() { public CommitInfoSubject commit() {
isNotNull(); isNotNull();
EditInfo editInfo = actual(); EditInfo editInfo = actual();
return CommitInfoSubject.assertThat(editInfo.commit).named("commit"); return check("commit()").about(commits()).that(editInfo.commit);
} }
public StringSubject baseRevision() { public StringSubject baseRevision() {
isNotNull(); isNotNull();
EditInfo editInfo = actual(); EditInfo editInfo = actual();
return Truth.assertThat(editInfo.baseRevision).named("baseRevision"); return check("baseRevision()").that(editInfo.baseRevision);
} }
} }

View File

@@ -20,7 +20,6 @@ import com.google.common.truth.ComparableSubject;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.IntegerSubject; import com.google.common.truth.IntegerSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.common.FileInfo; import com.google.gerrit.extensions.common.FileInfo;
public class FileInfoSubject extends Subject<FileInfoSubject, FileInfo> { public class FileInfoSubject extends Subject<FileInfoSubject, FileInfo> {
@@ -36,18 +35,18 @@ public class FileInfoSubject extends Subject<FileInfoSubject, FileInfo> {
public IntegerSubject linesInserted() { public IntegerSubject linesInserted() {
isNotNull(); isNotNull();
FileInfo fileInfo = actual(); FileInfo fileInfo = actual();
return Truth.assertThat(fileInfo.linesInserted).named("linesInserted"); return check("linesInserted()").that(fileInfo.linesInserted);
} }
public IntegerSubject linesDeleted() { public IntegerSubject linesDeleted() {
isNotNull(); isNotNull();
FileInfo fileInfo = actual(); FileInfo fileInfo = actual();
return Truth.assertThat(fileInfo.linesDeleted).named("linesDeleted"); return check("linesDeleted()").that(fileInfo.linesDeleted);
} }
public ComparableSubject<?, Character> status() { public ComparableSubject<?, Character> status() {
isNotNull(); isNotNull();
FileInfo fileInfo = actual(); FileInfo fileInfo = actual();
return Truth.assertThat(fileInfo.status).named("status"); return check("status()").that(fileInfo.status);
} }
} }

View File

@@ -19,13 +19,16 @@ import static com.google.common.truth.Truth.assertAbout;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.IntegerSubject; import com.google.common.truth.IntegerSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.common.DiffInfo.FileMeta; import com.google.gerrit.extensions.common.DiffInfo.FileMeta;
public class FileMetaSubject extends Subject<FileMetaSubject, FileMeta> { public class FileMetaSubject extends Subject<FileMetaSubject, FileMeta> {
public static FileMetaSubject assertThat(FileMeta fileMeta) { public static FileMetaSubject assertThat(FileMeta fileMeta) {
return assertAbout(FileMetaSubject::new).that(fileMeta); return assertAbout(fileMetas()).that(fileMeta);
}
public static Subject.Factory<FileMetaSubject, FileMeta> fileMetas() {
return FileMetaSubject::new;
} }
private FileMetaSubject(FailureMetadata failureMetadata, FileMeta fileMeta) { private FileMetaSubject(FailureMetadata failureMetadata, FileMeta fileMeta) {
@@ -35,6 +38,6 @@ public class FileMetaSubject extends Subject<FileMetaSubject, FileMeta> {
public IntegerSubject totalLineCount() { public IntegerSubject totalLineCount() {
isNotNull(); isNotNull();
FileMeta fileMeta = actual(); FileMeta fileMeta = actual();
return Truth.assertThat(fileMeta.lines).named("total line count"); return check("totalLineCount()").that(fileMeta.lines);
} }
} }

View File

@@ -15,18 +15,22 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static com.google.gerrit.extensions.common.testing.RangeSubject.ranges;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.common.FixReplacementInfo; import com.google.gerrit.extensions.common.FixReplacementInfo;
public class FixReplacementInfoSubject public class FixReplacementInfoSubject
extends Subject<FixReplacementInfoSubject, FixReplacementInfo> { extends Subject<FixReplacementInfoSubject, FixReplacementInfo> {
public static FixReplacementInfoSubject assertThat(FixReplacementInfo fixReplacementInfo) { public static FixReplacementInfoSubject assertThat(FixReplacementInfo fixReplacementInfo) {
return assertAbout(FixReplacementInfoSubject::new).that(fixReplacementInfo); return assertAbout(fixReplacements()).that(fixReplacementInfo);
}
public static Subject.Factory<FixReplacementInfoSubject, FixReplacementInfo> fixReplacements() {
return FixReplacementInfoSubject::new;
} }
private FixReplacementInfoSubject( private FixReplacementInfoSubject(
@@ -35,14 +39,17 @@ public class FixReplacementInfoSubject
} }
public StringSubject path() { public StringSubject path() {
return Truth.assertThat(actual().path).named("path"); isNotNull();
return check("path()").that(actual().path);
} }
public RangeSubject range() { public RangeSubject range() {
return RangeSubject.assertThat(actual().range).named("range"); isNotNull();
return check("range()").about(ranges()).that(actual().range);
} }
public StringSubject replacement() { public StringSubject replacement() {
return Truth.assertThat(actual().replacement).named("replacement"); isNotNull();
return check("replacement()").that(actual().replacement);
} }
} }

View File

@@ -15,6 +15,8 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static com.google.gerrit.extensions.common.testing.FixReplacementInfoSubject.fixReplacements;
import static com.google.gerrit.truth.ListSubject.elements;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
@@ -27,7 +29,11 @@ import com.google.gerrit.truth.ListSubject;
public class FixSuggestionInfoSubject extends Subject<FixSuggestionInfoSubject, FixSuggestionInfo> { public class FixSuggestionInfoSubject extends Subject<FixSuggestionInfoSubject, FixSuggestionInfo> {
public static FixSuggestionInfoSubject assertThat(FixSuggestionInfo fixSuggestionInfo) { public static FixSuggestionInfoSubject assertThat(FixSuggestionInfo fixSuggestionInfo) {
return assertAbout(FixSuggestionInfoSubject::new).that(fixSuggestionInfo); return assertAbout(fixSuggestions()).that(fixSuggestionInfo);
}
public static Subject.Factory<FixSuggestionInfoSubject, FixSuggestionInfo> fixSuggestions() {
return FixSuggestionInfoSubject::new;
} }
private FixSuggestionInfoSubject( private FixSuggestionInfoSubject(
@@ -40,8 +46,10 @@ public class FixSuggestionInfoSubject extends Subject<FixSuggestionInfoSubject,
} }
public ListSubject<FixReplacementInfoSubject, FixReplacementInfo> replacements() { public ListSubject<FixReplacementInfoSubject, FixReplacementInfo> replacements() {
return ListSubject.assertThat(actual().replacements, FixReplacementInfoSubject::assertThat) isNotNull();
.named("replacements"); return check("replacements()")
.about(elements())
.thatCustom(actual().replacements, fixReplacements());
} }
public FixReplacementInfoSubject onlyReplacement() { public FixReplacementInfoSubject onlyReplacement() {
@@ -49,6 +57,7 @@ public class FixSuggestionInfoSubject extends Subject<FixSuggestionInfoSubject,
} }
public StringSubject description() { public StringSubject description() {
return Truth.assertThat(actual().description).named("description"); isNotNull();
return check("description()").that(actual().description);
} }
} }

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import com.google.common.truth.ComparableSubject; import com.google.common.truth.ComparableSubject;
@@ -21,7 +22,6 @@ import com.google.common.truth.FailureMetadata;
import com.google.common.truth.IntegerSubject; import com.google.common.truth.IntegerSubject;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.common.GitPerson; import com.google.gerrit.extensions.common.GitPerson;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Date; import java.util.Date;
@@ -30,7 +30,11 @@ import org.eclipse.jgit.lib.PersonIdent;
public class GitPersonSubject extends Subject<GitPersonSubject, GitPerson> { public class GitPersonSubject extends Subject<GitPersonSubject, GitPerson> {
public static GitPersonSubject assertThat(GitPerson gitPerson) { public static GitPersonSubject assertThat(GitPerson gitPerson) {
return assertAbout(GitPersonSubject::new).that(gitPerson); return assertAbout(gitPersons()).that(gitPerson);
}
public static Factory<GitPersonSubject, GitPerson> gitPersons() {
return GitPersonSubject::new;
} }
private GitPersonSubject(FailureMetadata failureMetadata, GitPerson gitPerson) { private GitPersonSubject(FailureMetadata failureMetadata, GitPerson gitPerson) {
@@ -40,30 +44,30 @@ public class GitPersonSubject extends Subject<GitPersonSubject, GitPerson> {
public StringSubject name() { public StringSubject name() {
isNotNull(); isNotNull();
GitPerson gitPerson = actual(); GitPerson gitPerson = actual();
return Truth.assertThat(gitPerson.name).named("name"); return check("name()").that(gitPerson.name);
} }
public StringSubject email() { public StringSubject email() {
isNotNull(); isNotNull();
GitPerson gitPerson = actual(); GitPerson gitPerson = actual();
return Truth.assertThat(gitPerson.email).named("email"); return check("email()").that(gitPerson.email);
} }
public ComparableSubject<?, Timestamp> date() { public ComparableSubject<?, Timestamp> date() {
isNotNull(); isNotNull();
GitPerson gitPerson = actual(); GitPerson gitPerson = actual();
return Truth.assertThat(gitPerson.date).named("date"); return check("date()").that(gitPerson.date);
} }
public IntegerSubject tz() { public IntegerSubject tz() {
isNotNull(); isNotNull();
GitPerson gitPerson = actual(); GitPerson gitPerson = actual();
return Truth.assertThat(gitPerson.tz).named("tz"); return check("tz()").that(gitPerson.tz);
} }
public void hasSameDateAs(GitPerson other) { public void hasSameDateAs(GitPerson other) {
checkNotNull(other, "'other' GitPerson must not be null");
isNotNull(); isNotNull();
assertThat(other).named("other").isNotNull();
date().isEqualTo(other.date); date().isEqualTo(other.date);
tz().isEqualTo(other.tz); tz().isEqualTo(other.tz);
} }
@@ -72,9 +76,7 @@ public class GitPersonSubject extends Subject<GitPersonSubject, GitPerson> {
isNotNull(); isNotNull();
name().isEqualTo(ident.getName()); name().isEqualTo(ident.getName());
email().isEqualTo(ident.getEmailAddress()); email().isEqualTo(ident.getEmailAddress());
Truth.assertThat(new Date(actual().date.getTime())) check("roundedDate()").that(new Date(actual().date.getTime())).isEqualTo(ident.getWhen());
.named("rounded date")
.isEqualTo(ident.getWhen());
tz().isEqualTo(ident.getTimeZoneOffset()); tz().isEqualTo(ident.getTimeZoneOffset());
} }
} }

View File

@@ -14,19 +14,22 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.truth.Fact.fact; import static com.google.common.truth.Fact.simpleFact;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.IntegerSubject; import com.google.common.truth.IntegerSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.client.Comment; import com.google.gerrit.extensions.client.Comment;
public class RangeSubject extends Subject<RangeSubject, Comment.Range> { public class RangeSubject extends Subject<RangeSubject, Comment.Range> {
public static RangeSubject assertThat(Comment.Range range) { public static RangeSubject assertThat(Comment.Range range) {
return assertAbout(RangeSubject::new).that(range); return assertAbout(ranges()).that(range);
}
public static Subject.Factory<RangeSubject, Comment.Range> ranges() {
return RangeSubject::new;
} }
private RangeSubject(FailureMetadata failureMetadata, Comment.Range range) { private RangeSubject(FailureMetadata failureMetadata, Comment.Range range) {
@@ -34,32 +37,32 @@ public class RangeSubject extends Subject<RangeSubject, Comment.Range> {
} }
public IntegerSubject startLine() { public IntegerSubject startLine() {
return Truth.assertThat(actual().startLine).named("startLine"); return check("startLine()").that(actual().startLine);
} }
public IntegerSubject startCharacter() { public IntegerSubject startCharacter() {
return Truth.assertThat(actual().startCharacter).named("startCharacter"); return check("startCharacter()").that(actual().startCharacter);
} }
public IntegerSubject endLine() { public IntegerSubject endLine() {
return Truth.assertThat(actual().endLine).named("endLine"); return check("endLine()").that(actual().endLine);
} }
public IntegerSubject endCharacter() { public IntegerSubject endCharacter() {
return Truth.assertThat(actual().endCharacter).named("endCharacter"); return check("endCharacter()").that(actual().endCharacter);
} }
public void isValid() { public void isValid() {
isNotNull(); isNotNull();
if (!actual().isValid()) { if (!actual().isValid()) {
failWithoutActual(fact("expected", "valid")); failWithActual(simpleFact("expected to be valid"));
} }
} }
public void isInvalid() { public void isInvalid() {
isNotNull(); isNotNull();
if (actual().isValid()) { if (actual().isValid()) {
failWithoutActual(fact("expected", "not valid")); failWithActual(simpleFact("expected to be invalid"));
} }
} }
} }

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.extensions.common.testing; package com.google.gerrit.extensions.common.testing;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static com.google.gerrit.truth.ListSubject.elements;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
@@ -27,12 +28,15 @@ public class RobotCommentInfoSubject extends Subject<RobotCommentInfoSubject, Ro
public static ListSubject<RobotCommentInfoSubject, RobotCommentInfo> assertThatList( public static ListSubject<RobotCommentInfoSubject, RobotCommentInfo> assertThatList(
List<RobotCommentInfo> robotCommentInfos) { List<RobotCommentInfo> robotCommentInfos) {
return ListSubject.assertThat(robotCommentInfos, RobotCommentInfoSubject::assertThat) return ListSubject.assertThat(robotCommentInfos, robotComments()).named("robotCommentInfos");
.named("robotCommentInfos");
} }
public static RobotCommentInfoSubject assertThat(RobotCommentInfo robotCommentInfo) { public static RobotCommentInfoSubject assertThat(RobotCommentInfo robotCommentInfo) {
return assertAbout(RobotCommentInfoSubject::new).that(robotCommentInfo); return assertAbout(robotComments()).that(robotCommentInfo);
}
private static Factory<RobotCommentInfoSubject, RobotCommentInfo> robotComments() {
return RobotCommentInfoSubject::new;
} }
private RobotCommentInfoSubject( private RobotCommentInfoSubject(
@@ -41,8 +45,9 @@ public class RobotCommentInfoSubject extends Subject<RobotCommentInfoSubject, Ro
} }
public ListSubject<FixSuggestionInfoSubject, FixSuggestionInfo> fixSuggestions() { public ListSubject<FixSuggestionInfoSubject, FixSuggestionInfo> fixSuggestions() {
return ListSubject.assertThat(actual().fixSuggestions, FixSuggestionInfoSubject::assertThat) return check("fixSuggestions()")
.named("fixSuggestions"); .about(elements())
.thatCustom(actual().fixSuggestions, FixSuggestionInfoSubject.fixSuggestions());
} }
public FixSuggestionInfoSubject onlyFixSuggestion() { public FixSuggestionInfoSubject onlyFixSuggestion() {

View File

@@ -20,7 +20,6 @@ import com.google.common.truth.FailureMetadata;
import com.google.common.truth.PrimitiveByteArraySubject; import com.google.common.truth.PrimitiveByteArraySubject;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.restapi.BinaryResult; import com.google.gerrit.extensions.restapi.BinaryResult;
import com.google.gerrit.truth.OptionalSubject; import com.google.gerrit.truth.OptionalSubject;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -30,12 +29,16 @@ import java.util.Optional;
public class BinaryResultSubject extends Subject<BinaryResultSubject, BinaryResult> { public class BinaryResultSubject extends Subject<BinaryResultSubject, BinaryResult> {
public static BinaryResultSubject assertThat(BinaryResult binaryResult) { public static BinaryResultSubject assertThat(BinaryResult binaryResult) {
return assertAbout(BinaryResultSubject::new).that(binaryResult); return assertAbout(binaryResults()).that(binaryResult);
}
private static Subject.Factory<BinaryResultSubject, BinaryResult> binaryResults() {
return BinaryResultSubject::new;
} }
public static OptionalSubject<BinaryResultSubject, BinaryResult> assertThat( public static OptionalSubject<BinaryResultSubject, BinaryResult> assertThat(
Optional<BinaryResult> binaryResultOptional) { Optional<BinaryResult> binaryResultOptional) {
return OptionalSubject.assertThat(binaryResultOptional, BinaryResultSubject::assertThat); return OptionalSubject.assertThat(binaryResultOptional, binaryResults());
} }
private BinaryResultSubject(FailureMetadata failureMetadata, BinaryResult binaryResult) { private BinaryResultSubject(FailureMetadata failureMetadata, BinaryResult binaryResult) {
@@ -48,7 +51,7 @@ public class BinaryResultSubject extends Subject<BinaryResultSubject, BinaryResu
// be used afterwards. Besides, closing it doesn't have an effect for most // be used afterwards. Besides, closing it doesn't have an effect for most
// implementations of a BinaryResult. // implementations of a BinaryResult.
BinaryResult binaryResult = actual(); BinaryResult binaryResult = actual();
return Truth.assertThat(binaryResult.asString()); return check("asString()").that(binaryResult.asString());
} }
public PrimitiveByteArraySubject bytes() throws IOException { public PrimitiveByteArraySubject bytes() throws IOException {
@@ -60,6 +63,6 @@ public class BinaryResultSubject extends Subject<BinaryResultSubject, BinaryResu
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
binaryResult.writeTo(byteArrayOutputStream); binaryResult.writeTo(byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray(); byte[] bytes = byteArrayOutputStream.toByteArray();
return Truth.assertThat(bytes); return check("bytes()").that(bytes);
} }
} }

View File

@@ -19,7 +19,6 @@ import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import java.sql.Timestamp; import java.sql.Timestamp;
import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevCommit;
@@ -69,9 +68,7 @@ public class CommitSubject extends Subject<CommitSubject, RevCommit> {
public void hasCommitMessage(String expectedCommitMessage) { public void hasCommitMessage(String expectedCommitMessage) {
isNotNull(); isNotNull();
RevCommit commit = actual(); RevCommit commit = actual();
Truth.assertThat(commit.getFullMessage()) check("commitMessage()").that(commit.getFullMessage()).isEqualTo(expectedCommitMessage);
.named("commit message")
.isEqualTo(expectedCommitMessage);
} }
/** /**
@@ -84,7 +81,7 @@ public class CommitSubject extends Subject<CommitSubject, RevCommit> {
RevCommit commit = actual(); RevCommit commit = actual();
long timestampDiffMs = long timestampDiffMs =
Math.abs(commit.getCommitTime() * 1000L - expectedCommitTimestamp.getTime()); Math.abs(commit.getCommitTime() * 1000L - expectedCommitTimestamp.getTime());
Truth.assertThat(timestampDiffMs).named("commit timestamp diff").isAtMost(SECONDS.toMillis(1)); check("commitTimestampDiff()").that(timestampDiffMs).isAtMost(SECONDS.toMillis(1));
} }
/** /**
@@ -95,6 +92,6 @@ public class CommitSubject extends Subject<CommitSubject, RevCommit> {
public void hasSha1(ObjectId expectedSha1) { public void hasSha1(ObjectId expectedSha1) {
isNotNull(); isNotNull();
RevCommit commit = actual(); RevCommit commit = actual();
Truth.assertThat(commit).named("SHA1").isEqualTo(expectedSha1); check("sha1()").that(commit).isEqualTo(expectedSha1);
} }
} }

View File

@@ -18,12 +18,15 @@ import static com.google.common.truth.Truth.assertAbout;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectId;
public class ObjectIdSubject extends Subject<ObjectIdSubject, ObjectId> { public class ObjectIdSubject extends Subject<ObjectIdSubject, ObjectId> {
public static ObjectIdSubject assertThat(ObjectId objectId) { public static ObjectIdSubject assertThat(ObjectId objectId) {
return assertAbout(ObjectIdSubject::new).that(objectId); return assertAbout(objectIds()).that(objectId);
}
public static Factory<ObjectIdSubject, ObjectId> objectIds() {
return ObjectIdSubject::new;
} }
private ObjectIdSubject(FailureMetadata metadata, ObjectId actual) { private ObjectIdSubject(FailureMetadata metadata, ObjectId actual) {
@@ -33,6 +36,6 @@ public class ObjectIdSubject extends Subject<ObjectIdSubject, ObjectId> {
public void hasName(String expectedName) { public void hasName(String expectedName) {
isNotNull(); isNotNull();
ObjectId objectId = actual(); ObjectId objectId = actual();
Truth.assertThat(objectId.getName()).named("name").isEqualTo(expectedName); check("name()").that(objectId.getName()).isEqualTo(expectedName);
} }
} }

View File

@@ -16,7 +16,6 @@ package com.google.gerrit.git.testing;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static java.util.stream.Collectors.joining;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
@@ -25,11 +24,10 @@ import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StreamSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth; import com.google.common.truth.Truth;
import com.google.common.truth.Truth8;
import com.google.gerrit.common.Nullable; import com.google.gerrit.common.Nullable;
import java.util.Arrays;
import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.RemoteRefUpdate;
@@ -43,7 +41,8 @@ public class PushResultSubject extends Subject<PushResultSubject, PushResult> {
} }
public void hasNoMessages() { public void hasNoMessages() {
Truth.assertWithMessage("expected no messages") check()
.withMessage("expected no messages")
.that(Strings.nullToEmpty(trimMessages())) .that(Strings.nullToEmpty(trimMessages()))
.isEqualTo(""); .isEqualTo("");
} }
@@ -51,14 +50,14 @@ public class PushResultSubject extends Subject<PushResultSubject, PushResult> {
public void hasMessages(String... expectedLines) { public void hasMessages(String... expectedLines) {
checkArgument(expectedLines.length > 0, "use hasNoMessages()"); checkArgument(expectedLines.length > 0, "use hasNoMessages()");
isNotNull(); isNotNull();
Truth.assertThat(trimMessages()).isEqualTo(Arrays.stream(expectedLines).collect(joining("\n"))); check("messages()").that(trimMessages()).isEqualTo(String.join("\n", expectedLines));
} }
public void containsMessages(String... expectedLines) { public void containsMessages(String... expectedLines) {
checkArgument(expectedLines.length > 0, "use hasNoMessages()"); checkArgument(expectedLines.length > 0, "use hasNoMessages()");
isNotNull(); isNotNull();
Iterable<String> got = Splitter.on("\n").split(trimMessages()); Iterable<String> got = Splitter.on("\n").split(trimMessages());
Truth.assertThat(got).containsAllIn(expectedLines).inOrder(); check("messages()").that(got).containsAllIn(expectedLines).inOrder();
} }
private String trimMessages() { private String trimMessages() {
@@ -90,10 +89,7 @@ public class PushResultSubject extends Subject<PushResultSubject, PushResult> {
messages, Throwables.getStackTraceAsString(e)); messages, Throwables.getStackTraceAsString(e));
return; return;
} }
Truth.assertThat(actual) check("processedCommands()").that(actual).containsExactlyEntriesIn(expected).inOrder();
.named("processed commands")
.containsExactlyEntriesIn(expected)
.inOrder();
} }
@VisibleForTesting @VisibleForTesting
@@ -129,7 +125,9 @@ public class PushResultSubject extends Subject<PushResultSubject, PushResult> {
} }
public RemoteRefUpdateSubject onlyRef(String refName) { public RemoteRefUpdateSubject onlyRef(String refName) {
Truth8.assertThat(actual().getRemoteUpdates().stream().map(RemoteRefUpdate::getRemoteName)) check("setOfRefs()")
.about(StreamSubject.streams())
.that(actual().getRemoteUpdates().stream().map(RemoteRefUpdate::getRemoteName))
.named("set of refs") .named("set of refs")
.containsExactly(refName); .containsExactly(refName);
return ref(refName); return ref(refName);

View File

@@ -15,9 +15,8 @@
package com.google.gerrit.proto.testing; package com.google.gerrit.proto.testing;
import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.truth.Fact.simpleFact;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
@@ -67,21 +66,22 @@ public class SerializedClassSubject extends Subject<SerializedClassSubject, Clas
public void isAbstract() { public void isAbstract() {
isNotNull(); isNotNull();
assertWithMessage("expected class %s to be abstract", actual().getName()) if (!Modifier.isAbstract(actual().getModifiers())) {
.that(Modifier.isAbstract(actual().getModifiers())) failWithActual(simpleFact("expected class to be abstract"));
.isTrue(); }
} }
public void isConcrete() { public void isConcrete() {
isNotNull(); isNotNull();
assertWithMessage("expected class %s to be concrete", actual().getName()) if (Modifier.isAbstract(actual().getModifiers())) {
.that(!Modifier.isAbstract(actual().getModifiers())) failWithActual(simpleFact("expected class to be concrete"));
.isTrue(); }
} }
public void hasFields(Map<String, Type> expectedFields) { public void hasFields(Map<String, Type> expectedFields) {
isConcrete(); isConcrete();
assertThat( check("fields()")
.that(
FieldUtils.getAllFieldsList(actual()).stream() FieldUtils.getAllFieldsList(actual()).stream()
.filter(f -> !Modifier.isStatic(f.getModifiers())) .filter(f -> !Modifier.isStatic(f.getModifiers()))
.collect(toImmutableMap(Field::getName, Field::getGenericType))) .collect(toImmutableMap(Field::getName, Field::getGenericType)))
@@ -91,20 +91,20 @@ public class SerializedClassSubject extends Subject<SerializedClassSubject, Clas
public void hasAutoValueMethods(Map<String, Type> expectedMethods) { public void hasAutoValueMethods(Map<String, Type> expectedMethods) {
// Would be nice if we could check clazz is an @AutoValue, but the retention is not RUNTIME. // Would be nice if we could check clazz is an @AutoValue, but the retention is not RUNTIME.
isAbstract(); isAbstract();
assertThat( check("noArgumentAbstractMethodsOn(%s)", actual().getName())
.that(
Arrays.stream(actual().getDeclaredMethods()) Arrays.stream(actual().getDeclaredMethods())
.filter(m -> !Modifier.isStatic(m.getModifiers())) .filter(m -> !Modifier.isStatic(m.getModifiers()))
.filter(m -> Modifier.isAbstract(m.getModifiers())) .filter(m -> Modifier.isAbstract(m.getModifiers()))
.filter(m -> m.getParameters().length == 0) .filter(m -> m.getParameters().length == 0)
.collect(toImmutableMap(Method::getName, Method::getGenericReturnType))) .collect(toImmutableMap(Method::getName, Method::getGenericReturnType)))
.named("no-argument abstract methods on %s", actual().getName())
.isEqualTo(expectedMethods); .isEqualTo(expectedMethods);
} }
public void extendsClass(Type superclassType) { public void extendsClass(Type superclassType) {
isNotNull(); isNotNull();
assertThat(actual().getGenericSuperclass()) check("superclass(%s)", actual().getName())
.named("superclass of %s", actual().getName()) .that(actual().getGenericSuperclass())
.isEqualTo(superclassType); .isEqualTo(superclassType);
} }
} }

View File

@@ -23,7 +23,6 @@ import com.google.common.truth.FailureMetadata;
import com.google.common.truth.IterableSubject; import com.google.common.truth.IterableSubject;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.reviewdb.client.AccountGroup; import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.group.InternalGroup; import com.google.gerrit.server.group.InternalGroup;
import java.sql.Timestamp; import java.sql.Timestamp;
@@ -32,7 +31,11 @@ import org.eclipse.jgit.lib.ObjectId;
public class InternalGroupSubject extends Subject<InternalGroupSubject, InternalGroup> { public class InternalGroupSubject extends Subject<InternalGroupSubject, InternalGroup> {
public static InternalGroupSubject assertThat(InternalGroup group) { public static InternalGroupSubject assertThat(InternalGroup group) {
return assertAbout(InternalGroupSubject::new).that(group); return assertAbout(internalGroups()).that(group);
}
public static Subject.Factory<InternalGroupSubject, InternalGroup> internalGroups() {
return InternalGroupSubject::new;
} }
private InternalGroupSubject(FailureMetadata metadata, InternalGroup actual) { private InternalGroupSubject(FailureMetadata metadata, InternalGroup actual) {
@@ -42,66 +45,66 @@ public class InternalGroupSubject extends Subject<InternalGroupSubject, Internal
public ComparableSubject<?, AccountGroup.UUID> groupUuid() { public ComparableSubject<?, AccountGroup.UUID> groupUuid() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getGroupUUID()).named("groupUuid"); return check("groupUuid()").that(group.getGroupUUID());
} }
public ComparableSubject<?, AccountGroup.NameKey> nameKey() { public ComparableSubject<?, AccountGroup.NameKey> nameKey() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getNameKey()).named("nameKey"); return check("nameKey()").that(group.getNameKey());
} }
public StringSubject name() { public StringSubject name() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getName()).named("name"); return check("name()").that(group.getName());
} }
public DefaultSubject id() { public Subject<DefaultSubject, Object> id() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getId()).named("id"); return check("id()").that(group.getId());
} }
public StringSubject description() { public StringSubject description() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getDescription()).named("description"); return check("description()").that(group.getDescription());
} }
public ComparableSubject<?, AccountGroup.UUID> ownerGroupUuid() { public ComparableSubject<?, AccountGroup.UUID> ownerGroupUuid() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getOwnerGroupUUID()).named("ownerGroupUuid"); return check("ownerGroupUuid()").that(group.getOwnerGroupUUID());
} }
public BooleanSubject visibleToAll() { public BooleanSubject visibleToAll() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.isVisibleToAll()).named("visibleToAll"); return check("visibleToAll()").that(group.isVisibleToAll());
} }
public ComparableSubject<?, Timestamp> createdOn() { public ComparableSubject<?, Timestamp> createdOn() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getCreatedOn()).named("createdOn"); return check("createdOn()").that(group.getCreatedOn());
} }
public IterableSubject members() { public IterableSubject members() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getMembers()).named("members"); return check("members()").that(group.getMembers());
} }
public IterableSubject subgroups() { public IterableSubject subgroups() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getSubgroups()).named("subgroups"); return check("subgroups()").that(group.getSubgroups());
} }
public ComparableSubject<?, ObjectId> refState() { public ComparableSubject<?, ObjectId> refState() {
isNotNull(); isNotNull();
InternalGroup group = actual(); InternalGroup group = actual();
return Truth.assertThat(group.getRefState()).named("refState"); return check("refState()").that(group.getRefState());
} }
} }

View File

@@ -18,28 +18,34 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.truth.Fact.fact; import static com.google.common.truth.Fact.fact;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import com.google.common.collect.Iterables;
import com.google.common.truth.CustomSubjectBuilder;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.IterableSubject; import com.google.common.truth.IterableSubject;
import com.google.common.truth.StandardSubjectBuilder;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.BiFunction;
public class ListSubject<S extends Subject<S, E>, E> extends IterableSubject { public class ListSubject<S extends Subject<S, E>, E> extends IterableSubject {
private final Function<E, S> elementAssertThatFunction; private final BiFunction<StandardSubjectBuilder, E, S> elementSubjectCreator;
@SuppressWarnings("unchecked")
public static <S extends Subject<S, E>, E> ListSubject<S, E> assertThat( public static <S extends Subject<S, E>, E> ListSubject<S, E> assertThat(
List<E> list, Function<E, S> elementAssertThatFunction) { List<E> list, Subject.Factory<S, E> subjectFactory) {
// The ListSubjectFactory always returns ListSubjects. -> Casting is appropriate. return assertAbout(elements()).thatCustom(list, subjectFactory);
return (ListSubject<S, E>) }
assertAbout(new ListSubjectFactory<>(elementAssertThatFunction)).that(list);
public static CustomSubjectBuilder.Factory<ListSubjectBuilder> elements() {
return ListSubjectBuilder::new;
} }
private ListSubject( private ListSubject(
FailureMetadata failureMetadata, List<E> list, Function<E, S> elementAssertThatFunction) { FailureMetadata failureMetadata,
List<E> list,
BiFunction<StandardSubjectBuilder, E, S> elementSubjectCreator) {
super(failureMetadata, list); super(failureMetadata, list);
this.elementAssertThatFunction = elementAssertThatFunction; this.elementSubjectCreator = elementSubjectCreator;
} }
public S element(int index) { public S element(int index) {
@@ -49,20 +55,21 @@ public class ListSubject<S extends Subject<S, E>, E> extends IterableSubject {
if (index >= list.size()) { if (index >= list.size()) {
failWithoutActual(fact("expected to have element at index", index)); failWithoutActual(fact("expected to have element at index", index));
} }
return elementAssertThatFunction.apply(list.get(index)); return elementSubjectCreator.apply(check("element(%s)", index), list.get(index));
} }
public S onlyElement() { public S onlyElement() {
isNotNull(); isNotNull();
hasSize(1); hasSize(1);
return element(0); List<E> list = getActualList();
return elementSubjectCreator.apply(check("onlyElement()"), Iterables.getOnlyElement(list));
} }
public S lastElement() { public S lastElement() {
isNotNull(); isNotNull();
isNotEmpty(); isNotEmpty();
List<E> list = getActualList(); List<E> list = getActualList();
return element(list.size() - 1); return elementSubjectCreator.apply(check("lastElement()"), Iterables.getLast(list));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -78,20 +85,20 @@ public class ListSubject<S extends Subject<S, E>, E> extends IterableSubject {
return (ListSubject<S, E>) super.named(s, objects); return (ListSubject<S, E>) super.named(s, objects);
} }
private static class ListSubjectFactory<S extends Subject<S, T>, T> public static class ListSubjectBuilder extends CustomSubjectBuilder {
implements Subject.Factory<IterableSubject, Iterable<?>> {
private Function<T, S> elementAssertThatFunction; ListSubjectBuilder(FailureMetadata failureMetadata) {
super(failureMetadata);
ListSubjectFactory(Function<T, S> elementAssertThatFunction) {
this.elementAssertThatFunction = elementAssertThatFunction;
} }
@SuppressWarnings("unchecked") public <S extends Subject<S, E>, E> ListSubject<S, E> thatCustom(
@Override List<E> list, Subject.Factory<S, E> subjectFactory) {
public ListSubject<S, T> createSubject(FailureMetadata failureMetadata, Iterable<?> objects) { return that(list, (builder, element) -> builder.about(subjectFactory).that(element));
// The constructor of ListSubject only accepts lists. -> Casting is appropriate. }
return new ListSubject<>(failureMetadata, (List<T>) objects, elementAssertThatFunction);
public <S extends Subject<S, E>, E> ListSubject<S, E> that(
List<E> list, BiFunction<StandardSubjectBuilder, E, S> elementSubjectCreator) {
return new ListSubject<>(metadata(), list, elementSubjectCreator);
} }
} }
} }

View File

@@ -17,41 +17,52 @@ package com.google.gerrit.truth;
import static com.google.common.truth.Fact.fact; import static com.google.common.truth.Fact.fact;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import com.google.common.truth.CustomSubjectBuilder;
import com.google.common.truth.DefaultSubject; import com.google.common.truth.DefaultSubject;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StandardSubjectBuilder;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import java.util.Optional; import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
public class OptionalSubject<S extends Subject<S, ? super T>, T> public class OptionalSubject<S extends Subject<S, ? super T>, T>
extends Subject<OptionalSubject<S, T>, Optional<T>> { extends Subject<OptionalSubject<S, T>, Optional<T>> {
private final Function<? super T, ? extends S> valueAssertThatFunction; private final BiFunction<StandardSubjectBuilder, ? super T, ? extends S> valueSubjectCreator;
public static <S extends Subject<S, ? super T>, T> OptionalSubject<S, T> assertThat( // TODO(aliceks): Remove when all relevant usages are adapted to new check()/factory approach.
public static <S extends Subject<S, T>, T> OptionalSubject<S, T> assertThat(
Optional<T> optional, Function<? super T, ? extends S> elementAssertThatFunction) { Optional<T> optional, Function<? super T, ? extends S> elementAssertThatFunction) {
OptionalSubjectFactory<S, T> optionalSubjectFactory = Subject.Factory<S, T> valueSubjectFactory =
new OptionalSubjectFactory<>(elementAssertThatFunction); (metadata, value) -> elementAssertThatFunction.apply(value);
return assertAbout(optionalSubjectFactory).that(optional); return assertThat(optional, valueSubjectFactory);
}
public static <S extends Subject<S, T>, T> OptionalSubject<S, T> assertThat(
Optional<T> optional, Subject.Factory<S, T> valueSubjectFactory) {
return assertAbout(optionals()).thatCustom(optional, valueSubjectFactory);
} }
public static OptionalSubject<DefaultSubject, ?> assertThat(Optional<?> optional) { public static OptionalSubject<DefaultSubject, ?> assertThat(Optional<?> optional) {
// Unfortunately, we need to cast to DefaultSubject as Truth.assertThat() // Unfortunately, we need to cast to DefaultSubject as StandardSubjectBuilder#that
// only returns Subject<DefaultSubject, Object>. There shouldn't be a way // only returns Subject<DefaultSubject, Object>. There shouldn't be a way
// for that method not to return a DefaultSubject because the generic type // for that method not to return a DefaultSubject because the generic type
// definitions of a Subject are quite strict. // definitions of a Subject are quite strict.
Function<Object, DefaultSubject> valueAssertThatFunction = return assertAbout(optionals())
value -> (DefaultSubject) Truth.assertThat(value); .that(optional, (builder, value) -> (DefaultSubject) builder.that(value));
return assertThat(optional, valueAssertThatFunction); }
public static CustomSubjectBuilder.Factory<OptionalSubjectBuilder> optionals() {
return OptionalSubjectBuilder::new;
} }
private OptionalSubject( private OptionalSubject(
FailureMetadata failureMetadata, FailureMetadata failureMetadata,
Optional<T> optional, Optional<T> optional,
Function<? super T, ? extends S> valueAssertThatFunction) { BiFunction<StandardSubjectBuilder, ? super T, ? extends S> valueSubjectCreator) {
super(failureMetadata, optional); super(failureMetadata, optional);
this.valueAssertThatFunction = valueAssertThatFunction; this.valueSubjectCreator = valueSubjectCreator;
} }
public void isPresent() { public void isPresent() {
@@ -78,22 +89,28 @@ public class OptionalSubject<S extends Subject<S, ? super T>, T>
isNotNull(); isNotNull();
isPresent(); isPresent();
Optional<T> optional = actual(); Optional<T> optional = actual();
return valueAssertThatFunction.apply(optional.get()); return valueSubjectCreator.apply(check("value()"), optional.get());
} }
private static class OptionalSubjectFactory<S extends Subject<S, ? super T>, T> public static class OptionalSubjectBuilder extends CustomSubjectBuilder {
implements Subject.Factory<OptionalSubject<S, T>, Optional<T>> {
private Function<? super T, ? extends S> valueAssertThatFunction; OptionalSubjectBuilder(FailureMetadata failureMetadata) {
super(failureMetadata);
OptionalSubjectFactory(Function<? super T, ? extends S> valueAssertThatFunction) {
this.valueAssertThatFunction = valueAssertThatFunction;
} }
@Override public <S extends Subject<S, T>, T> OptionalSubject<S, T> thatCustom(
public OptionalSubject<S, T> createSubject( Optional<T> optional, Subject.Factory<S, T> valueSubjectFactory) {
FailureMetadata failureMetadata, Optional<T> optional) { return that(optional, (builder, value) -> builder.about(valueSubjectFactory).that(value));
return new OptionalSubject<>(failureMetadata, optional, valueAssertThatFunction); }
public OptionalSubject<DefaultSubject, ?> that(Optional<?> optional) {
return that(optional, (builder, value) -> (DefaultSubject) builder.that(value));
}
public <S extends Subject<S, ? super T>, T> OptionalSubject<S, T> that(
Optional<T> optional,
BiFunction<StandardSubjectBuilder, ? super T, ? extends S> valueSubjectCreator) {
return new OptionalSubject<>(metadata(), optional, valueSubjectCreator);
} }
} }
} }

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.acceptance.api.group; package com.google.gerrit.acceptance.api.group;
import static com.google.common.truth.Truth.assertWithMessage; import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.gerrit.server.group.testing.InternalGroupSubject.internalGroups;
import static com.google.gerrit.truth.ListSubject.assertThat; import static com.google.gerrit.truth.ListSubject.assertThat;
import static com.google.gerrit.truth.OptionalSubject.assertThat; import static com.google.gerrit.truth.OptionalSubject.assertThat;
@@ -163,11 +164,11 @@ public class GroupIndexerIT {
private static OptionalSubject<InternalGroupSubject, InternalGroup> assertThatGroup( private static OptionalSubject<InternalGroupSubject, InternalGroup> assertThatGroup(
Optional<InternalGroup> updatedGroup) { Optional<InternalGroup> updatedGroup) {
return assertThat(updatedGroup, InternalGroupSubject::assertThat); return assertThat(updatedGroup, internalGroups());
} }
private static ListSubject<InternalGroupSubject, InternalGroup> assertThatGroups( private static ListSubject<InternalGroupSubject, InternalGroup> assertThatGroups(
List<InternalGroup> parentGroups) { List<InternalGroup> parentGroups) {
return assertThat(parentGroups, InternalGroupSubject::assertThat); return assertThat(parentGroups, internalGroups());
} }
} }

View File

@@ -20,7 +20,6 @@ import com.google.common.io.CharStreams;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.StringSubject; import com.google.common.truth.StringSubject;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import com.google.gerrit.extensions.restapi.RawInput; import com.google.gerrit.extensions.restapi.RawInput;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@@ -41,16 +40,16 @@ public class ChangeFileContentModificationSubject
public StringSubject filePath() { public StringSubject filePath() {
isNotNull(); isNotNull();
return Truth.assertThat(actual().getFilePath()).named("filePath"); return check("filePath()").that(actual().getFilePath());
} }
public StringSubject newContent() throws IOException { public StringSubject newContent() throws IOException {
isNotNull(); isNotNull();
RawInput newContent = actual().getNewContent(); RawInput newContent = actual().getNewContent();
Truth.assertThat(newContent).named("newContent").isNotNull(); check("newContent()").that(newContent).isNotNull();
String contentString = String contentString =
CharStreams.toString( CharStreams.toString(
new InputStreamReader(newContent.getInputStream(), StandardCharsets.UTF_8)); new InputStreamReader(newContent.getInputStream(), StandardCharsets.UTF_8));
return Truth.assertThat(contentString).named("newContent"); return check("newContent()").that(contentString);
} }
} }

View File

@@ -24,12 +24,17 @@ import java.util.List;
public class TreeModificationSubject extends Subject<TreeModificationSubject, TreeModification> { public class TreeModificationSubject extends Subject<TreeModificationSubject, TreeModification> {
public static TreeModificationSubject assertThat(TreeModification treeModification) { public static TreeModificationSubject assertThat(TreeModification treeModification) {
return assertAbout(TreeModificationSubject::new).that(treeModification); return assertAbout(treeModifications()).that(treeModification);
}
private static Factory<TreeModificationSubject, TreeModification> treeModifications() {
return TreeModificationSubject::new;
} }
public static ListSubject<TreeModificationSubject, TreeModification> assertThatList( public static ListSubject<TreeModificationSubject, TreeModification> assertThatList(
List<TreeModification> treeModifications) { List<TreeModification> treeModifications) {
return ListSubject.assertThat(treeModifications, TreeModificationSubject::assertThat) return assertAbout(ListSubject.elements())
.thatCustom(treeModifications, treeModifications())
.named("treeModifications"); .named("treeModifications");
} }

View File

@@ -16,6 +16,7 @@ package com.google.gerrit.server.group.db;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage; import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.gerrit.server.group.testing.InternalGroupSubject.internalGroups;
import static com.google.gerrit.truth.OptionalSubject.assertThat; import static com.google.gerrit.truth.OptionalSubject.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.instanceOf;
@@ -1673,6 +1674,6 @@ public class GroupConfigTest extends GerritBaseTests {
private static OptionalSubject<InternalGroupSubject, InternalGroup> assertThatGroup( private static OptionalSubject<InternalGroupSubject, InternalGroup> assertThatGroup(
Optional<InternalGroup> loadedGroup) { Optional<InternalGroup> loadedGroup) {
return assertThat(loadedGroup, InternalGroupSubject::assertThat); return assertThat(loadedGroup, internalGroups());
} }
} }

View File

@@ -16,7 +16,9 @@ package com.google.gerrit.server.group.db;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_; import static com.google.common.truth.Truth.assert_;
import static com.google.gerrit.common.data.testing.GroupReferenceSubject.groupReferences;
import static com.google.gerrit.extensions.common.testing.CommitInfoSubject.assertThat; import static com.google.gerrit.extensions.common.testing.CommitInfoSubject.assertThat;
import static com.google.gerrit.extensions.common.testing.CommitInfoSubject.commits;
import static com.google.gerrit.reviewdb.client.RefNames.REFS_GROUPNAMES; import static com.google.gerrit.reviewdb.client.RefNames.REFS_GROUPNAMES;
import static com.google.gerrit.truth.OptionalSubject.assertThat; import static com.google.gerrit.truth.OptionalSubject.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
@@ -584,11 +586,11 @@ public class GroupNameNotesTest extends GerritBaseTests {
private static OptionalSubject<GroupReferenceSubject, GroupReference> assertThatGroup( private static OptionalSubject<GroupReferenceSubject, GroupReference> assertThatGroup(
Optional<GroupReference> group) { Optional<GroupReference> group) {
return assertThat(group, GroupReferenceSubject::assertThat); return assertThat(group, groupReferences());
} }
private static ListSubject<CommitInfoSubject, CommitInfo> assertThatCommits( private static ListSubject<CommitInfoSubject, CommitInfo> assertThatCommits(
List<CommitInfo> commits) { List<CommitInfo> commits) {
return ListSubject.assertThat(commits, CommitInfoSubject::assertThat); return ListSubject.assertThat(commits, commits());
} }
} }