├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── core ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── common │ │ └── truth │ │ ├── AbstractArraySubject.java │ │ ├── ActualValueInference.java │ │ ├── AssertionErrorWithFacts.java │ │ ├── BigDecimalSubject.java │ │ ├── BooleanSubject.java │ │ ├── ClassSubject.java │ │ ├── ComparableSubject.java │ │ ├── ComparisonFailureWithFacts.java │ │ ├── ComparisonFailures.java │ │ ├── Correspondence.java │ │ ├── CustomSubjectBuilder.java │ │ ├── DiffUtils.java │ │ ├── DoubleSubject.java │ │ ├── ErrorWithFacts.java │ │ ├── Expect.java │ │ ├── ExpectFailure.java │ │ ├── Fact.java │ │ ├── FailureMetadata.java │ │ ├── FailureStrategy.java │ │ ├── FloatSubject.java │ │ ├── GraphMatching.java │ │ ├── GuavaOptionalSubject.java │ │ ├── IgnoreJRERequirement.java │ │ ├── IntStreamSubject.java │ │ ├── IntegerSubject.java │ │ ├── IterableSubject.java │ │ ├── J2ktIncompatible.java │ │ ├── LazyMessage.java │ │ ├── LongStreamSubject.java │ │ ├── LongSubject.java │ │ ├── MapSubject.java │ │ ├── MathUtil.java │ │ ├── MultimapSubject.java │ │ ├── MultisetSubject.java │ │ ├── NullnessCasts.java │ │ ├── ObjectArraySubject.java │ │ ├── OptionalDoubleSubject.java │ │ ├── OptionalIntSubject.java │ │ ├── OptionalLongSubject.java │ │ ├── OptionalSubject.java │ │ ├── Ordered.java │ │ ├── PathSubject.java │ │ ├── Platform.java │ │ ├── PrimitiveBooleanArraySubject.java │ │ ├── PrimitiveByteArraySubject.java │ │ ├── PrimitiveCharArraySubject.java │ │ ├── PrimitiveDoubleArraySubject.java │ │ ├── PrimitiveFloatArraySubject.java │ │ ├── PrimitiveIntArraySubject.java │ │ ├── PrimitiveLongArraySubject.java │ │ ├── PrimitiveShortArraySubject.java │ │ ├── SimpleSubjectBuilder.java │ │ ├── SneakyThrows.java │ │ ├── StackTraceCleaner.java │ │ ├── StandardSubjectBuilder.java │ │ ├── StreamSubject.java │ │ ├── StringSubject.java │ │ ├── Subject.java │ │ ├── SubjectUtils.java │ │ ├── TableSubject.java │ │ ├── ThrowableSubject.java │ │ ├── Truth.gwt.xml │ │ ├── Truth.java │ │ ├── Truth8.java │ │ ├── TruthFailureSubject.java │ │ ├── TruthJUnit.java │ │ ├── UsedByReflection.java │ │ ├── package-info.java │ │ └── super │ │ └── com │ │ └── google │ │ └── common │ │ └── truth │ │ └── Platform.java │ └── test │ └── java │ └── com │ └── google │ └── common │ └── truth │ ├── ActualValueInferenceTest.java │ ├── BigDecimalSubjectTest.java │ ├── BooleanSubjectTest.java │ ├── ChainingTest.java │ ├── ClassSubjectTest.java │ ├── ComparableSubjectTest.java │ ├── ComparisonFailureWithFactsTest.java │ ├── CorrespondenceExceptionStoreTest.java │ ├── CorrespondenceTest.java │ ├── CustomFailureMessageTest.java │ ├── DoubleSubjectTest.java │ ├── ExpectFailure8Test.java │ ├── ExpectFailureNonRuleTest.java │ ├── ExpectFailureRuleTest.java │ ├── ExpectFailureTest.java │ ├── ExpectFailureWithStackTraceTest.java │ ├── ExpectTest.java │ ├── ExpectWithStackTest.java │ ├── FactTest.java │ ├── FailureAssertions.java │ ├── FloatSubjectTest.java │ ├── GraphMatchingTest.java │ ├── GuavaOptionalSubjectTest.java │ ├── IntStreamSubjectTest.java │ ├── IntegerSubjectTest.java │ ├── IterableSubjectCorrespondenceTest.java │ ├── IterableSubjectTest.java │ ├── LongStreamSubjectTest.java │ ├── LongSubjectTest.java │ ├── MapSubjectTest.java │ ├── MathUtilTest.java │ ├── MultimapSubjectTest.java │ ├── MultisetSubjectTest.java │ ├── NoJUnitTest.java │ ├── NumericComparisonTest.java │ ├── ObjectArraySubjectTest.java │ ├── OptionalDoubleSubjectTest.java │ ├── OptionalIntSubjectTest.java │ ├── OptionalLongSubjectTest.java │ ├── OptionalSubjectTest.java │ ├── PathSubjectTest.java │ ├── PrimitiveBooleanArraySubjectTest.java │ ├── PrimitiveByteArraySubjectTest.java │ ├── PrimitiveCharArraySubjectTest.java │ ├── PrimitiveDoubleArraySubjectTest.java │ ├── PrimitiveFloatArraySubjectTest.java │ ├── PrimitiveIntArraySubjectTest.java │ ├── PrimitiveLongArraySubjectTest.java │ ├── PrimitiveShortArraySubjectTest.java │ ├── StackTraceCleanerJUnit3Test.java │ ├── StackTraceCleanerTest.java │ ├── StandardSubjectBuilderTest.java │ ├── StreamSubjectTest.java │ ├── StringSubjectTest.java │ ├── SubjectTest.java │ ├── TableSubjectTest.java │ ├── TestCorrespondences.java │ ├── TestPlatform.java │ ├── ThrowableSubjectTest.java │ ├── TruthAssertThatTest.java │ ├── TruthFailureSubjectTest.java │ ├── extension │ ├── Employee.java │ ├── EmployeeSubject.java │ ├── EmployeeSubjectTest.java │ ├── FakeHrDatabase.java │ ├── FakeHrDatabaseTest.java │ └── HrDatabase.java │ ├── gwt │ ├── Inventory.java │ ├── TruthGwtTest.java │ └── TruthTest.gwt.xml │ ├── no_junit_test.sh │ └── super │ └── com │ └── google │ └── common │ └── truth │ └── TestPlatform.java ├── extensions ├── java8 │ └── pom.xml ├── liteproto │ ├── pom.xml │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── google │ │ │ └── common │ │ │ └── truth │ │ │ └── extensions │ │ │ └── proto │ │ │ ├── LiteProtoSubject.java │ │ │ └── LiteProtoTruth.java │ │ └── test │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── common │ │ │ └── truth │ │ │ └── extensions │ │ │ └── proto │ │ │ └── LiteProtoSubjectTest.java │ │ └── proto │ │ ├── test_message_lite2.proto │ │ └── test_message_lite3.proto ├── pom.xml ├── proto │ ├── pom.xml │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── google │ │ │ └── common │ │ │ └── truth │ │ │ └── extensions │ │ │ └── proto │ │ │ ├── AnyUtils.java │ │ │ ├── DiffResult.java │ │ │ ├── FieldDescriptorValidator.java │ │ │ ├── FieldNumberTree.java │ │ │ ├── FieldScope.java │ │ │ ├── FieldScopeImpl.java │ │ │ ├── FieldScopeLogic.java │ │ │ ├── FieldScopeLogicContainer.java │ │ │ ├── FieldScopeLogicMap.java │ │ │ ├── FieldScopeResult.java │ │ │ ├── FieldScopeUtil.java │ │ │ ├── FieldScopes.java │ │ │ ├── FluentEqualityConfig.java │ │ │ ├── IterableOfProtosFluentAssertion.java │ │ │ ├── IterableOfProtosSubject.java │ │ │ ├── IterableOfProtosUsingCorrespondence.java │ │ │ ├── MapWithProtoValuesFluentAssertion.java │ │ │ ├── MapWithProtoValuesSubject.java │ │ │ ├── MultimapWithProtoValuesFluentAssertion.java │ │ │ ├── MultimapWithProtoValuesSubject.java │ │ │ ├── ProtoFluentAssertion.java │ │ │ ├── ProtoSubject.java │ │ │ ├── ProtoSubjectBuilder.java │ │ │ ├── ProtoTruth.java │ │ │ ├── ProtoTruthMessageDifferencer.java │ │ │ ├── RecursableDiffEntity.java │ │ │ ├── SubScopeId.java │ │ │ ├── UnknownFieldDescriptor.java │ │ │ └── package-info.java │ │ └── test │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── common │ │ │ └── truth │ │ │ └── extensions │ │ │ └── proto │ │ │ ├── FieldScopesTest.java │ │ │ ├── IterableOfProtosSubjectTest.java │ │ │ ├── MapWithProtoValuesSubjectTest.java │ │ │ ├── MultiExpectFailure.java │ │ │ ├── MultimapWithProtoValuesSubjectTest.java │ │ │ ├── OverloadResolutionTest.java │ │ │ ├── ProtoSubjectTest.java │ │ │ └── ProtoSubjectTestBase.java │ │ └── proto │ │ ├── test_message2.proto │ │ └── test_message3.proto └── re2j │ ├── pom.xml │ └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── common │ │ └── truth │ │ └── extensions │ │ └── re2j │ │ └── Re2jSubjects.java │ └── test │ └── java │ └── com │ └── google │ └── common │ └── truth │ └── extensions │ └── re2j │ └── Re2jSubjectsTest.java ├── javadoc-link └── j2objc-annotations │ └── package-list ├── overview.html ├── pom.xml ├── refactorings └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── common │ │ └── truth │ │ └── refactorings │ │ ├── CorrespondenceSubclassToFactoryCall.java │ │ └── FailWithFacts.java │ └── test │ └── java │ └── com │ └── google │ └── common │ └── truth │ └── refactorings │ ├── CorrespondenceSubclassToFactoryCallTest.java │ ├── FailWithFactsTest.java │ ├── NamedToWithMessageTest.java │ └── StoreActualValueInFieldTest.java └── util └── generate-latest-docs.sh /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "maven" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | groups: 8 | dependencies: 9 | applies-to: version-updates 10 | patterns: 11 | - "*" 12 | ignore: 13 | - dependency-name: "com.google.guava:guava" 14 | - dependency-name: "com.google.guava:guava-testlib" 15 | - dependency-name: "com.google.guava:guava-gwt" 16 | - package-ecosystem: "github-actions" 17 | directory: "/" 18 | schedule: 19 | interval: "monthly" 20 | groups: 21 | github-actions: 22 | applies-to: version-updates 23 | patterns: 24 | - "*" 25 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | test: 13 | name: "JDK ${{ matrix.java }}" 14 | strategy: 15 | matrix: 16 | java: [ 8, 11 ] 17 | runs-on: ubuntu-latest 18 | steps: 19 | # Cancel any previous runs for the same branch that are still running. 20 | - name: 'Cancel previous runs' 21 | uses: styfle/cancel-workflow-action@85880fa0301c86cca9da44039ee3bb12d3bedbfa 22 | with: 23 | access_token: ${{ github.token }} 24 | - name: 'Check out repository' 25 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 26 | - name: 'Set up JDK ${{ matrix.java }}' 27 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 28 | with: 29 | java-version: ${{ matrix.java }} 30 | distribution: 'zulu' 31 | cache: 'maven' 32 | - name: 'Install' 33 | shell: bash 34 | run: mvn -B -P!standard-with-extra-repos install -U -DskipTests=true 35 | - name: 'Test' 36 | shell: bash 37 | run: mvn -B -P!standard-with-extra-repos verify -U -Dmaven.javadoc.skip=true 38 | - name: 'Javadoc Test Run' 39 | shell: bash 40 | run: mvn -B -P!standard-with-extra-repos javadoc:aggregate -U 41 | 42 | publish_snapshot: 43 | name: 'Publish snapshot' 44 | needs: test 45 | if: github.event_name == 'push' && github.repository == 'google/truth' 46 | runs-on: ubuntu-latest 47 | steps: 48 | - name: 'Check out repository' 49 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 50 | - name: 'Set up JDK 11' 51 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 52 | with: 53 | java-version: 11 54 | distribution: 'zulu' 55 | cache: 'maven' 56 | server-id: sonatype-nexus-snapshots 57 | server-username: CI_DEPLOY_USERNAME 58 | server-password: CI_DEPLOY_PASSWORD 59 | - name: 'Publish' 60 | env: 61 | CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} 62 | CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} 63 | run: mvn -B clean source:jar javadoc:jar deploy -DskipTests=true 64 | 65 | generate_docs: 66 | name: 'Generate latest docs' 67 | needs: test 68 | if: github.event_name == 'push' && github.repository == 'google/truth' 69 | runs-on: ubuntu-latest 70 | steps: 71 | - name: 'Check out repository' 72 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 73 | - name: 'Set up JDK 11' 74 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 75 | with: 76 | java-version: 11 77 | distribution: 'zulu' 78 | cache: 'maven' 79 | - name: 'Generate latest docs' 80 | env: 81 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 82 | run: ./util/generate-latest-docs.sh 83 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | target 3 | .project 4 | .classpath 5 | .settings 6 | .clover 7 | .* 8 | *.iml 9 | *.ipr 10 | *.iws 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are a 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to any Google project must be accompanied by a Contributor License 9 | Agreement. This is not a copyright **assignment**, it simply gives Google 10 | permission to use and redistribute your contributions as part of the project. 11 | 12 | When submitting a pull request, if you have not already signed the 13 | [Contributor License Agreement (CLA)][CLA], then a bot will remind you. 14 | Code cannot even be evaluated without this step. 15 | 16 | ## Submitting a patch 17 | 18 | 1. It's generally best to start by opening a new issue describing the bug or 19 | feature you're intending to fix. Even if you think it's relatively minor, 20 | it's helpful to know what people are working on. Mention in the initial 21 | issue that you are planning to work on that bug or feature so that it can be 22 | assigned to you. 23 | 24 | 2. Follow the normal process of [forking] the project, and setup a new branch 25 | to work in. It's important that each group of changes be done in separate 26 | branches in order to ensure that a pull request only includes the commits 27 | related to that bug or feature. 28 | 29 | 3. Any significant changes should almost always be accompanied by tests. The 30 | project already has good test coverage, so look at some of the existing 31 | tests if you're unsure how to go about it. 32 | 33 | 4. All contributions must be licensed Apache 2.0 and all files must have a copy 34 | of the boilerplate licence comment (can be copied from an existing file). 35 | Files should be formatted according to Google's [java style guide]. 36 | 37 | 5. Do your best to have [well-formed commit messages] for each change. This 38 | provides consistency throughout the project, and ensures that commit 39 | messages are able to be formatted properly by various git tools. 40 | 41 | 6. Finally, push the commits to your fork and submit a [pull request]. 42 | 43 | [CLA]: https://cla.developers.google.com 44 | [forking]: https://help.github.com/articles/fork-a-repo 45 | [java style guide]: https://google.github.io/styleguide/javaguide.html 46 | [well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html 47 | [pull request]: https://help.github.com/articles/creating-a-pull-request 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Main Site][gh-pages-shield]][gh-pages-link] 2 | [![Build Status][ci-shield]][ci-link] 3 | [![Maven Release][maven-shield]][maven-link] 4 | [![Stackoverflow][stackoverflow-shield]][stackoverflow-link] 5 | 6 | ## What is Truth? 7 | 8 | Truth makes your [test assertions] and [failure messages] more readable. 9 | [Similar][comparison] to [AssertJ], it [natively supports][known_types] many JDK 10 | and [Guava] types, and it is [extensible][extension] to others. 11 | 12 | Truth is owned and maintained by the [Guava] team. It is used in the majority 13 | of the tests in Google’s own codebase. 14 | 15 | Read more at [the main website](https://truth.dev). 16 | 17 | 18 | 19 | [test assertions]: https://truth.dev/benefits#readable-assertions 20 | [failure messages]: https://truth.dev/benefits#readable-messages 21 | [comparison]: https://truth.dev/comparison 22 | [AssertJ]: http://joel-costigliola.github.io/assertj/ 23 | [known_types]: https://truth.dev/known_types 24 | [extension]: https://truth.dev/extension 25 | [Guava]: https://github.com/google/guava 26 | [gh-pages-shield]: https://img.shields.io/badge/main%20site-truth.dev-ff55ff.png?style=flat 27 | [gh-pages-link]: https://truth.dev 28 | [ci-shield]: https://github.com/google/truth/workflows/CI/badge.svg?branch=master 29 | [ci-link]: https://github.com/google/truth/actions 30 | [maven-shield]: https://img.shields.io/maven-central/v/com.google.truth/truth.png 31 | [maven-link]: https://search.maven.org/artifact/com.google.truth/truth 32 | [stackoverflow-shield]: https://img.shields.io/badge/stackoverflow-google‐truth-5555ff.png?style=flat 33 | [stackoverflow-link]: https://stackoverflow.com/questions/tagged/google-truth 34 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/AbstractArraySubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkArgument; 19 | import static com.google.common.base.Preconditions.checkNotNull; 20 | import static com.google.common.truth.Fact.simpleFact; 21 | 22 | import java.lang.reflect.Array; 23 | import org.jspecify.annotations.Nullable; 24 | 25 | /** 26 | * A common supertype for Array subjects, abstracting some common display and error infrastructure. 27 | * 28 | * @author Christian Gruber (cgruber@israfil.net) 29 | */ 30 | abstract class AbstractArraySubject extends Subject { 31 | private final @Nullable Object actual; 32 | 33 | AbstractArraySubject( 34 | FailureMetadata metadata, @Nullable Object actual, @Nullable String typeDescriptionOverride) { 35 | super(metadata, actual, typeDescriptionOverride); 36 | this.actual = actual; 37 | } 38 | 39 | /** Fails if the array is not empty (i.e. {@code array.length > 0}). */ 40 | public final void isEmpty() { 41 | if (length() > 0) { 42 | failWithActual(simpleFact("expected to be empty")); 43 | } 44 | } 45 | 46 | /** Fails if the array is empty (i.e. {@code array.length == 0}). */ 47 | public final void isNotEmpty() { 48 | if (length() == 0) { 49 | failWithoutActual(simpleFact("expected not to be empty")); 50 | } 51 | } 52 | 53 | /** 54 | * Fails if the array does not have the given length. 55 | * 56 | * @throws IllegalArgumentException if {@code length < 0} 57 | */ 58 | public final void hasLength(int length) { 59 | checkArgument(length >= 0, "length (%s) must be >= 0", length); 60 | check("length").that(length()).isEqualTo(length); 61 | } 62 | 63 | private int length() { 64 | return Array.getLength(checkNotNull(actual)); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | import static com.google.common.truth.Fact.makeMessage; 20 | 21 | import com.google.common.collect.ImmutableList; 22 | import org.jspecify.annotations.Nullable; 23 | 24 | /** 25 | * An {@link AssertionError} composed of structured {@link Fact} instances and other string 26 | * messages. 27 | */ 28 | @SuppressWarnings("OverrideThrowableToString") // We intentionally hide the class name. 29 | final class AssertionErrorWithFacts extends AssertionError implements ErrorWithFacts { 30 | private final ImmutableList facts; 31 | 32 | private AssertionErrorWithFacts( 33 | ImmutableList messages, ImmutableList facts, @Nullable Throwable cause) { 34 | super(makeMessage(messages, facts), cause); 35 | this.facts = checkNotNull(facts); 36 | } 37 | 38 | static AssertionErrorWithFacts create( 39 | ImmutableList messages, ImmutableList facts, @Nullable Throwable cause) { 40 | return new AssertionErrorWithFacts(messages, facts, cause); 41 | } 42 | 43 | static AssertionError createWithoutFacts(String message, @Nullable Throwable cause) { 44 | return create(ImmutableList.of(message), ImmutableList.of(), cause); 45 | } 46 | 47 | static AssertionError createWithoutFactsOrStack(String message, @Nullable Throwable cause) { 48 | AssertionError error = createWithoutFacts(message, cause); 49 | error.setStackTrace(new StackTraceElement[0]); 50 | return error; 51 | } 52 | 53 | static AssertionError createWithoutFactsOrStack(String message) { 54 | return createWithoutFactsOrStack(message, /* cause= */ null); 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return checkNotNull(getLocalizedMessage()); 60 | } 61 | 62 | @Override 63 | public ImmutableList facts() { 64 | return facts; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/BooleanSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Fact.simpleFact; 19 | 20 | import org.jspecify.annotations.Nullable; 21 | 22 | /** 23 | * Propositions for boolean subjects. 24 | * 25 | * @author Christian Gruber (cgruber@israfil.net) 26 | */ 27 | public final class BooleanSubject extends Subject { 28 | private final @Nullable Boolean actual; 29 | 30 | private BooleanSubject(FailureMetadata metadata, @Nullable Boolean actual) { 31 | super(metadata, actual); 32 | this.actual = actual; 33 | } 34 | 35 | /** Fails if the subject is false or {@code null}. */ 36 | public void isTrue() { 37 | if (actual == null) { 38 | isEqualTo(true); // fails 39 | } else if (!actual) { 40 | failWithoutActual(simpleFact("expected to be true")); 41 | } 42 | } 43 | 44 | /** Fails if the subject is true or {@code null}. */ 45 | public void isFalse() { 46 | if (actual == null) { 47 | isEqualTo(false); // fails 48 | } else if (actual) { 49 | failWithoutActual(simpleFact("expected to be false")); 50 | } 51 | } 52 | 53 | static Factory booleans() { 54 | return BooleanSubject::new; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/ClassSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import com.google.common.annotations.GwtIncompatible; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * Propositions for {@link Class} subjects. 25 | * 26 | * @author Kurt Alfred Kluever 27 | */ 28 | @GwtIncompatible("reflection") 29 | @J2ktIncompatible 30 | public final class ClassSubject extends Subject { 31 | private final @Nullable Class actual; 32 | 33 | private ClassSubject(FailureMetadata metadata, @Nullable Class o) { 34 | super(metadata, o); 35 | this.actual = o; 36 | } 37 | 38 | /** 39 | * Fails if this class or interface is not the same as or a subclass or subinterface of, the given 40 | * class or interface. 41 | */ 42 | public void isAssignableTo(Class clazz) { 43 | if (!clazz.isAssignableFrom(checkNotNull(actual))) { 44 | failWithActual("expected to be assignable to", clazz.getName()); 45 | } 46 | } 47 | 48 | static Factory> classes() { 49 | return ClassSubject::new; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | import static com.google.common.base.Preconditions.checkNotNull; 20 | import static com.google.common.truth.Fact.makeMessage; 21 | 22 | import com.google.common.collect.ImmutableList; 23 | import com.google.common.truth.Platform.PlatformComparisonFailure; 24 | import org.jspecify.annotations.Nullable; 25 | 26 | /** 27 | * An {@link AssertionError} (usually a JUnit {@code ComparisonFailure}, but not under GWT) composed 28 | * of structured {@link Fact} instances and other string messages. 29 | */ 30 | final class ComparisonFailureWithFacts extends PlatformComparisonFailure implements ErrorWithFacts { 31 | private final ImmutableList facts; 32 | 33 | @UsedByReflection 34 | ComparisonFailureWithFacts( 35 | ImmutableList messages, 36 | ImmutableList facts, 37 | String expected, 38 | String actual, 39 | @Nullable Throwable cause) { 40 | super(makeMessage(messages, facts), checkNotNull(expected), checkNotNull(actual), cause); 41 | this.facts = checkNotNull(facts); 42 | } 43 | 44 | @Override 45 | public ImmutableList facts() { 46 | return facts; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/CustomSubjectBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | import static com.google.common.base.Preconditions.checkNotNull; 20 | 21 | 22 | /** 23 | * In a fluent assertion chain, exposes one or more "custom" {@code that} methods, which accept a 24 | * value under test and return a {@link Subject}. 25 | * 26 | *

(Note that the "custom" {@code that} methods are not defined on {@code CustomSubjectBuilder} 27 | * itself, only on its subtypes, which are the types users actually interact with.) 28 | * 29 | *

For more information about the methods in this class, see this FAQ entry. 31 | * 32 | *

For people extending Truth

33 | * 34 | *

When you write a custom subject, see our doc on 35 | * extensions. It explains the cases in which {@code CustomSubjectBuilder} is necessary, and it 36 | * links to further instructions. 37 | */ 38 | public abstract class CustomSubjectBuilder { 39 | /** 40 | * In a fluent assertion chain, the argument to the "custom" overload of {@link 41 | * StandardSubjectBuilder#about(CustomSubjectBuilder.Factory) about}, the method that specifies 42 | * what kind of {@link Subject} to create. 43 | * 44 | *

For more information about the fluent chain, see this FAQ entry. 46 | * 47 | *

For people extending Truth

48 | * 49 | *

When you write a custom subject, see our doc on 50 | * extensions. It explains the cases in which {@code CustomSubjectBuilder.Factory} is 51 | * necessary. 52 | */ 53 | public interface Factory { 54 | /** Creates a new {@link CustomSubjectBuilder} of the appropriate type. */ 55 | CustomSubjectBuilderT createSubjectBuilder(FailureMetadata metadata); 56 | } 57 | 58 | private final FailureMetadata metadata; 59 | 60 | /** Constructor for use by subclasses. */ 61 | protected CustomSubjectBuilder(FailureMetadata metadata) { 62 | this.metadata = checkNotNull(metadata); 63 | } 64 | 65 | /** 66 | * Returns the {@link FailureMetadata} instance that {@code that} methods should pass to {@link 67 | * Subject} constructors. 68 | */ 69 | protected final FailureMetadata metadata() { 70 | return metadata; 71 | } 72 | 73 | // TODO(user,cgruber): Better enforce that subclasses implement a that() method. 74 | } 75 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/ErrorWithFacts.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | import com.google.common.collect.ImmutableList; 20 | 21 | /** 22 | * Supertype of Truth's {@link AssertionError} subclasses that are created from a list of {@link 23 | * Fact} instances. 24 | */ 25 | interface ErrorWithFacts { 26 | ImmutableList facts(); 27 | } 28 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/FailureStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | 19 | /** 20 | * Defines what to do when a check fails. 21 | * 22 | *

This type does not appear directly in a fluent assertion chain, but you choose a {@code 23 | * FailureStrategy} by choosing which method to call at the beginning of the chain. 24 | * 25 | *

Built-in strategies include: 26 | * 27 | *

    28 | *
  • {@linkplain Truth#assert_ assertions} 29 | *
  • {@linkplain Expect expectations} 30 | *
  • {@linkplain TruthJUnit#assume assumptions} 31 | *
  • (and some useful only to people who implement custom subjects, described below) 32 | *
33 | * 34 | *

For more information about the fluent chain, see this 35 | * FAQ entry. 36 | * 37 | *

For people extending Truth

38 | * 39 | *

Custom {@code FailureStrategy} implementations are unusual. If you think you need one, 40 | * consider these alternatives: 41 | * 42 | *

    43 | *
  • To test a custom subject, use {@link ExpectFailure}. 44 | *
  • To create subjects for other objects related to your actual value (for chained assertions), 45 | * use {@link Subject#check(String, Object...)}, which preserves the existing {@code 46 | * FailureStrategy} and other context. 47 | *
  • To return a no-op subject after a previous assertion has failed (for chained assertions), 48 | * use {@link Subject#ignoreCheck} 49 | *
50 | * 51 | *

When you really do need to create your own strategy, rather than expose your {@code 52 | * FailureStrategy} instance to users, expose a {@link StandardSubjectBuilder} instance using {@link 53 | * StandardSubjectBuilder#forCustomFailureStrategy 54 | * StandardSubjectBuilder.forCustomFailureStrategy(STRATEGY)}. 55 | */ 56 | public interface FailureStrategy { 57 | /** 58 | * Handles a failure. The parameter is an {@code AssertionError} or subclass thereof, and it 59 | * contains information about the failure, which may include: 60 | * 61 | *

    62 | *
  • message: {@link Throwable#getMessage getMessage()} 63 | *
  • cause: {@link Throwable#getCause getCause()} 64 | *
  • actual and expected values: {@link org.junit.ComparisonFailure#getActual}, {@link 65 | * org.junit.ComparisonFailure#getExpected} 66 | *
  • stack trace: {@link Throwable#getStackTrace} 67 | *
68 | * 69 | * 70 | * 71 | *

We encourage implementations to record as much of this information as practical in the 72 | * exceptions they may throw or the other records they may make. 73 | */ 74 | void fail(AssertionError failure); 75 | } 76 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Fact.fact; 19 | import static com.google.common.truth.Fact.simpleFact; 20 | 21 | import com.google.common.base.Optional; 22 | import org.jspecify.annotations.Nullable; 23 | 24 | /** 25 | * Propositions for Guava {@link Optional} subjects. 26 | * 27 | *

If you are looking for a {@code java.util.Optional} subject, see {@link OptionalSubject}. 28 | * 29 | * @author Christian Gruber 30 | */ 31 | public final class GuavaOptionalSubject extends Subject { 32 | @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type 33 | private final @Nullable Optional actual; 34 | 35 | private GuavaOptionalSubject( 36 | FailureMetadata metadata, 37 | @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type 38 | @Nullable Optional actual) { 39 | super(metadata, actual, /* typeDescriptionOverride= */ "optional"); 40 | this.actual = actual; 41 | } 42 | 43 | /** Fails if the {@link Optional}{@code } is absent or the subject is null. */ 44 | public void isPresent() { 45 | if (actual == null) { 46 | failWithActual(simpleFact("expected present optional")); 47 | } else if (!actual.isPresent()) { 48 | failWithoutActual(simpleFact("expected to be present")); 49 | } 50 | } 51 | 52 | /** Fails if the {@link Optional}{@code } is present or the subject is null. */ 53 | public void isAbsent() { 54 | if (actual == null) { 55 | failWithActual(simpleFact("expected absent optional")); 56 | } else if (actual.isPresent()) { 57 | failWithoutActual( 58 | simpleFact("expected to be absent"), fact("but was present with value", actual.get())); 59 | } 60 | } 61 | 62 | /** 63 | * Fails if the {@link Optional}{@code } does not have the given value or the subject is null. 64 | * 65 | *

To make more complex assertions on the optional's value, split your assertion in two: 66 | * 67 | *

{@code
68 |    * assertThat(myOptional).isPresent();
69 |    * assertThat(myOptional.get()).contains("foo");
70 |    * }
71 | */ 72 | public void hasValue(@Nullable Object expected) { 73 | if (expected == null) { 74 | throw new NullPointerException("Optional cannot have a null value."); 75 | } 76 | if (actual == null) { 77 | failWithActual("expected an optional with value", expected); 78 | } else if (!actual.isPresent()) { 79 | failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); 80 | } else { 81 | checkNoNeedToDisplayBothValues("get()").that(actual.get()).isEqualTo(expected); 82 | } 83 | } 84 | 85 | static Factory> guavaOptionals() { 86 | return GuavaOptionalSubject::new; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/IgnoreJRERequirement.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | import static java.lang.annotation.ElementType.CONSTRUCTOR; 20 | import static java.lang.annotation.ElementType.METHOD; 21 | import static java.lang.annotation.ElementType.TYPE; 22 | 23 | import java.lang.annotation.Target; 24 | 25 | /** Disables Animal Sniffer's checking of compatibility with older versions of Java/Android. */ 26 | @Target({METHOD, CONSTRUCTOR, TYPE}) 27 | @interface IgnoreJRERequirement {} 28 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/J2ktIncompatible.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 The Guava Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. 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 distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | 15 | package com.google.common.truth; 16 | 17 | import java.lang.annotation.ElementType; 18 | import java.lang.annotation.Retention; 19 | import java.lang.annotation.RetentionPolicy; 20 | import java.lang.annotation.Target; 21 | 22 | /** 23 | * The presence of this annotation on an API indicates that the method may not be used with 24 | * J2kt. This can be removed once we can safely depend on a Guava release that contains it. 25 | */ 26 | @Retention(RetentionPolicy.CLASS) 27 | @Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD}) 28 | @interface J2ktIncompatible {} 29 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/LazyMessage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkArgument; 19 | import static com.google.common.base.Strings.lenientFormat; 20 | 21 | import com.google.common.annotations.VisibleForTesting; 22 | import com.google.common.collect.ImmutableList; 23 | import org.jspecify.annotations.Nullable; 24 | 25 | final class LazyMessage { 26 | private final String format; 27 | private final @Nullable Object[] args; 28 | 29 | LazyMessage(String format, @Nullable Object... args) { 30 | this.format = format; 31 | this.args = args; 32 | int placeholders = countPlaceholders(format); 33 | checkArgument( 34 | placeholders == args.length, 35 | "Incorrect number of args (%s) for the given placeholders (%s) in string template:\"%s\"", 36 | args.length, 37 | placeholders, 38 | format); 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | return lenientFormat(format, args); 44 | } 45 | 46 | @VisibleForTesting 47 | static int countPlaceholders(String template) { 48 | int index = 0; 49 | int count = 0; 50 | while (true) { 51 | index = template.indexOf("%s", index); 52 | if (index == -1) { 53 | break; 54 | } 55 | index++; 56 | count++; 57 | } 58 | return count; 59 | } 60 | 61 | static ImmutableList evaluateAll(ImmutableList messages) { 62 | ImmutableList.Builder result = ImmutableList.builder(); 63 | for (LazyMessage message : messages) { 64 | result.add(message.toString()); 65 | } 66 | return result.build(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/MultisetSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkArgument; 19 | import static com.google.common.base.Preconditions.checkNotNull; 20 | 21 | import com.google.common.collect.Multiset; 22 | import org.jspecify.annotations.Nullable; 23 | 24 | /** 25 | * Propositions for {@link Multiset} subjects. 26 | * 27 | * @author Kurt Alfred Kluever 28 | */ 29 | public final class MultisetSubject extends IterableSubject { 30 | 31 | private final @Nullable Multiset actual; 32 | 33 | private MultisetSubject(FailureMetadata metadata, @Nullable Multiset multiset) { 34 | super(metadata, multiset, /* typeDescriptionOverride= */ "multiset"); 35 | this.actual = multiset; 36 | } 37 | 38 | /** Fails if the element does not have the given count. */ 39 | public final void hasCount(@Nullable Object element, int expectedCount) { 40 | checkArgument(expectedCount >= 0, "expectedCount(%s) must be >= 0", expectedCount); 41 | int actualCount = checkNotNull(actual).count(element); 42 | check("count(%s)", element).that(actualCount).isEqualTo(expectedCount); 43 | } 44 | 45 | static Factory> multisets() { 46 | return MultisetSubject::new; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/NullnessCasts.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. 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 distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | 15 | package com.google.common.truth; 16 | 17 | import org.jspecify.annotations.Nullable; 18 | 19 | /** A utility method to perform unchecked casts to suppress errors produced by nullness analyses. */ 20 | final class NullnessCasts { 21 | /** 22 | * Accepts a {@code @Nullable T} and returns a plain {@code T}, without performing any check that 23 | * that conversion is safe. 24 | * 25 | *

This method is intended to help with usages of type parameters that have parametric 26 | * nullness. If a type parameter instead ranges over only non-null types (or if the type is a 27 | * non-variable type, like {@code String}), then code should almost never use this method, 28 | * preferring instead to call {@code requireNonNull} so as to benefit from its runtime check. 29 | * 30 | *

An example use case for this method is in implementing an {@code Iterator} whose {@code 31 | * next} field is lazily initialized. The type of that field would be {@code @Nullable T}, and the 32 | * code would be responsible for populating a "real" {@code T} (which might still be the value 33 | * {@code null}!) before returning it to callers. Depending on how the code is structured, a 34 | * nullness analysis might not understand that the field has been populated. To avoid that problem 35 | * without having to add {@code @SuppressWarnings}, the code can call this method. 36 | * 37 | *

Why not just add {@code SuppressWarnings}? The problem is that this method is 38 | * typically useful for {@code return} statements. That leaves the code with two options: Either 39 | * add the suppression to the whole method (which turns off checking for a large section of code), 40 | * or extract a variable, and put the suppression on that. However, a local variable typically 41 | * doesn't work: Because nullness analyses typically infer the nullness of local variables, 42 | * there's no way to assign a {@code @Nullable T} to a field {@code T foo;} and instruct the 43 | * analysis that that means "plain {@code T}" rather than the inferred type {@code @Nullable T}. 44 | * (Even if supported added {@code @NonNull}, that would not help, since the problem case 45 | * addressed by this method is the case in which {@code T} has parametric nullness -- and thus its 46 | * value may be legitimately {@code null}.) 47 | */ 48 | @SuppressWarnings("nullness") 49 | static T uncheckedCastNullableTToT(@Nullable T t) { 50 | return t; 51 | } 52 | 53 | private NullnessCasts() {} 54 | } 55 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/ObjectArraySubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import java.util.Arrays; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * A Subject for {@code Object[]} and more generically {@code T[]}. 25 | * 26 | * @author Christian Gruber 27 | */ 28 | public final class ObjectArraySubject extends AbstractArraySubject { 29 | private final T @Nullable [] actual; 30 | 31 | private ObjectArraySubject(FailureMetadata metadata, T @Nullable [] o) { 32 | super(metadata, o, /* typeDescriptionOverride= */ "array"); 33 | this.actual = o; 34 | } 35 | 36 | public IterableSubject asList() { 37 | return checkNoNeedToDisplayBothValues("asList()").that(Arrays.asList(checkNotNull(actual))); 38 | } 39 | 40 | static Factory, T[]> objectArrays() { 41 | return ObjectArraySubject::new; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/OptionalDoubleSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Fact.fact; 19 | import static com.google.common.truth.Fact.simpleFact; 20 | import static com.google.common.truth.Platform.doubleToString; 21 | 22 | import java.util.OptionalDouble; 23 | import org.jspecify.annotations.Nullable; 24 | 25 | /** 26 | * Propositions for Java 8 {@link OptionalDouble} subjects. 27 | * 28 | * @author Ben Douglass 29 | * @since 1.3.0 (previously part of {@code truth-java8-extension}) 30 | */ 31 | @IgnoreJRERequirement 32 | public final class OptionalDoubleSubject extends Subject { 33 | 34 | private final @Nullable OptionalDouble actual; 35 | 36 | private OptionalDoubleSubject(FailureMetadata failureMetadata, @Nullable OptionalDouble subject) { 37 | super(failureMetadata, subject, /* typeDescriptionOverride= */ "optionalDouble"); 38 | this.actual = subject; 39 | } 40 | 41 | /** Fails if the {@link OptionalDouble} is empty or the subject is null. */ 42 | public void isPresent() { 43 | if (actual == null) { 44 | failWithActual(simpleFact("expected present optional")); 45 | } else if (!actual.isPresent()) { 46 | failWithoutActual(simpleFact("expected to be present")); 47 | } 48 | } 49 | 50 | /** Fails if the {@link OptionalDouble} is present or the subject is null. */ 51 | public void isEmpty() { 52 | if (actual == null) { 53 | failWithActual(simpleFact("expected empty optional")); 54 | } else if (actual.isPresent()) { 55 | failWithoutActual( 56 | simpleFact("expected to be empty"), 57 | fact("but was present with value", doubleToString(actual.getAsDouble()))); 58 | } 59 | } 60 | 61 | /** 62 | * Fails if the {@link OptionalDouble} does not have the given value or the subject is null. This 63 | * method is not recommended when the code under test is doing any kind of arithmetic, 64 | * since the exact result of floating point arithmetic is sensitive to apparently trivial changes. 65 | * More sophisticated comparisons can be done using {@code assertThat(optional.getAsDouble())…}. 66 | * This method is recommended when the code under test is specified as either copying a value 67 | * without modification from its input or returning a well-defined literal or constant value. 68 | */ 69 | public void hasValue(double expected) { 70 | if (actual == null) { 71 | failWithActual("expected an optional with value", expected); 72 | } else if (!actual.isPresent()) { 73 | failWithoutActual( 74 | fact("expected to have value", doubleToString(expected)), simpleFact("but was absent")); 75 | } else { 76 | checkNoNeedToDisplayBothValues("getAsDouble()") 77 | .that(actual.getAsDouble()) 78 | .isEqualTo(expected); 79 | } 80 | } 81 | 82 | /** 83 | * Obsolete factory instance. This factory was previously necessary for assertions like {@code 84 | * assertWithMessage(...).about(optionalDoubles()).that(optional)....}. Now, you can perform 85 | * assertions like that without the {@code about(...)} call. 86 | * 87 | * @deprecated Instead of {@code about(optionalDoubles()).that(...)}, use just {@code that(...)}. 88 | * Similarly, instead of {@code assertAbout(optionalDoubles()).that(...)}, use just {@code 89 | * assertThat(...)}. 90 | */ 91 | @Deprecated 92 | @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. 93 | public static Factory optionalDoubles() { 94 | return OptionalDoubleSubject::new; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/OptionalIntSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Fact.fact; 19 | import static com.google.common.truth.Fact.simpleFact; 20 | 21 | import java.util.OptionalInt; 22 | import org.jspecify.annotations.Nullable; 23 | 24 | /** 25 | * Propositions for Java 8 {@link OptionalInt} subjects. 26 | * 27 | * @author Ben Douglass 28 | * @since 1.3.0 (previously part of {@code truth-java8-extension}) 29 | */ 30 | @IgnoreJRERequirement 31 | public final class OptionalIntSubject extends Subject { 32 | private final @Nullable OptionalInt actual; 33 | 34 | private OptionalIntSubject(FailureMetadata failureMetadata, @Nullable OptionalInt subject) { 35 | super(failureMetadata, subject, /* typeDescriptionOverride= */ "optionalInt"); 36 | this.actual = subject; 37 | } 38 | 39 | /** Fails if the {@link OptionalInt} is empty or the subject is null. */ 40 | public void isPresent() { 41 | if (actual == null) { 42 | failWithActual(simpleFact("expected present optional")); 43 | } else if (!actual.isPresent()) { 44 | failWithoutActual(simpleFact("expected to be present")); 45 | } 46 | } 47 | 48 | /** Fails if the {@link OptionalInt} is present or the subject is null. */ 49 | public void isEmpty() { 50 | if (actual == null) { 51 | failWithActual(simpleFact("expected empty optional")); 52 | } else if (actual.isPresent()) { 53 | failWithoutActual( 54 | simpleFact("expected to be empty"), 55 | fact("but was present with value", actual.getAsInt())); 56 | } 57 | } 58 | 59 | /** 60 | * Fails if the {@link OptionalInt} does not have the given value or the subject is null. More 61 | * sophisticated comparisons can be done using {@code assertThat(optional.getAsInt())…}. 62 | */ 63 | public void hasValue(int expected) { 64 | if (actual == null) { 65 | failWithActual("expected an optional with value", expected); 66 | } else if (!actual.isPresent()) { 67 | failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); 68 | } else { 69 | checkNoNeedToDisplayBothValues("getAsInt()").that(actual.getAsInt()).isEqualTo(expected); 70 | } 71 | } 72 | 73 | /** 74 | * Obsolete factory instance. This factory was previously necessary for assertions like {@code 75 | * assertWithMessage(...).about(optionalInts()).that(optional)....}. Now, you can perform 76 | * assertions like that without the {@code about(...)} call. 77 | * 78 | * @deprecated Instead of {@code about(optionalInts()).that(...)}, use just {@code that(...)}. 79 | * Similarly, instead of {@code assertAbout(optionalInts()).that(...)}, use just {@code 80 | * assertThat(...)}. 81 | */ 82 | @Deprecated 83 | @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. 84 | public static Factory optionalInts() { 85 | return OptionalIntSubject::new; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/OptionalLongSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Fact.fact; 19 | import static com.google.common.truth.Fact.simpleFact; 20 | 21 | import java.util.OptionalLong; 22 | import org.jspecify.annotations.Nullable; 23 | 24 | /** 25 | * Propositions for Java 8 {@link OptionalLong} subjects. 26 | * 27 | * @author Ben Douglass 28 | * @since 1.3.0 (previously part of {@code truth-java8-extension}) 29 | */ 30 | @IgnoreJRERequirement 31 | public final class OptionalLongSubject extends Subject { 32 | private final @Nullable OptionalLong actual; 33 | 34 | private OptionalLongSubject(FailureMetadata failureMetadata, @Nullable OptionalLong subject) { 35 | super(failureMetadata, subject, /* typeDescriptionOverride= */ "optionalLong"); 36 | this.actual = subject; 37 | } 38 | 39 | /** Fails if the {@link OptionalLong} is empty or the subject is null. */ 40 | public void isPresent() { 41 | if (actual == null) { 42 | failWithActual(simpleFact("expected present optional")); 43 | } else if (!actual.isPresent()) { 44 | failWithoutActual(simpleFact("expected to be present")); 45 | } 46 | } 47 | 48 | /** Fails if the {@link OptionalLong} is present or the subject is null. */ 49 | public void isEmpty() { 50 | if (actual == null) { 51 | failWithActual(simpleFact("expected empty optional")); 52 | } else if (actual.isPresent()) { 53 | failWithoutActual( 54 | simpleFact("expected to be empty"), 55 | fact("but was present with value", actual.getAsLong())); 56 | } 57 | } 58 | 59 | /** 60 | * Fails if the {@link OptionalLong} does not have the given value or the subject is null. More 61 | * sophisticated comparisons can be done using {@code assertThat(optional.getAsLong())…}. 62 | */ 63 | public void hasValue(long expected) { 64 | if (actual == null) { 65 | failWithActual("expected an optional with value", expected); 66 | } else if (!actual.isPresent()) { 67 | failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); 68 | } else { 69 | checkNoNeedToDisplayBothValues("getAsLong()").that(actual.getAsLong()).isEqualTo(expected); 70 | } 71 | } 72 | 73 | /** 74 | * Obsolete factory instance. This factory was previously necessary for assertions like {@code 75 | * assertWithMessage(...).about(optionalLongs()).that(optional)....}. Now, you can perform 76 | * assertions like that without the {@code about(...)} call. 77 | * 78 | * @deprecated Instead of {@code about(optionalLongs()).that(...)}, use just {@code that(...)}. 79 | * Similarly, instead of {@code assertAbout(optionalLongs()).that(...)}, use just {@code 80 | * assertThat(...)}. 81 | */ 82 | @Deprecated 83 | @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. 84 | public static Factory optionalLongs() { 85 | return OptionalLongSubject::new; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/OptionalSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Fact.fact; 19 | import static com.google.common.truth.Fact.simpleFact; 20 | 21 | import java.util.Optional; 22 | import org.jspecify.annotations.Nullable; 23 | 24 | /** 25 | * Propositions for Java 8 {@link Optional} subjects. 26 | * 27 | * @author Christian Gruber 28 | * @since 1.3.0 (previously part of {@code truth-java8-extension}) 29 | */ 30 | @IgnoreJRERequirement 31 | public final class OptionalSubject extends Subject { 32 | @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type 33 | private final @Nullable Optional actual; 34 | 35 | private OptionalSubject( 36 | FailureMetadata failureMetadata, 37 | @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type 38 | @Nullable Optional subject) { 39 | super(failureMetadata, subject, /* typeDescriptionOverride= */ "optional"); 40 | this.actual = subject; 41 | } 42 | 43 | // TODO(cpovirk): Consider making OptionalIntSubject and OptionalLongSubject delegate to this. 44 | 45 | /** Fails if the {@link Optional}{@code } is empty or the subject is null. */ 46 | public void isPresent() { 47 | if (actual == null) { 48 | failWithActual(simpleFact("expected present optional")); 49 | } else if (!actual.isPresent()) { 50 | failWithoutActual(simpleFact("expected to be present")); 51 | } 52 | } 53 | 54 | /** Fails if the {@link Optional}{@code } is present or the subject is null. */ 55 | public void isEmpty() { 56 | if (actual == null) { 57 | failWithActual(simpleFact("expected empty optional")); 58 | } else if (actual.isPresent()) { 59 | failWithoutActual( 60 | simpleFact("expected to be empty"), fact("but was present with value", actual.get())); 61 | } 62 | } 63 | 64 | /** 65 | * Fails if the {@link Optional}{@code } does not have the given value or the subject is null. 66 | * 67 | *

To make more complex assertions on the optional's value, split your assertion in two: 68 | * 69 | *

{@code
 70 |    * assertThat(myOptional).isPresent();
 71 |    * assertThat(myOptional.get()).contains("foo");
 72 |    * }
73 | */ 74 | public void hasValue(@Nullable Object expected) { 75 | if (expected == null) { 76 | throw new NullPointerException("Optional cannot have a null value."); 77 | } 78 | if (actual == null) { 79 | failWithActual("expected an optional with value", expected); 80 | } else if (!actual.isPresent()) { 81 | failWithoutActual(fact("expected to have value", expected), simpleFact("but was empty")); 82 | } else { 83 | checkNoNeedToDisplayBothValues("get()").that(actual.get()).isEqualTo(expected); 84 | } 85 | } 86 | 87 | /** 88 | * Obsolete factory instance. This factory was previously necessary for assertions like {@code 89 | * assertWithMessage(...).about(paths()).that(path)....}. Now, you can perform assertions like 90 | * that without the {@code about(...)} call. 91 | * 92 | * @deprecated Instead of {@code about(optionals()).that(...)}, use just {@code that(...)}. 93 | * Similarly, instead of {@code assertAbout(optionals()).that(...)}, use just {@code 94 | * assertThat(...)}. 95 | */ 96 | @Deprecated 97 | @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. 98 | public static Factory> optionals() { 99 | return OptionalSubject::new; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/Ordered.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | 19 | /** 20 | * Returned by calls like {@link IterableSubject#containsExactly}, {@code Ordered} lets the caller 21 | * additionally check that the expected elements were present in the order they were passed to the 22 | * previous calls. 23 | * 24 | *
{@code
25 |  * assertThat(supportedCharsets).containsExactly("UTF-8", "US-ASCII"); // does not check order
26 |  * assertThat(supportedCharsets).containsExactly("UTF-8", "US-ASCII").inOrder(); // does check order
27 |  * }
28 | */ 29 | public interface Ordered { 30 | 31 | /** 32 | * An additional assertion, implemented by some containment subjects which allows for a further 33 | * constraint of orderedness. 34 | */ 35 | void inOrder(); 36 | } 37 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/PathSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import com.google.common.annotations.GwtIncompatible; 19 | import com.google.j2objc.annotations.J2ObjCIncompatible; 20 | import java.nio.file.Path; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * Assertions for {@link Path} instances. 25 | * 26 | * @since 1.3.0 (previously part of {@code truth-java8-extension}) 27 | */ 28 | @GwtIncompatible 29 | @J2ObjCIncompatible 30 | @J2ktIncompatible 31 | public final class PathSubject extends Subject { 32 | private PathSubject(FailureMetadata failureMetadata, @Nullable Path actual) { 33 | super(failureMetadata, actual); 34 | } 35 | 36 | /** 37 | * Obsolete factory instance. This factory was previously necessary for assertions like {@code 38 | * assertWithMessage(...).about(paths()).that(path)....}. Now, you can perform assertions like 39 | * that without the {@code about(...)} call. 40 | * 41 | * @deprecated Instead of {@code about(paths()).that(...)}, use just {@code that(...)}. Similarly, 42 | * instead of {@code assertAbout(paths()).that(...)}, use just {@code assertThat(...)}. 43 | */ 44 | @Deprecated 45 | @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. 46 | public static Factory paths() { 47 | return PathSubject::new; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/PrimitiveBooleanArraySubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import com.google.common.primitives.Booleans; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * A Subject for {@code boolean[]}. 25 | * 26 | * @author Christian Gruber (cgruber@israfil.net) 27 | */ 28 | public final class PrimitiveBooleanArraySubject extends AbstractArraySubject { 29 | private final boolean @Nullable [] actual; 30 | 31 | private PrimitiveBooleanArraySubject(FailureMetadata metadata, boolean @Nullable [] o) { 32 | super(metadata, o, /* typeDescriptionOverride= */ "array"); 33 | this.actual = o; 34 | } 35 | 36 | public IterableSubject asList() { 37 | return checkNoNeedToDisplayBothValues("asList()").that(Booleans.asList(checkNotNull(actual))); 38 | } 39 | 40 | static Factory booleanArrays() { 41 | return PrimitiveBooleanArraySubject::new; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/PrimitiveByteArraySubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import com.google.common.primitives.Bytes; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * A Subject for {@code byte[]}. 25 | * 26 | * @author Kurt Alfred Kluever 27 | */ 28 | public final class PrimitiveByteArraySubject extends AbstractArraySubject { 29 | private final byte @Nullable [] actual; 30 | 31 | private PrimitiveByteArraySubject(FailureMetadata metadata, byte @Nullable [] o) { 32 | super(metadata, o, /* typeDescriptionOverride= */ "array"); 33 | this.actual = o; 34 | } 35 | 36 | public IterableSubject asList() { 37 | return checkNoNeedToDisplayBothValues("asList()").that(Bytes.asList(checkNotNull(actual))); 38 | } 39 | 40 | static Factory byteArrays() { 41 | return PrimitiveByteArraySubject::new; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/PrimitiveCharArraySubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import com.google.common.primitives.Chars; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * A Subject for {@code char[]}. 25 | * 26 | * @author Christian Gruber (cgruber@israfil.net) 27 | */ 28 | public final class PrimitiveCharArraySubject extends AbstractArraySubject { 29 | private final char @Nullable [] actual; 30 | 31 | private PrimitiveCharArraySubject(FailureMetadata metadata, char @Nullable [] o) { 32 | super(metadata, o, /* typeDescriptionOverride= */ "array"); 33 | this.actual = o; 34 | } 35 | 36 | public IterableSubject asList() { 37 | return checkNoNeedToDisplayBothValues("asList()").that(Chars.asList(checkNotNull(actual))); 38 | } 39 | 40 | static Factory charArrays() { 41 | return PrimitiveCharArraySubject::new; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/PrimitiveIntArraySubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import com.google.common.primitives.Ints; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * A Subject for {@code int[]}. 25 | * 26 | * @author Christian Gruber (cgruber@israfil.net) 27 | */ 28 | public final class PrimitiveIntArraySubject extends AbstractArraySubject { 29 | private final int @Nullable [] actual; 30 | 31 | private PrimitiveIntArraySubject(FailureMetadata metadata, int @Nullable [] o) { 32 | super(metadata, o, /* typeDescriptionOverride= */ "array"); 33 | this.actual = o; 34 | } 35 | 36 | public IterableSubject asList() { 37 | return checkNoNeedToDisplayBothValues("asList()").that(Ints.asList(checkNotNull(actual))); 38 | } 39 | 40 | static Factory intArrays() { 41 | return PrimitiveIntArraySubject::new; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/PrimitiveLongArraySubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import com.google.common.primitives.Longs; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * A Subject for {@code long[]}. 25 | * 26 | * @author Christian Gruber (cgruber@israfil.net) 27 | */ 28 | public final class PrimitiveLongArraySubject extends AbstractArraySubject { 29 | private final long @Nullable [] actual; 30 | 31 | private PrimitiveLongArraySubject(FailureMetadata metadata, long @Nullable [] o) { 32 | super(metadata, o, /* typeDescriptionOverride= */ "array"); 33 | this.actual = o; 34 | } 35 | 36 | public IterableSubject asList() { 37 | return checkNoNeedToDisplayBothValues("asList()").that(Longs.asList(checkNotNull(actual))); 38 | } 39 | 40 | static Factory longArrays() { 41 | return PrimitiveLongArraySubject::new; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/PrimitiveShortArraySubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import com.google.common.primitives.Shorts; 21 | import org.jspecify.annotations.Nullable; 22 | 23 | /** 24 | * A Subject for {@code short[]}. 25 | * 26 | * @author Christian Gruber (cgruber@israfil.net) 27 | */ 28 | public final class PrimitiveShortArraySubject extends AbstractArraySubject { 29 | private final short @Nullable [] actual; 30 | 31 | private PrimitiveShortArraySubject(FailureMetadata metadata, short @Nullable [] o) { 32 | super(metadata, o, /* typeDescriptionOverride= */ "array"); 33 | this.actual = o; 34 | } 35 | 36 | public IterableSubject asList() { 37 | return checkNoNeedToDisplayBothValues("asList()").that(Shorts.asList(checkNotNull(actual))); 38 | } 39 | 40 | static Factory shortArrays() { 41 | return PrimitiveShortArraySubject::new; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/SimpleSubjectBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | 20 | import org.jspecify.annotations.Nullable; 21 | 22 | /** 23 | * In a fluent assertion chain, exposes the most common {@code that} method, which accepts a value 24 | * under test and returns a {@link Subject}. 25 | * 26 | *

For more information about the methods in this class, see this FAQ entry. 28 | * 29 | *

For people extending Truth

30 | * 31 | *

You won't extend this type. When you write a custom subject, see our doc on extensions. 33 | */ 34 | public final class SimpleSubjectBuilder { 35 | private final FailureMetadata metadata; 36 | private final Subject.Factory subjectFactory; 37 | 38 | SimpleSubjectBuilder( 39 | FailureMetadata metadata, Subject.Factory subjectFactory) { 40 | this.metadata = checkNotNull(metadata); 41 | this.subjectFactory = checkNotNull(subjectFactory); 42 | } 43 | 44 | public SubjectT that(@Nullable ActualT actual) { 45 | return subjectFactory.createSubject(metadata, actual); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/SneakyThrows.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | import com.google.errorprone.annotations.CanIgnoreReturnValue; 20 | 21 | /** Static utility method for unchecked throwing of any {@link Throwable}. */ 22 | final class SneakyThrows { 23 | /** 24 | * Throws {@code t} as if it were an unchecked {@link Throwable}. 25 | * 26 | *

This method is useful primarily when we make a reflective call to a method with no {@code 27 | * throws} clause: Java forces us to handle an arbitrary {@link Throwable} from that method, 28 | * rather than just the {@link RuntimeException} or {@link Error} that should be possible. (And in 29 | * fact the static type of {@link Throwable} is occasionally justified even for a method with no 30 | * {@code throws} clause: Some such methods can in fact throw a checked exception (e.g., by 31 | * calling code written in Kotlin).) Typically, we want to let a {@link Throwable} from such a 32 | * method propagate untouched, just as we'd typically let it do for a non-reflective call. 33 | * However, we can't usually write {@code throw t;} when {@code t} has a static type of {@link 34 | * Throwable}. But we can write {@code sneakyThrow(t);}. 35 | * 36 | *

We sometimes also use {@code sneakyThrow} for testing how our code responds to sneaky 37 | * checked exceptions. 38 | * 39 | * @return never; this method declares a return type of {@link Error} only so that callers can 40 | * write {@code throw sneakyThrow(t);} to convince the compiler that the statement will always 41 | * throw. 42 | */ 43 | @CanIgnoreReturnValue 44 | static Error sneakyThrow(Throwable t) { 45 | throw new SneakyThrows().throwIt(t); 46 | } 47 | 48 | @SuppressWarnings("unchecked") // not really safe, but that's the point 49 | private Error throwIt(Throwable t) throws T { 50 | throw (T) t; 51 | } 52 | 53 | private SneakyThrows() {} 54 | } 55 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/Truth.gwt.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/Truth8.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import com.google.common.annotations.GwtIncompatible; 19 | import com.google.j2objc.annotations.J2ObjCIncompatible; 20 | import java.nio.file.Path; 21 | import java.util.Optional; 22 | import java.util.OptionalDouble; 23 | import java.util.OptionalInt; 24 | import java.util.OptionalLong; 25 | import java.util.stream.IntStream; 26 | import java.util.stream.LongStream; 27 | import java.util.stream.Stream; 28 | import org.jspecify.annotations.Nullable; 29 | 30 | /** 31 | * The obsolete entry point for assertions about Java 8 types. 32 | * 33 | * @deprecated Instead of this class's methods, use the identical methods declared in the main 34 | * {@link Truth} class. In most cases, you can migrate your whole project 36 | * mechanically: {@code git grep -l Truth8 | xargs perl -pi -e 's/\bTruth8\b/Truth/g;'} 37 | * Migration is important if you static import {@code assertThat}: If you do not migrate, 38 | * such static imports will become ambiguous in Truth 1.4.2, breaking your build. 39 | */ 40 | @Deprecated 41 | // Replacing "Truth.assertThat" with "assertThat" would produce an infinite loop. 42 | @SuppressWarnings({ 43 | "StaticImportPreferred", 44 | "StaticImportPreferredForTruth", 45 | }) 46 | public final class Truth8 { 47 | @SuppressWarnings("AssertAboutOptionals") // suggests infinite recursion 48 | public static OptionalSubject assertThat(@Nullable Optional target) { 49 | return Truth.assertThat(target); 50 | } 51 | 52 | public static OptionalIntSubject assertThat(@Nullable OptionalInt target) { 53 | return Truth.assertThat(target); 54 | } 55 | 56 | public static OptionalLongSubject assertThat(@Nullable OptionalLong target) { 57 | return Truth.assertThat(target); 58 | } 59 | 60 | public static OptionalDoubleSubject assertThat(@Nullable OptionalDouble target) { 61 | return Truth.assertThat(target); 62 | } 63 | 64 | public static StreamSubject assertThat(@Nullable Stream target) { 65 | return Truth.assertThat(target); 66 | } 67 | 68 | public static IntStreamSubject assertThat(@Nullable IntStream target) { 69 | return Truth.assertThat(target); 70 | } 71 | 72 | public static LongStreamSubject assertThat(@Nullable LongStream target) { 73 | return Truth.assertThat(target); 74 | } 75 | 76 | @GwtIncompatible 77 | @J2ObjCIncompatible 78 | @J2ktIncompatible 79 | public static PathSubject assertThat(@Nullable Path target) { 80 | return Truth.assertThat(target); 81 | } 82 | 83 | private Truth8() {} 84 | } 85 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/TruthJUnit.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import org.junit.AssumptionViolatedException; 19 | 20 | /** 21 | * Provides a way to use Truth to perform JUnit "assumptions." An assumption is a check that, if 22 | * false, aborts (skips) the test. This is especially useful in JUnit theories, parameterized tests, 23 | * or other combinatorial tests where some subset of the combinations are simply not applicable for 24 | * testing. 25 | * 26 | *

For example: 27 | * 28 | *

{@code
29 |  * import static com.google.common.truth.Truth.assertThat;
30 |  * import static com.google.common.truth.TruthJUnit.assume;
31 |  *
32 |  * public void @Test testFoosAgainstBars {
33 |  *   assume().that(foo).isNotNull();
34 |  *   assume().that(bar).isNotNull();
35 |  *   assertThat(foo.times(bar)).isEqualTo(blah);
36 |  * }
37 |  * }
38 | * 39 | * @author David Saff 40 | * @author Christian Gruber (cgruber@israfil.net) 41 | */ 42 | @com.google.common.annotations.GwtIncompatible("JUnit4") 43 | public final class TruthJUnit { 44 | @SuppressWarnings("ConstantCaseForConstants") // Despite the "Builder" name, it's not mutable. 45 | private static final StandardSubjectBuilder ASSUME = 46 | StandardSubjectBuilder.forCustomFailureStrategy( 47 | failure -> { 48 | AssumptionViolatedException assumptionViolated = 49 | new AssumptionViolatedException(failure.getMessage(), failure.getCause()); 50 | assumptionViolated.setStackTrace(failure.getStackTrace()); 51 | throw assumptionViolated; 52 | }); 53 | 54 | /** 55 | * Begins a call chain with the fluent Truth API. If the check made by the chain fails, it will 56 | * throw {@link AssumptionViolatedException}. 57 | */ 58 | public static StandardSubjectBuilder assume() { 59 | return ASSUME; 60 | } 61 | 62 | private TruthJUnit() {} 63 | } 64 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/UsedByReflection.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static java.lang.annotation.ElementType.CONSTRUCTOR; 19 | import static java.lang.annotation.ElementType.FIELD; 20 | import static java.lang.annotation.ElementType.METHOD; 21 | 22 | import java.lang.annotation.Target; 23 | 24 | @Target({METHOD, FIELD, CONSTRUCTOR}) 25 | @interface UsedByReflection {} 26 | -------------------------------------------------------------------------------- /core/src/main/java/com/google/common/truth/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * Truth is a library for performing assertions in 19 | * tests: 20 | * 21 | *
{@code
22 |  * assertThat(notificationText).contains("testuser@google.com");
23 |  * }
24 | * 25 | *

Truth is owned and maintained by the Guava team. It is used in the majority of the tests in Google’s own codebase. 27 | * 28 | *

For more information, see our introduction and 29 | * other docs. 30 | */ 31 | @CheckReturnValue 32 | @NullMarked 33 | package com.google.common.truth; 34 | 35 | import com.google.errorprone.annotations.CheckReturnValue; 36 | import org.jspecify.annotations.NullMarked; 37 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/BooleanSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.expectFailure; 19 | import static com.google.common.truth.FailureAssertions.assertFailureKeys; 20 | import static com.google.common.truth.FailureAssertions.assertFailureValue; 21 | import static com.google.common.truth.Truth.assertThat; 22 | 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | /** 28 | * Tests for Boolean Subjects. 29 | * 30 | * @author Christian Gruber (cgruber@israfil.net) 31 | */ 32 | @RunWith(JUnit4.class) 33 | public class BooleanSubjectTest { 34 | 35 | @Test 36 | public void isTrue() { 37 | assertThat(true).isTrue(); 38 | } 39 | 40 | @Test 41 | public void nullIsTrueFailing() { 42 | AssertionError e = expectFailure(whenTesting -> whenTesting.that((Boolean) null).isTrue()); 43 | assertFailureKeys(e, "expected", "but was"); 44 | assertFailureValue(e, "expected", "true"); 45 | assertFailureValue(e, "but was", "null"); 46 | } 47 | 48 | @Test 49 | public void nullIsFalseFailing() { 50 | AssertionError e = expectFailure(whenTesting -> whenTesting.that((Boolean) null).isFalse()); 51 | assertFailureKeys(e, "expected", "but was"); 52 | assertFailureValue(e, "expected", "false"); 53 | assertFailureValue(e, "but was", "null"); 54 | } 55 | 56 | @Test 57 | public void isTrueFailing() { 58 | AssertionError e = expectFailure(whenTesting -> whenTesting.that(false).isTrue()); 59 | assertFailureKeys(e, "expected to be true"); 60 | } 61 | 62 | @Test 63 | public void isFalse() { 64 | assertThat(false).isFalse(); 65 | } 66 | 67 | @Test 68 | public void isFalseFailing() { 69 | AssertionError e = expectFailure(whenTesting -> whenTesting.that(true).isFalse()); 70 | assertFailureKeys(e, "expected to be false"); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/ClassSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.expectFailure; 19 | import static com.google.common.truth.FailureAssertions.assertFailureValue; 20 | import static com.google.common.truth.Truth.assertThat; 21 | 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.junit.runners.JUnit4; 25 | 26 | /** 27 | * Tests for introspective Subject behaviour. 28 | * 29 | * @author Christian Gruber (cgruber@israfil.net) 30 | */ 31 | @RunWith(JUnit4.class) 32 | public class ClassSubjectTest { 33 | @Test 34 | public void testIsAssignableTo_same() { 35 | assertThat(String.class).isAssignableTo(String.class); 36 | } 37 | 38 | @Test 39 | public void testIsAssignableTo_parent() { 40 | assertThat(String.class).isAssignableTo(Object.class); 41 | assertThat(NullPointerException.class).isAssignableTo(Exception.class); 42 | } 43 | 44 | @Test 45 | public void testIsAssignableTo_reversed() { 46 | AssertionError e = 47 | expectFailure(whenTesting -> whenTesting.that(Object.class).isAssignableTo(String.class)); 48 | assertFailureValue(e, "expected to be assignable to", "java.lang.String"); 49 | } 50 | 51 | @Test 52 | public void testIsAssignableTo_differentTypes() { 53 | AssertionError e = 54 | expectFailure( 55 | whenTesting -> whenTesting.that(String.class).isAssignableTo(Exception.class)); 56 | assertFailureValue(e, "expected to be assignable to", "java.lang.Exception"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/ExpectFailure8Test.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.assertThat; 19 | import static com.google.common.truth.ExpectFailure.expectFailure; 20 | import static com.google.common.truth.ExpectFailure.expectFailureAbout; 21 | 22 | import com.google.common.truth.ExpectFailure.SimpleSubjectBuilderCallback; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | /** Tests of {@link ExpectFailure}'s Java 8 support. */ 28 | @RunWith(JUnit4.class) 29 | public final class ExpectFailure8Test { 30 | 31 | @Test 32 | public void testExpectFailure() throws Exception { 33 | AssertionError failure1 = expectFailure(whenTesting -> whenTesting.that(4).isEqualTo(5)); 34 | assertThat(failure1).factValue("expected").isEqualTo("5"); 35 | 36 | // verify multiple independent failures can be caught in the same test 37 | AssertionError failure2 = expectFailure(whenTesting -> whenTesting.that(5).isEqualTo(4)); 38 | assertThat(failure2).factValue("expected").isEqualTo("4"); 39 | } 40 | 41 | @Test 42 | public void testExpectFailureAbout() { 43 | AssertionError unused = 44 | expectFailureAbout( 45 | StringSubject::new, 46 | (SimpleSubjectBuilderCallback) 47 | whenTesting -> whenTesting.that("foo").contains("bar")); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/ExpectFailureRuleTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Truth.assertThat; 19 | 20 | import com.google.common.annotations.GwtIncompatible; 21 | import org.junit.Rule; 22 | import org.junit.Test; 23 | import org.junit.rules.ExpectedException; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | /** Tests for {@link ExpectFailure} used as JUnit {@link Rule}. */ 28 | @RunWith(JUnit4.class) 29 | @GwtIncompatible("org.junit.Rule") 30 | public class ExpectFailureRuleTest { 31 | @Rule public final ExpectFailure expectFailure = new ExpectFailure(); 32 | @Rule public final ExpectedException thrown = ExpectedException.none(); 33 | 34 | @Test 35 | public void expectFail_captureFailureAsExpected() { 36 | expectFailure.whenTesting().withMessage("abc").fail(); 37 | assertThat(expectFailure.getFailure()).hasMessageThat().isEqualTo("abc"); 38 | } 39 | 40 | @Test 41 | @SuppressWarnings("TruthSelfEquals") 42 | public void expectFail_passesIfUnused() { 43 | assertThat(4).isEqualTo(4); 44 | } 45 | 46 | @Test 47 | @SuppressWarnings("TruthSelfEquals") 48 | public void expectFail_failsAfterTest() { 49 | expectFailure.whenTesting().that(4).isEqualTo(4); 50 | thrown.expectMessage("ExpectFailure.whenTesting() invoked, but no failure was caught."); 51 | } 52 | 53 | @Test 54 | public void expectFail_throwInSubject_shouldPropagateOriginalException() { 55 | thrown.expectMessage("Throwing deliberately"); 56 | expectFailure.whenTesting().that(throwingMethod()).isEqualTo(2); 57 | } 58 | 59 | @Test 60 | @SuppressWarnings("TruthSelfEquals") 61 | public void expectFail_throwAfterSubject_shouldPropagateOriginalException() { 62 | expectFailure.whenTesting().that(2).isEqualTo(2); 63 | thrown.expectMessage("Throwing deliberately"); 64 | throwingMethod(); 65 | } 66 | 67 | private static long throwingMethod() { 68 | throw new RuntimeException("Throwing deliberately"); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/ExpectFailureWithStackTraceTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Truth.assertThat; 19 | 20 | import org.junit.Rule; 21 | import org.junit.Test; 22 | import org.junit.rules.TestRule; 23 | import org.junit.runner.Description; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | import org.junit.runners.model.Statement; 27 | 28 | /** Test that stack traces are included in the error message created by Expect. */ 29 | @RunWith(JUnit4.class) 30 | public class ExpectFailureWithStackTraceTest { 31 | private static final String METHOD_NAME = "ExpectFailureWithStackTraceTest.expectTwoFailures"; 32 | 33 | @Rule public final FailingExpect failToExpect = new FailingExpect(); 34 | 35 | @Test 36 | @SuppressWarnings("TruthSelfEquals") 37 | public void expectTwoFailures() { 38 | failToExpect.delegate.that(4).isNotEqualTo(4); 39 | failToExpect.delegate.that("abc").contains("x"); 40 | } 41 | 42 | /** Expect class that can examine the error message */ 43 | public static class FailingExpect implements TestRule { 44 | final Expect delegate = Expect.create(); 45 | 46 | @Override 47 | public Statement apply(Statement base, Description description) { 48 | Statement s = delegate.apply(base, description); 49 | return new Statement() { 50 | @Override 51 | public void evaluate() throws Throwable { 52 | String failureMessage = ""; 53 | try { 54 | s.evaluate(); 55 | } catch (AssertionError e) { 56 | failureMessage = e.getMessage(); 57 | } 58 | // Check that error message contains stack traces. Method name should appear twice, 59 | // once for each expect error. 60 | int firstIndex = failureMessage.indexOf(METHOD_NAME); 61 | assertThat(firstIndex).isGreaterThan(0); 62 | int secondIndex = failureMessage.indexOf(METHOD_NAME, firstIndex + 1); 63 | assertThat(secondIndex).isGreaterThan(firstIndex); 64 | } 65 | }; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/FailureAssertions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.assertThat; 19 | 20 | /** Convenience methods for {@link Subject} tests. */ 21 | final class FailureAssertions { 22 | static void assertFailureKeys(AssertionError e, String... keys) { 23 | assertThat(e).factKeys().containsExactlyElementsIn(keys).inOrder(); 24 | } 25 | 26 | static void assertFailureValue(AssertionError e, String key, String value) { 27 | assertThat(e).factValue(key).isEqualTo(value); 28 | } 29 | 30 | static void assertFailureValueIndexed(AssertionError e, String key, int index, String value) { 31 | assertThat(e).factValue(key, index).isEqualTo(value); 32 | } 33 | 34 | private FailureAssertions() {} 35 | } 36 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/GuavaOptionalSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.expectFailure; 19 | import static com.google.common.truth.FailureAssertions.assertFailureKeys; 20 | import static com.google.common.truth.FailureAssertions.assertFailureValue; 21 | import static com.google.common.truth.Truth.assertThat; 22 | import static org.junit.Assert.assertThrows; 23 | 24 | import com.google.common.base.Optional; 25 | import org.junit.Test; 26 | import org.junit.runner.RunWith; 27 | import org.junit.runners.JUnit4; 28 | 29 | /** 30 | * Tests for Guava {@link Optional} Subjects. 31 | * 32 | * @author Christian Gruber (cgruber@israfil.net) 33 | */ 34 | @RunWith(JUnit4.class) 35 | public class GuavaOptionalSubjectTest { 36 | 37 | @Test 38 | public void isPresent() { 39 | assertThat(Optional.of("foo")).isPresent(); 40 | } 41 | 42 | @Test 43 | public void isPresentFailing() { 44 | AssertionError e = 45 | expectFailure(whenTesting -> whenTesting.that(Optional.absent()).isPresent()); 46 | assertFailureKeys(e, "expected to be present"); 47 | } 48 | 49 | @Test 50 | public void isPresentFailingNull() { 51 | AssertionError e = 52 | expectFailure(whenTesting -> whenTesting.that((Optional) null).isPresent()); 53 | assertFailureKeys(e, "expected present optional", "but was"); 54 | } 55 | 56 | @Test 57 | public void isAbsent() { 58 | assertThat(Optional.absent()).isAbsent(); 59 | } 60 | 61 | @Test 62 | public void isAbsentFailing() { 63 | AssertionError e = 64 | expectFailure(whenTesting -> whenTesting.that(Optional.of("foo")).isAbsent()); 65 | assertFailureKeys(e, "expected to be absent", "but was present with value"); 66 | assertFailureValue(e, "but was present with value", "foo"); 67 | } 68 | 69 | @Test 70 | public void isAbsentFailingNull() { 71 | AssertionError e = 72 | expectFailure(whenTesting -> whenTesting.that((Optional) null).isAbsent()); 73 | assertFailureKeys(e, "expected absent optional", "but was"); 74 | } 75 | 76 | @Test 77 | public void hasValue() { 78 | assertThat(Optional.of("foo")).hasValue("foo"); 79 | } 80 | 81 | @Test 82 | public void hasValue_failingWithAbsent() { 83 | AssertionError e = 84 | expectFailure(whenTesting -> whenTesting.that(Optional.absent()).hasValue("foo")); 85 | assertFailureKeys(e, "expected to have value", "but was absent"); 86 | assertFailureValue(e, "expected to have value", "foo"); 87 | } 88 | 89 | @Test 90 | public void hasValue_npeWithNullParameter() { 91 | NullPointerException expected = 92 | assertThrows( 93 | NullPointerException.class, () -> assertThat(Optional.of("foo")).hasValue(null)); 94 | assertThat(expected).hasMessageThat().contains("Optional"); 95 | } 96 | 97 | @Test 98 | public void hasValue_failingWithWrongValue() { 99 | AssertionError e = 100 | expectFailure(whenTesting -> whenTesting.that(Optional.of("foo")).hasValue("boo")); 101 | assertFailureValue(e, "value of", "optional.get()"); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/MultisetSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.expectFailure; 19 | import static com.google.common.truth.FailureAssertions.assertFailureValue; 20 | import static com.google.common.truth.Truth.assertThat; 21 | import static com.google.common.truth.Truth.assertWithMessage; 22 | 23 | import com.google.common.collect.ImmutableMultiset; 24 | import org.junit.Test; 25 | import org.junit.runner.RunWith; 26 | import org.junit.runners.JUnit4; 27 | 28 | /** 29 | * Tests for Multiset Subjects. 30 | * 31 | * @author Kurt Alfred Kluever 32 | */ 33 | @RunWith(JUnit4.class) 34 | public class MultisetSubjectTest { 35 | 36 | @Test 37 | public void hasCount() { 38 | ImmutableMultiset multiset = ImmutableMultiset.of("kurt", "kurt", "kluever"); 39 | assertThat(multiset).hasCount("kurt", 2); 40 | assertThat(multiset).hasCount("kluever", 1); 41 | assertThat(multiset).hasCount("alfred", 0); 42 | 43 | assertWithMessage("name").that(multiset).hasCount("kurt", 2); 44 | } 45 | 46 | @Test 47 | public void hasCountFail() { 48 | ImmutableMultiset multiset = ImmutableMultiset.of("kurt", "kurt", "kluever"); 49 | AssertionError e = expectFailure(whenTesting -> whenTesting.that(multiset).hasCount("kurt", 3)); 50 | assertFailureValue(e, "value of", "multiset.count(kurt)"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/NoJUnitTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | import static com.google.common.truth.Truth.assertThat; 20 | 21 | import com.google.common.collect.ImmutableList; 22 | 23 | /** Truth-using binary to be run without JUnit on the classpath to verify that it still works. */ 24 | public final class NoJUnitTest { 25 | public static void main(String[] args) { 26 | try { 27 | assertThat("a").isEqualTo("b"); 28 | throw new Error("assertion should have failed"); 29 | } catch (AssertionError expected) { 30 | ImmutableList facts = ((AssertionErrorWithFacts) expected).facts(); 31 | assertThat(facts.get(0).key).isEqualTo("expected"); 32 | assertThat(facts.get(0).value).isEqualTo("b"); 33 | assertThat(facts.get(1).key).isEqualTo("but was"); 34 | assertThat(facts.get(1).value).isEqualTo("a"); 35 | } 36 | } 37 | 38 | private NoJUnitTest() {} 39 | } 40 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/OptionalDoubleSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.assertThat; 19 | import static com.google.common.truth.ExpectFailure.expectFailure; 20 | import static com.google.common.truth.Truth.assertThat; 21 | 22 | import java.util.OptionalDouble; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | /** 28 | * Tests for Java 8 {@link OptionalDouble} Subjects. 29 | * 30 | * @author Ben Douglass 31 | */ 32 | @RunWith(JUnit4.class) 33 | public class OptionalDoubleSubjectTest { 34 | 35 | @Test 36 | public void failOnNullSubject() { 37 | AssertionError expected = 38 | expectFailure(whenTesting -> whenTesting.that((OptionalDouble) null).isEmpty()); 39 | assertThat(expected).factKeys().containsExactly("expected empty optional", "but was").inOrder(); 40 | } 41 | 42 | @Test 43 | public void isPresent() { 44 | assertThat(OptionalDouble.of(1337.0)).isPresent(); 45 | } 46 | 47 | @Test 48 | public void isPresentFailing() { 49 | AssertionError expected = 50 | expectFailure(whenTesting -> whenTesting.that(OptionalDouble.empty()).isPresent()); 51 | assertThat(expected).factKeys().containsExactly("expected to be present"); 52 | } 53 | 54 | @Test 55 | public void isEmpty() { 56 | assertThat(OptionalDouble.empty()).isEmpty(); 57 | } 58 | 59 | @Test 60 | public void isEmptyFailing() { 61 | AssertionError expected = 62 | expectFailure(whenTesting -> whenTesting.that(OptionalDouble.of(1337.0)).isEmpty()); 63 | assertThat(expected).factKeys().contains("expected to be empty"); 64 | assertThat(expected).factValue("but was present with value").isEqualTo("1337.0"); 65 | } 66 | 67 | @Test 68 | public void isEmptyFailingNull() { 69 | AssertionError expected = 70 | expectFailure(whenTesting -> whenTesting.that((OptionalDouble) null).isEmpty()); 71 | assertThat(expected).factKeys().containsExactly("expected empty optional", "but was").inOrder(); 72 | } 73 | 74 | @Test 75 | public void hasValue() { 76 | assertThat(OptionalDouble.of(1337.0)).hasValue(1337.0); 77 | } 78 | 79 | @Test 80 | public void hasValue_FailingWithEmpty() { 81 | AssertionError expected = 82 | expectFailure(whenTesting -> whenTesting.that(OptionalDouble.empty()).hasValue(1337.0)); 83 | assertThat(expected) 84 | .factKeys() 85 | .containsExactly("expected to have value", "but was absent") 86 | .inOrder(); 87 | assertThat(expected).factValue("expected to have value").isEqualTo("1337.0"); 88 | } 89 | 90 | @Test 91 | public void hasValue_FailingWithWrongValue() { 92 | AssertionError expected = 93 | expectFailure(whenTesting -> whenTesting.that(OptionalDouble.of(1337.0)).hasValue(42.0)); 94 | assertThat(expected).factValue("value of").isEqualTo("optionalDouble.getAsDouble()"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/OptionalIntSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.assertThat; 19 | import static com.google.common.truth.ExpectFailure.expectFailure; 20 | import static com.google.common.truth.Truth.assertThat; 21 | 22 | import java.util.OptionalInt; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | /** 28 | * Tests for Java 8 {@link OptionalInt} Subjects. 29 | * 30 | * @author Ben Douglass 31 | */ 32 | @RunWith(JUnit4.class) 33 | public class OptionalIntSubjectTest { 34 | 35 | @Test 36 | public void failOnNullSubject() { 37 | AssertionError expected = 38 | expectFailure(whenTesting -> whenTesting.that((OptionalInt) null).isEmpty()); 39 | assertThat(expected).factKeys().containsExactly("expected empty optional", "but was").inOrder(); 40 | } 41 | 42 | @Test 43 | public void isPresent() { 44 | assertThat(OptionalInt.of(1337)).isPresent(); 45 | } 46 | 47 | @Test 48 | public void isPresentFailing() { 49 | AssertionError expected = 50 | expectFailure(whenTesting -> whenTesting.that(OptionalInt.empty()).isPresent()); 51 | assertThat(expected).factKeys().containsExactly("expected to be present"); 52 | } 53 | 54 | @Test 55 | public void isEmpty() { 56 | assertThat(OptionalInt.empty()).isEmpty(); 57 | } 58 | 59 | @Test 60 | public void isEmptyFailing() { 61 | AssertionError expected = 62 | expectFailure(whenTesting -> whenTesting.that(OptionalInt.of(1337)).isEmpty()); 63 | assertThat(expected).factKeys().contains("expected to be empty"); 64 | assertThat(expected).factValue("but was present with value").isEqualTo("1337"); 65 | } 66 | 67 | @Test 68 | public void isEmptyFailingNull() { 69 | AssertionError expected = 70 | expectFailure(whenTesting -> whenTesting.that((OptionalInt) null).isEmpty()); 71 | assertThat(expected).factKeys().containsExactly("expected empty optional", "but was").inOrder(); 72 | } 73 | 74 | @Test 75 | public void hasValue() { 76 | assertThat(OptionalInt.of(1337)).hasValue(1337); 77 | } 78 | 79 | @Test 80 | public void hasValue_FailingWithEmpty() { 81 | AssertionError expected = 82 | expectFailure(whenTesting -> whenTesting.that(OptionalInt.empty()).hasValue(1337)); 83 | assertThat(expected) 84 | .factKeys() 85 | .containsExactly("expected to have value", "but was absent") 86 | .inOrder(); 87 | assertThat(expected).factValue("expected to have value").isEqualTo("1337"); 88 | } 89 | 90 | @Test 91 | public void hasValue_FailingWithWrongValue() { 92 | AssertionError expected = 93 | expectFailure(whenTesting -> whenTesting.that(OptionalInt.of(1337)).hasValue(42)); 94 | assertThat(expected).factValue("value of").isEqualTo("optionalInt.getAsInt()"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/OptionalLongSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.assertThat; 19 | import static com.google.common.truth.ExpectFailure.expectFailure; 20 | import static com.google.common.truth.Truth.assertThat; 21 | 22 | import java.util.OptionalLong; 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | /** 28 | * Tests for Java 8 {@link OptionalLong} Subjects. 29 | * 30 | * @author Ben Douglass 31 | */ 32 | @RunWith(JUnit4.class) 33 | public class OptionalLongSubjectTest { 34 | 35 | @Test 36 | public void failOnNullSubject() { 37 | AssertionError expected = 38 | expectFailure(whenTesting -> whenTesting.that((OptionalLong) null).isEmpty()); 39 | assertThat(expected).factKeys().containsExactly("expected empty optional", "but was").inOrder(); 40 | } 41 | 42 | @Test 43 | public void isPresent() { 44 | assertThat(OptionalLong.of(1337L)).isPresent(); 45 | } 46 | 47 | @Test 48 | public void isPresentFailing() { 49 | AssertionError expected = 50 | expectFailure(whenTesting -> whenTesting.that(OptionalLong.empty()).isPresent()); 51 | assertThat(expected).factKeys().containsExactly("expected to be present"); 52 | } 53 | 54 | @Test 55 | public void isEmpty() { 56 | assertThat(OptionalLong.empty()).isEmpty(); 57 | } 58 | 59 | @Test 60 | public void isEmptyFailing() { 61 | AssertionError expected = 62 | expectFailure(whenTesting -> whenTesting.that(OptionalLong.of(1337L)).isEmpty()); 63 | assertThat(expected).factKeys().contains("expected to be empty"); 64 | assertThat(expected).factValue("but was present with value").isEqualTo("1337"); 65 | } 66 | 67 | @Test 68 | public void isEmptyFailingNull() { 69 | AssertionError expected = 70 | expectFailure(whenTesting -> whenTesting.that((OptionalLong) null).isEmpty()); 71 | assertThat(expected).factKeys().containsExactly("expected empty optional", "but was").inOrder(); 72 | } 73 | 74 | @Test 75 | public void hasValue() { 76 | assertThat(OptionalLong.of(1337L)).hasValue(1337L); 77 | } 78 | 79 | @Test 80 | public void hasValue_FailingWithEmpty() { 81 | AssertionError expected = 82 | expectFailure(whenTesting -> whenTesting.that(OptionalLong.empty()).hasValue(1337L)); 83 | assertThat(expected) 84 | .factKeys() 85 | .containsExactly("expected to have value", "but was absent") 86 | .inOrder(); 87 | assertThat(expected).factValue("expected to have value").isEqualTo("1337"); 88 | } 89 | 90 | @Test 91 | public void hasValue_FailingWithWrongValue() { 92 | AssertionError expected = 93 | expectFailure(whenTesting -> whenTesting.that(OptionalLong.of(1337L)).hasValue(42L)); 94 | assertThat(expected).factValue("value of").isEqualTo("optionalLong.getAsLong()"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/OptionalSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.assertThat; 19 | import static com.google.common.truth.ExpectFailure.expectFailure; 20 | import static com.google.common.truth.Truth.assertThat; 21 | import static org.junit.Assert.assertThrows; 22 | 23 | import java.util.Optional; 24 | import org.junit.Test; 25 | import org.junit.runner.RunWith; 26 | import org.junit.runners.JUnit4; 27 | 28 | /** 29 | * Tests for Java 8 {@link Optional} Subject. 30 | * 31 | * @author Christian Gruber (cgruber@israfil.net) 32 | */ 33 | @RunWith(JUnit4.class) 34 | public class OptionalSubjectTest { 35 | 36 | @Test 37 | public void isPresent() { 38 | assertThat(Optional.of("foo")).isPresent(); 39 | } 40 | 41 | @Test 42 | public void isPresentFailing() { 43 | AssertionError expected = 44 | expectFailure(whenTesting -> whenTesting.that(Optional.empty()).isPresent()); 45 | assertThat(expected).factKeys().containsExactly("expected to be present"); 46 | } 47 | 48 | @Test 49 | public void isPresentFailingNull() { 50 | AssertionError expected = 51 | expectFailure(whenTesting -> whenTesting.that((Optional) null).isPresent()); 52 | assertThat(expected) 53 | .factKeys() 54 | .containsExactly("expected present optional", "but was") 55 | .inOrder(); 56 | } 57 | 58 | @Test 59 | public void isEmpty() { 60 | assertThat(Optional.empty()).isEmpty(); 61 | } 62 | 63 | @Test 64 | public void isEmptyFailing() { 65 | AssertionError expected = 66 | expectFailure(whenTesting -> whenTesting.that(Optional.of("foo")).isEmpty()); 67 | assertThat(expected).factKeys().contains("expected to be empty"); 68 | assertThat(expected).factValue("but was present with value").isEqualTo("foo"); 69 | } 70 | 71 | @Test 72 | public void isEmptyFailingNull() { 73 | AssertionError expected = 74 | expectFailure(whenTesting -> whenTesting.that((Optional) null).isEmpty()); 75 | assertThat(expected).factKeys().containsExactly("expected empty optional", "but was").inOrder(); 76 | } 77 | 78 | @Test 79 | public void hasValue() { 80 | assertThat(Optional.of("foo")).hasValue("foo"); 81 | } 82 | 83 | @Test 84 | public void hasValue_failingWithEmpty() { 85 | AssertionError expected = 86 | expectFailure(whenTesting -> whenTesting.that(Optional.empty()).hasValue("foo")); 87 | assertThat(expected) 88 | .factKeys() 89 | .containsExactly("expected to have value", "but was empty") 90 | .inOrder(); 91 | assertThat(expected).factValue("expected to have value").isEqualTo("foo"); 92 | } 93 | 94 | @Test 95 | public void hasValue_npeWithNullParameter() { 96 | NullPointerException expected = 97 | assertThrows( 98 | NullPointerException.class, () -> assertThat(Optional.of("foo")).hasValue(null)); 99 | assertThat(expected).hasMessageThat().isEqualTo("Optional cannot have a null value."); 100 | } 101 | 102 | @Test 103 | public void hasValue_failingWithWrongValue() { 104 | AssertionError expected = 105 | expectFailure(whenTesting -> whenTesting.that(Optional.of("foo")).hasValue("boo")); 106 | assertThat(expected).factValue("value of").isEqualTo("optional.get()"); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/PathSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Truth.assertThat; 19 | 20 | import java.nio.file.Paths; 21 | import org.junit.Test; 22 | import org.junit.runner.RunWith; 23 | import org.junit.runners.JUnit4; 24 | 25 | @RunWith(JUnit4.class) 26 | public class PathSubjectTest { 27 | @Test 28 | public void basicEquality() { 29 | assertThat(Paths.get("foo")).isEqualTo(Paths.get("foo")); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/PrimitiveBooleanArraySubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.expectFailure; 19 | import static com.google.common.truth.FailureAssertions.assertFailureValue; 20 | import static com.google.common.truth.Truth.assertThat; 21 | 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.junit.runners.JUnit4; 25 | 26 | /** 27 | * Tests for {@link com.google.common.truth.PrimitiveBooleanArraySubject}. 28 | * 29 | * @author Christian Gruber (cgruber@israfil.net) 30 | */ 31 | @RunWith(JUnit4.class) 32 | public class PrimitiveBooleanArraySubjectTest { 33 | 34 | @Test 35 | public void isEqualTo() { 36 | assertThat(array(true, false, true)).isEqualTo(array(true, false, true)); 37 | } 38 | 39 | @SuppressWarnings("TruthSelfEquals") 40 | @Test 41 | public void isEqualTo_Same() { 42 | boolean[] same = array(true, false, true); 43 | assertThat(same).isEqualTo(same); 44 | } 45 | 46 | @Test 47 | public void asList() { 48 | assertThat(array(true, true, false)).asList().containsAtLeast(true, false); 49 | } 50 | 51 | @Test 52 | public void isEqualTo_Fail_UnequalOrdering() { 53 | AssertionError e = 54 | expectFailure( 55 | whenTesting -> 56 | whenTesting.that(array(true, false, true)).isEqualTo(array(false, true, true))); 57 | assertFailureValue(e, "differs at index", "[0]"); 58 | } 59 | 60 | @Test 61 | public void isEqualTo_Fail_NotAnArray() { 62 | expectFailure( 63 | whenTesting -> whenTesting.that(array(true, false, true)).isEqualTo(new Object())); 64 | } 65 | 66 | @Test 67 | public void isNotEqualTo_SameLengths() { 68 | assertThat(array(true, false)).isNotEqualTo(array(true, true)); 69 | } 70 | 71 | @Test 72 | public void isNotEqualTo_DifferentLengths() { 73 | assertThat(array(true, false)).isNotEqualTo(array(true, false, true)); 74 | } 75 | 76 | @Test 77 | public void isNotEqualTo_DifferentTypes() { 78 | assertThat(array(true, false)).isNotEqualTo(new Object()); 79 | } 80 | 81 | @Test 82 | public void isNotEqualTo_FailEquals() { 83 | expectFailure( 84 | whenTesting -> whenTesting.that(array(true, false)).isNotEqualTo(array(true, false))); 85 | } 86 | 87 | @SuppressWarnings("TruthSelfEquals") 88 | @Test 89 | public void isNotEqualTo_FailSame() { 90 | boolean[] same = array(true, false); 91 | expectFailure(whenTesting -> whenTesting.that(same).isNotEqualTo(same)); 92 | } 93 | 94 | private static boolean[] array(boolean... ts) { 95 | return ts; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/PrimitiveByteArraySubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.assertThat; 19 | import static com.google.common.truth.ExpectFailure.expectFailure; 20 | import static com.google.common.truth.FailureAssertions.assertFailureKeys; 21 | import static com.google.common.truth.FailureAssertions.assertFailureValueIndexed; 22 | import static com.google.common.truth.Truth.assertThat; 23 | 24 | import org.junit.Test; 25 | import org.junit.runner.RunWith; 26 | import org.junit.runners.JUnit4; 27 | 28 | /** 29 | * Tests for {@link com.google.common.truth.PrimitiveByteArraySubject}. 30 | * 31 | * @author Kurt Alfred Kluever 32 | */ 33 | @RunWith(JUnit4.class) 34 | // We intentionally test mismatches. 35 | // TODO(cpovirk): Maybe suppress at a finer scope. 36 | @SuppressWarnings("TruthIncompatibleType") 37 | public class PrimitiveByteArraySubjectTest { 38 | private static final byte BYTE_0 = (byte) 0; 39 | private static final byte BYTE_1 = (byte) 1; 40 | private static final byte BYTE_2 = (byte) 2; 41 | 42 | @Test 43 | public void isEqualTo() { 44 | assertThat(array(BYTE_0, BYTE_1)).isEqualTo(array(BYTE_0, BYTE_1)); 45 | } 46 | 47 | @SuppressWarnings("TruthSelfEquals") 48 | @Test 49 | public void isEqualTo_Same() { 50 | byte[] same = array(BYTE_0, BYTE_1); 51 | assertThat(same).isEqualTo(same); 52 | } 53 | 54 | @Test 55 | public void asList() { 56 | assertThat(array(BYTE_0, BYTE_1, BYTE_2)).asList().containsAtLeast(BYTE_0, BYTE_2); 57 | } 58 | 59 | @Test 60 | public void isEqualTo_Fail_UnequalOrdering() { 61 | AssertionError e = 62 | expectFailure( 63 | whenTesting -> 64 | whenTesting.that(array(BYTE_0, (byte) 123)).isEqualTo(array((byte) 123, BYTE_0))); 65 | assertFailureKeys(e, "expected", "but was", "expected", "but was"); 66 | assertFailureValueIndexed(e, "expected", 0, "7B00"); 67 | assertFailureValueIndexed(e, "but was", 0, "007B"); 68 | assertFailureValueIndexed(e, "expected", 1, "[123, 0]"); 69 | assertFailureValueIndexed(e, "but was", 1, "[0, 123]"); 70 | assertThat(e).isInstanceOf(ComparisonFailureWithFacts.class); 71 | } 72 | 73 | @Test 74 | public void isEqualTo_Fail_NotAnArray() { 75 | AssertionError e = 76 | expectFailure( 77 | whenTesting -> whenTesting.that(array(BYTE_0, BYTE_1)).isEqualTo(new int[] {})); 78 | assertFailureKeys(e, "expected", "but was", "wrong type", "expected", "but was"); 79 | assertFailureValueIndexed(e, "expected", 1, "int[]"); 80 | assertFailureValueIndexed(e, "but was", 1, "byte[]"); 81 | } 82 | 83 | @Test 84 | public void isNotEqualTo_SameLengths() { 85 | assertThat(array(BYTE_0, BYTE_1)).isNotEqualTo(array(BYTE_1, BYTE_0)); 86 | } 87 | 88 | @Test 89 | public void isNotEqualTo_DifferentLengths() { 90 | assertThat(array(BYTE_0, BYTE_1)).isNotEqualTo(array(BYTE_1, BYTE_0, BYTE_2)); 91 | } 92 | 93 | @Test 94 | public void isNotEqualTo_DifferentTypes() { 95 | assertThat(array(BYTE_0, BYTE_1)).isNotEqualTo(new Object()); 96 | } 97 | 98 | @Test 99 | public void isNotEqualTo_FailEquals() { 100 | expectFailure( 101 | whenTesting -> whenTesting.that(array(BYTE_0, BYTE_1)).isNotEqualTo(array(BYTE_0, BYTE_1))); 102 | } 103 | 104 | @SuppressWarnings("TruthSelfEquals") 105 | @Test 106 | public void isNotEqualTo_FailSame() { 107 | byte[] same = array(BYTE_0, BYTE_1); 108 | expectFailure(whenTesting -> whenTesting.that(same).isNotEqualTo(same)); 109 | } 110 | 111 | private static byte[] array(byte... ts) { 112 | return ts; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/PrimitiveCharArraySubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.expectFailure; 19 | import static com.google.common.truth.FailureAssertions.assertFailureKeys; 20 | import static com.google.common.truth.FailureAssertions.assertFailureValue; 21 | import static com.google.common.truth.FailureAssertions.assertFailureValueIndexed; 22 | import static com.google.common.truth.Truth.assertThat; 23 | 24 | import org.junit.Test; 25 | import org.junit.runner.RunWith; 26 | import org.junit.runners.JUnit4; 27 | 28 | /** 29 | * Tests for {@link com.google.common.truth.PrimitiveCharArraySubject}. 30 | * 31 | * @author Christian Gruber (cgruber@israfil.net) 32 | */ 33 | @RunWith(JUnit4.class) 34 | // We intentionally test mismatches. 35 | // TODO(cpovirk): Maybe suppress at a finer scope. 36 | @SuppressWarnings("TruthIncompatibleType") 37 | public class PrimitiveCharArraySubjectTest { 38 | 39 | @Test 40 | public void isEqualTo() { 41 | assertThat(array('a', 'q')).isEqualTo(array('a', 'q')); 42 | } 43 | 44 | @SuppressWarnings("TruthSelfEquals") 45 | @Test 46 | public void isEqualTo_Same() { 47 | char[] same = array('a', 'q'); 48 | assertThat(same).isEqualTo(same); 49 | } 50 | 51 | @Test 52 | public void asList() { 53 | assertThat(array('a', 'q', 'z')).asList().containsAtLeast('a', 'z'); 54 | } 55 | 56 | @Test 57 | public void isEqualTo_Fail_UnequalOrdering() { 58 | AssertionError e = 59 | expectFailure(whenTesting -> whenTesting.that(array('a', 'q')).isEqualTo(array('q', 'a'))); 60 | assertFailureKeys(e, "expected", "but was", "differs at index"); 61 | assertFailureValue(e, "expected", "[q, a]"); 62 | assertFailureValue(e, "but was", "[a, q]"); 63 | assertFailureValue(e, "differs at index", "[0]"); 64 | } 65 | 66 | @Test 67 | public void isEqualTo_Fail_DifferentKindOfArray() { 68 | AssertionError e = 69 | expectFailure(whenTesting -> whenTesting.that(array('a', 'q')).isEqualTo(new int[] {})); 70 | assertFailureKeys(e, "expected", "but was", "wrong type", "expected", "but was"); 71 | assertFailureValueIndexed(e, "expected", 1, "int[]"); 72 | assertFailureValueIndexed(e, "but was", 1, "char[]"); 73 | } 74 | 75 | @Test 76 | public void isNotEqualTo_SameLengths() { 77 | assertThat(array('a', 'q')).isNotEqualTo(array('q', 'a')); 78 | } 79 | 80 | @Test 81 | public void isNotEqualTo_DifferentLengths() { 82 | assertThat(array('a', 'q')).isNotEqualTo(array('q', 'a', 'b')); 83 | } 84 | 85 | @Test 86 | public void isNotEqualTo_DifferentTypes() { 87 | assertThat(array('a', 'q')).isNotEqualTo(new Object()); 88 | } 89 | 90 | @Test 91 | public void isNotEqualTo_FailEquals() { 92 | expectFailure(whenTesting -> whenTesting.that(array('a', 'q')).isNotEqualTo(array('a', 'q'))); 93 | } 94 | 95 | @SuppressWarnings("TruthSelfEquals") 96 | @Test 97 | public void isNotEqualTo_FailSame() { 98 | char[] same = array('a', 'q'); 99 | expectFailure(whenTesting -> whenTesting.that(same).isNotEqualTo(same)); 100 | } 101 | 102 | private static char[] array(char... ts) { 103 | return ts; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/PrimitiveLongArraySubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.expectFailure; 19 | import static com.google.common.truth.FailureAssertions.assertFailureKeys; 20 | import static com.google.common.truth.FailureAssertions.assertFailureValue; 21 | import static com.google.common.truth.FailureAssertions.assertFailureValueIndexed; 22 | import static com.google.common.truth.Truth.assertThat; 23 | 24 | import org.junit.Test; 25 | import org.junit.runner.RunWith; 26 | import org.junit.runners.JUnit4; 27 | 28 | /** 29 | * Tests for {@link com.google.common.truth.PrimitiveLongArraySubject}. 30 | * 31 | * @author Christian Gruber (cgruber@israfil.net) 32 | */ 33 | @RunWith(JUnit4.class) 34 | // We intentionally test mismatches. 35 | // TODO(cpovirk): Maybe suppress at a finer scope. 36 | @SuppressWarnings("TruthIncompatibleType") 37 | public class PrimitiveLongArraySubjectTest { 38 | 39 | @Test 40 | public void isEqualTo() { 41 | assertThat(array(2L, 5)).isEqualTo(array(2L, 5)); 42 | } 43 | 44 | @SuppressWarnings("TruthSelfEquals") 45 | @Test 46 | public void isEqualTo_Same() { 47 | long[] same = array(2L, 5); 48 | assertThat(same).isEqualTo(same); 49 | } 50 | 51 | @Test 52 | public void asList() { 53 | assertThat(array(5, 2, 9)).asList().containsAtLeast(2L, 9L); 54 | } 55 | 56 | @Test 57 | public void isEqualTo_Fail_UnequalOrdering() { 58 | AssertionError e = 59 | expectFailure(whenTesting -> whenTesting.that(array(2, 3)).isEqualTo(array(3, 2))); 60 | assertFailureKeys(e, "expected", "but was", "differs at index"); 61 | assertFailureValue(e, "expected", "[3, 2]"); 62 | assertFailureValue(e, "but was", "[2, 3]"); 63 | assertFailureValue(e, "differs at index", "[0]"); 64 | } 65 | 66 | @Test 67 | public void isEqualTo_Fail_NotAnArray() { 68 | AssertionError e = 69 | expectFailure(whenTesting -> whenTesting.that(array(2, 3, 4)).isEqualTo(new int[] {})); 70 | assertFailureKeys(e, "expected", "but was", "wrong type", "expected", "but was"); 71 | assertFailureValueIndexed(e, "expected", 1, "int[]"); 72 | assertFailureValueIndexed(e, "but was", 1, "long[]"); 73 | } 74 | 75 | @Test 76 | public void isNotEqualTo_SameLengths() { 77 | assertThat(array(2, 3)).isNotEqualTo(array(3, 2)); 78 | } 79 | 80 | @Test 81 | public void isNotEqualTo_DifferentLengths() { 82 | assertThat(array(2, 3)).isNotEqualTo(array(2, 3, 1)); 83 | } 84 | 85 | @Test 86 | public void isNotEqualTo_DifferentTypes() { 87 | assertThat(array(2, 3)).isNotEqualTo(new Object()); 88 | } 89 | 90 | @Test 91 | public void isNotEqualTo_FailEquals() { 92 | expectFailure(whenTesting -> whenTesting.that(array(2, 3)).isNotEqualTo(array(2, 3))); 93 | } 94 | 95 | @SuppressWarnings("TruthSelfEquals") 96 | @Test 97 | public void isNotEqualTo_FailSame() { 98 | long[] same = array(2, 3); 99 | expectFailure(whenTesting -> whenTesting.that(same).isNotEqualTo(same)); 100 | } 101 | 102 | private static long[] array(long... ts) { 103 | return ts; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/PrimitiveShortArraySubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.ExpectFailure.expectFailure; 19 | import static com.google.common.truth.FailureAssertions.assertFailureKeys; 20 | import static com.google.common.truth.FailureAssertions.assertFailureValue; 21 | import static com.google.common.truth.Truth.assertThat; 22 | 23 | import org.junit.Test; 24 | import org.junit.runner.RunWith; 25 | import org.junit.runners.JUnit4; 26 | 27 | /** 28 | * Tests for {@link PrimitiveShortArraySubject}. 29 | * 30 | * @author Christian Gruber (cgruber@israfil.net) 31 | */ 32 | @RunWith(JUnit4.class) 33 | public class PrimitiveShortArraySubjectTest { 34 | 35 | @Test 36 | public void isEqualTo() { 37 | assertThat(array(1, 0, 1)).isEqualTo(array(1, 0, 1)); 38 | } 39 | 40 | @SuppressWarnings("TruthSelfEquals") 41 | @Test 42 | public void isEqualTo_Same() { 43 | short[] same = array(1, 0, 1); 44 | assertThat(same).isEqualTo(same); 45 | } 46 | 47 | @Test 48 | public void asList() { 49 | assertThat(array(1, 1, 0)).asList().containsAtLeast((short) 1, (short) 0); 50 | } 51 | 52 | @Test 53 | public void asListWithoutCastingFails() { 54 | AssertionError e = 55 | expectFailure( 56 | whenTesting -> whenTesting.that(array(1, 1, 0)).asList().containsAtLeast(1, 0)); 57 | assertFailureKeys( 58 | e, 59 | "value of", 60 | "missing (2)", 61 | "though it did contain (3)", 62 | "---", 63 | "expected to contain at least", 64 | "but was"); 65 | } 66 | 67 | @Test 68 | public void isEqualTo_Fail_UnequalOrdering() { 69 | AssertionError e = 70 | expectFailure(whenTesting -> whenTesting.that(array(1, 0, 1)).isEqualTo(array(0, 1, 1))); 71 | assertFailureKeys(e, "expected", "but was", "differs at index"); 72 | assertFailureValue(e, "expected", "[0, 1, 1]"); 73 | assertFailureValue(e, "but was", "[1, 0, 1]"); 74 | assertFailureValue(e, "differs at index", "[0]"); 75 | } 76 | 77 | @Test 78 | public void isEqualTo_Fail_NotAnArray() { 79 | expectFailure(whenTesting -> whenTesting.that(array(1, 0, 1)).isEqualTo(new Object())); 80 | } 81 | 82 | @Test 83 | public void isNotEqualTo_SameLengths() { 84 | assertThat(array(1, 0)).isNotEqualTo(array(1, 1)); 85 | } 86 | 87 | @Test 88 | public void isNotEqualTo_DifferentLengths() { 89 | assertThat(array(1, 0)).isNotEqualTo(array(1, 0, 1)); 90 | } 91 | 92 | @Test 93 | public void isNotEqualTo_DifferentTypes() { 94 | assertThat(array(1, 0)).isNotEqualTo(new Object()); 95 | } 96 | 97 | @Test 98 | public void isNotEqualTo_FailEquals() { 99 | expectFailure(whenTesting -> whenTesting.that(array(1, 0)).isNotEqualTo(array(1, 0))); 100 | } 101 | 102 | @SuppressWarnings("TruthSelfEquals") 103 | @Test 104 | public void isNotEqualTo_FailSame() { 105 | short[] same = array(1, 0); 106 | expectFailure(whenTesting -> whenTesting.that(same).isNotEqualTo(same)); 107 | } 108 | 109 | private static short[] array(int a, int b, int c) { 110 | return new short[] {(short) a, (short) b, (short) c}; 111 | } 112 | 113 | private static short[] array(int a, int b) { 114 | return new short[] {(short) a, (short) b}; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/StackTraceCleanerJUnit3Test.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Truth.assertThat; 19 | 20 | import junit.framework.TestCase; 21 | 22 | /** 23 | * JUnit3 tests for {@link StackTraceCleaner}. 24 | * 25 | *

The "main" tests are in {@link StackTraceCleanerTest}. 26 | */ 27 | public class StackTraceCleanerJUnit3Test extends TestCase { 28 | public void testSimple() { 29 | try { 30 | assertThat(0).isEqualTo(1); 31 | throw new Error(); 32 | } catch (AssertionError failure) { 33 | assertThat(failure.getStackTrace()).hasLength(1); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/StandardSubjectBuilderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | import static com.google.common.truth.ExpectFailure.assertThat; 20 | import static com.google.common.truth.ExpectFailure.expectFailure; 21 | 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.junit.runners.JUnit4; 25 | 26 | /** Tests for {@link StandardSubjectBuilder}. */ 27 | @RunWith(JUnit4.class) 28 | public final class StandardSubjectBuilderTest { 29 | @Test 30 | public void failNoMessage() { 31 | AssertionError e = expectFailure(whenTesting -> whenTesting.fail()); 32 | assertThat(e).hasMessageThat().isEmpty(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/TestPlatform.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | final class TestPlatform { 20 | static boolean isGwt() { 21 | return false; 22 | } 23 | 24 | private TestPlatform() {} 25 | } 26 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/TruthAssertThatTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth; 17 | 18 | import static com.google.common.truth.Truth.assert_; 19 | import static java.util.Arrays.asList; 20 | 21 | import com.google.common.collect.FluentIterable; 22 | import com.google.common.collect.ImmutableSortedSet; 23 | import com.google.common.collect.Iterables; 24 | import com.google.common.collect.Ordering; 25 | import com.google.common.reflect.TypeToken; 26 | import java.lang.reflect.Method; 27 | import java.lang.reflect.Modifier; 28 | import org.junit.Test; 29 | import org.junit.runner.RunWith; 30 | import org.junit.runners.JUnit4; 31 | 32 | /** 33 | * Tests for the FEST-alike assertThat() entry point. 34 | * 35 | * @author Christian Gruber (cgruber@israfil.net) 36 | */ 37 | @RunWith(JUnit4.class) 38 | public class TruthAssertThatTest { 39 | private static TypeToken methodToReturnTypeToken(Method input) { 40 | return TypeToken.of(Iterables.getOnlyElement(asList(input.getParameterTypes()))); 41 | } 42 | 43 | @Test 44 | public void staticAssertThatMethodsMatchStandardSubjectBuilderInstanceMethods() { 45 | ImmutableSortedSet> verbTypes = 46 | FluentIterable.from(asList(StandardSubjectBuilder.class.getMethods())) 47 | .filter(input -> input.getName().equals("that")) 48 | .transform(TruthAssertThatTest::methodToReturnTypeToken) 49 | .toSortedSet(Ordering.usingToString()); 50 | ImmutableSortedSet> truthTypes = 51 | FluentIterable.from(asList(Truth.class.getMethods())) 52 | .filter( 53 | input -> 54 | input.getName().equals("assertThat") && Modifier.isStatic(input.getModifiers())) 55 | .transform(TruthAssertThatTest::methodToReturnTypeToken) 56 | .toSortedSet(Ordering.usingToString()); 57 | 58 | assert_().that(verbTypes).isNotEmpty(); 59 | assert_().that(truthTypes).isNotEmpty(); 60 | assert_().that(truthTypes).containsExactlyElementsIn(verbTypes); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/extension/Employee.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth.extension; 17 | 18 | import com.google.auto.value.AutoValue; 19 | 20 | /** Represents an employee. */ 21 | @AutoValue 22 | public abstract class Employee { 23 | public static Employee create( 24 | String username, long id, String name, Location location, boolean isCeo) { 25 | return new AutoValue_Employee(username, id, name, location, isCeo); 26 | } 27 | 28 | abstract String username(); 29 | 30 | abstract long id(); 31 | 32 | abstract String name(); 33 | 34 | abstract Location location(); 35 | 36 | abstract boolean isCeo(); 37 | 38 | public enum Location { 39 | MTV, 40 | PIT, 41 | CHI, 42 | NYC 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/extension/EmployeeSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth.extension; 17 | 18 | import static com.google.common.truth.Fact.simpleFact; 19 | import static com.google.common.truth.Truth.assertAbout; 20 | 21 | import com.google.common.truth.ComparableSubject; 22 | import com.google.common.truth.FailureMetadata; 23 | import com.google.common.truth.LongSubject; 24 | import com.google.common.truth.StringSubject; 25 | import com.google.common.truth.Subject; 26 | import org.jspecify.annotations.Nullable; 27 | 28 | /** 29 | * A Truth subject for {@link Employee}. 30 | * 31 | * @author Kurt Alfred Kluever (kak@google.com) 32 | */ 33 | public final class EmployeeSubject extends Subject { 34 | 35 | // User-defined entry point 36 | public static EmployeeSubject assertThat(@Nullable Employee employee) { 37 | return assertAbout(employees()).that(employee); 38 | } 39 | 40 | // Static method for getting the subject factory (for use with assertAbout()) 41 | public static Factory employees() { 42 | return EmployeeSubject::new; 43 | } 44 | 45 | private final Employee actual; 46 | 47 | private EmployeeSubject(FailureMetadata failureMetadata, @Nullable Employee subject) { 48 | super(failureMetadata, subject); 49 | this.actual = subject; 50 | } 51 | 52 | // User-defined test assertion SPI below this point 53 | 54 | public void hasName(String name) { 55 | name().isEqualTo(name); 56 | } 57 | 58 | public void hasUsername(String username) { 59 | username().isEqualTo(username); 60 | } 61 | 62 | public void hasId(long id) { 63 | id().isEqualTo(id); 64 | } 65 | 66 | public void hasLocation(Employee.Location location) { 67 | location().isEqualTo(location); 68 | } 69 | 70 | public void isCeo() { 71 | if (!actual.isCeo()) { 72 | failWithActual(simpleFact("expected to be CEO")); 73 | } 74 | } 75 | 76 | public void isNotCeo() { 77 | if (actual.isCeo()) { 78 | failWithActual(simpleFact("expected not to be CEO")); 79 | } 80 | } 81 | 82 | // Chained subjects methods below this point 83 | 84 | public StringSubject name() { 85 | return check("name()").that(actual.name()); 86 | } 87 | 88 | public StringSubject username() { 89 | return check("username()").that(actual.username()); 90 | } 91 | 92 | public LongSubject id() { 93 | return check("id()").that(actual.id()); 94 | } 95 | 96 | public ComparableSubject location() { 97 | return check("location()").that(actual.location()); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/extension/EmployeeSubjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth.extension; 17 | 18 | import static com.google.common.truth.ExpectFailure.assertThat; 19 | import static com.google.common.truth.ExpectFailure.expectFailureAbout; 20 | import static com.google.common.truth.extension.EmployeeSubject.assertThat; 21 | import static com.google.common.truth.extension.EmployeeSubject.employees; 22 | 23 | import com.google.common.truth.ExpectFailure.SimpleSubjectBuilderCallback; 24 | import com.google.common.truth.extension.Employee.Location; 25 | import com.google.errorprone.annotations.CanIgnoreReturnValue; 26 | import org.junit.Test; 27 | import org.junit.runner.RunWith; 28 | import org.junit.runners.JUnit4; 29 | 30 | @RunWith(JUnit4.class) 31 | public final class EmployeeSubjectTest { 32 | 33 | // Note: not real employee IDs :-) 34 | 35 | private static final Employee KURT = 36 | Employee.create("kak", 37802, "Kurt Alfred Kluever", Location.NYC, /* isCeo= */ false); 37 | 38 | @Test 39 | public void id() { 40 | assertThat(KURT).hasId(37802); 41 | expectFailure(whenTesting -> whenTesting.that(KURT).hasId(12345)); 42 | } 43 | 44 | @Test 45 | public void name() { 46 | assertThat(KURT).hasName("Kurt Alfred Kluever"); 47 | expectFailure(whenTesting -> whenTesting.that(KURT).hasName("Sundar Pichai")); 48 | } 49 | 50 | @Test 51 | public void username() { 52 | assertThat(KURT).hasUsername("kak"); 53 | // Here's an example of asserting on the failure message. 54 | // Note that it uses the assertThat method from ExpectFailure. 55 | AssertionError failure = 56 | expectFailure(whenTesting -> whenTesting.that(KURT).hasUsername("sundar")); 57 | assertThat(failure).factValue("value of").isEqualTo("employee.username()"); 58 | } 59 | 60 | @CanIgnoreReturnValue 61 | private static AssertionError expectFailure( 62 | SimpleSubjectBuilderCallback callback) { 63 | return expectFailureAbout(employees(), callback); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/extension/FakeHrDatabase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth.extension; 17 | 18 | import static com.google.common.base.Preconditions.checkNotNull; 19 | import static com.google.common.base.Preconditions.checkState; 20 | 21 | import com.google.common.collect.ImmutableSet; 22 | import com.google.common.truth.extension.Employee.Location; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | /** In-memory implementation of {@link HrDatabase}, suitable for testing. */ 27 | public final class FakeHrDatabase implements HrDatabase { 28 | private final Map employees = new HashMap<>(); 29 | 30 | public void put(Employee employee) { 31 | employees.put(employee.id(), employee); 32 | } 33 | 34 | @Override 35 | public Employee get(long id) { 36 | return employees.get(id); 37 | } 38 | 39 | @Override 40 | public void relocate(long id, Location location) { 41 | checkNotNull(location); 42 | Employee old = get(id); 43 | checkState(old != null, "No employee found with ID %s", id); 44 | employees.put(id, Employee.create(old.username(), old.id(), old.name(), location, old.isCeo())); 45 | } 46 | 47 | @Override 48 | public ImmutableSet getByLocation(Location location) { 49 | checkNotNull(location); 50 | ImmutableSet.Builder result = ImmutableSet.builder(); 51 | for (Employee employee : employees.values()) { 52 | if (employee.location() == location) { 53 | result.add(employee); 54 | } 55 | } 56 | return result.build(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/extension/FakeHrDatabaseTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth.extension; 17 | 18 | import static com.google.common.truth.Truth.assertThat; 19 | import static com.google.common.truth.extension.EmployeeSubject.assertThat; 20 | 21 | import com.google.common.truth.extension.Employee.Location; 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.junit.runners.JUnit4; 25 | 26 | @RunWith(JUnit4.class) 27 | public final class FakeHrDatabaseTest { 28 | 29 | // Note: not real employee IDs :-) 30 | 31 | private static final Employee KURT = 32 | Employee.create("kak", 37802, "Kurt Alfred Kluever", Location.NYC, /* isCeo= */ false); 33 | 34 | private static final Employee SUNDAR = 35 | Employee.create("sundar", 5243, "Sundar Pichai", Location.MTV, /* isCeo= */ true); 36 | 37 | // Notice that we static import two different assertThat methods. 38 | 39 | // These assertions use the EmployeeSubject.assertThat(Employee) overload and the 40 | // EmployeeSubject-specific methods. 41 | 42 | @Test 43 | public void relocatePresent() { 44 | FakeHrDatabase db = new FakeHrDatabase(); 45 | db.put(KURT); 46 | db.relocate(KURT.id(), Location.MTV); 47 | Employee movedKurt = db.get(KURT.id()); 48 | assertThat(movedKurt).hasLocation(Location.MTV); 49 | assertThat(movedKurt).hasUsername("kak"); 50 | } 51 | 52 | // These assertions use the EmployeeSubject.assertThat(Employee) overload but the assertion 53 | // methods inherited from Subject. 54 | 55 | @Test 56 | public void getPresent() { 57 | FakeHrDatabase db = new FakeHrDatabase(); 58 | db.put(KURT); 59 | assertThat(db.get(KURT.id())).isEqualTo(KURT); 60 | } 61 | 62 | @Test 63 | public void getAbsent() { 64 | FakeHrDatabase db = new FakeHrDatabase(); 65 | db.put(KURT); 66 | assertThat(db.get(SUNDAR.id())).isNull(); 67 | } 68 | 69 | // These assertions use Truth.assertThat() overloads 70 | 71 | @Test 72 | public void getByLocation() { 73 | FakeHrDatabase db = new FakeHrDatabase(); 74 | db.put(KURT); 75 | assertThat(db.getByLocation(Location.NYC)).containsExactly(KURT); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/extension/HrDatabase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth.extension; 17 | 18 | import com.google.common.collect.ImmutableSet; 19 | import com.google.common.truth.extension.Employee.Location; 20 | 21 | /** 22 | * Service for accessing human resources data. 23 | * 24 | *

This class (and all the classes in this package) are just a demonstration of how to write and 25 | * use a custom Truth subject. The only implementation of {@code HrDatabase} is {@link 26 | * FakeHrDatabase}, and the only place we use it is in its own test, whose real purpose is to 27 | * demonstrate how to use a custom Truth subject. 28 | */ 29 | public interface HrDatabase { 30 | Employee get(long id); 31 | 32 | void relocate(long id, Location location); 33 | 34 | ImmutableSet getByLocation(Location location); 35 | } 36 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/gwt/TruthTest.gwt.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/no_junit_test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euE 4 | 5 | # Just run the provided java_binary. 6 | "$1" 7 | -------------------------------------------------------------------------------- /core/src/test/java/com/google/common/truth/super/com/google/common/truth/TestPlatform.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth; 18 | 19 | final class TestPlatform { 20 | static boolean isGwt() { 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /extensions/java8/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.google.truth.extensions 9 | truth-extensions-parent 10 | HEAD-SNAPSHOT 11 | 12 | truth-java8-extension 13 | Obsolete Truth Extension for Java8 14 | 15 | Obsolete, empty artifact that merely pulls in the main `truth` artifact: Assertions for Java 8 types are now part of that main artifact. 16 | 17 | 18 | 19 | com.google.truth 20 | truth 21 | 22 | 23 | 24 | 25 | 26 | ../.. 27 | 28 | LICENSE 29 | 30 | META-INF 31 | 32 | 33 | 34 | 35 | maven-javadoc-plugin 36 | 37 | 38 | maven-compiler-plugin 39 | 40 | 41 | maven-jar-plugin 42 | 43 | 44 | attach-gwt-sources 45 | post-integration-test 46 | jar 47 | 48 | gwt 49 | src/main/java 50 | 51 | **/*.java 52 | **/*.gwt.xml 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /extensions/liteproto/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.google.truth.extensions 9 | truth-extensions-parent 10 | HEAD-SNAPSHOT 11 | 12 | truth-liteproto-extension 13 | Truth Extension for Lite Protocol Buffers 14 | 15 | An extension for the Truth test assertion framework supporting the Lite 16 | version of Protocol Buffers. 17 | 18 | 19 | 20 | com.google.truth 21 | truth 22 | 23 | 24 | com.google.guava 25 | guava 26 | 27 | 28 | org.jspecify 29 | jspecify 30 | 31 | 32 | com.google.auto.value 33 | auto-value-annotations 34 | 35 | 36 | com.google.errorprone 37 | error_prone_annotations 38 | 39 | 40 | com.google.protobuf 41 | protobuf-lite 42 | 43 | true 44 | 45 | 46 | 47 | 48 | 49 | ../.. 50 | 51 | LICENSE 52 | 53 | META-INF 54 | 55 | 56 | 57 | 58 | kr.motd.maven 59 | os-maven-plugin 60 | ${os-maven-plugin.version} 61 | 62 | 63 | 64 | 65 | 66 | maven-javadoc-plugin 67 | 68 | 69 | org.xolstice.maven.plugins 70 | protobuf-maven-plugin 71 | 72 | com.google.protobuf:protoc:${protobuf-lite.protoc.version}:exe:${os.detected.classifier} 73 | 74 | test_message_lite2.proto 75 | test_message_lite3.proto 76 | 77 | 78 | 79 | 80 | build-test-protos 81 | generate-test-sources 82 | 83 | test-compile 84 | 85 | 86 | 87 | 88 | 89 | maven-compiler-plugin 90 | 91 | 92 | 93 | com.google.auto.value 94 | auto-value 95 | ${auto-value.version} 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /extensions/liteproto/src/main/java/com/google/common/truth/extensions/proto/LiteProtoTruth.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.extensions.proto; 18 | 19 | import static com.google.common.truth.Truth.assertAbout; 20 | 21 | import com.google.common.truth.Subject; 22 | import com.google.errorprone.annotations.CheckReturnValue; 23 | import com.google.protobuf.MessageLite; 24 | import org.jspecify.annotations.Nullable; 25 | 26 | /** 27 | * A set of static methods to begin a Truth assertion chain for the lite version of protocol 28 | * buffers. 29 | * 30 | *

This class implements a subset of what {@code ProtoTruth} provides, so if you are already 31 | * using {@code ProtoTruth}, you should not import this class. {@code LiteProtoTruth} is only useful 32 | * if you cannot depend on {@code ProtoTruth} for dependency management reasons. 33 | * 34 | *

Note: Usage of different failure strategies such as assume and expect should 35 | * rely on {@linkplain com.google.common.truth.StandardSubjectBuilder#about(Subject.Factory) 36 | * about(liteProtos())} to begin a chain with those alternative behaviors. 37 | */ 38 | @CheckReturnValue 39 | public final class LiteProtoTruth { 40 | public static LiteProtoSubject assertThat(@Nullable MessageLite messageLite) { 41 | return assertAbout(liteProtos()).that(messageLite); 42 | } 43 | 44 | public static Subject.Factory liteProtos() { 45 | return LiteProtoSubject.liteProtos(); 46 | } 47 | 48 | private LiteProtoTruth() {} 49 | } 50 | -------------------------------------------------------------------------------- /extensions/liteproto/src/test/proto/test_message_lite2.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto2"; 2 | 3 | package com.google.common.truth.extensions.proto; 4 | 5 | option optimize_for = LITE_RUNTIME; 6 | 7 | option java_package = "com.google.common.truth.extensions.proto"; 8 | option java_multiple_files = true; 9 | 10 | message TestMessageLite2 { 11 | optional int32 optional_int = 1; 12 | 13 | message SubMessage { 14 | optional string optional_string = 1; 15 | } 16 | optional SubMessage sub_message = 2; 17 | } 18 | 19 | message OtherTestMessageLite2 { 20 | optional int32 optional_int = 1; 21 | } 22 | 23 | message TestMessageLite2WithRequiredFields { 24 | required int32 required_int = 1; 25 | optional string optional_string = 2; 26 | } 27 | -------------------------------------------------------------------------------- /extensions/liteproto/src/test/proto/test_message_lite3.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package com.google.common.truth.extensions.proto; 4 | 5 | option optimize_for = LITE_RUNTIME; 6 | 7 | option java_package = "com.google.common.truth.extensions.proto"; 8 | option java_multiple_files = true; 9 | 10 | message TestMessageLite3 { 11 | int32 optional_int = 1; 12 | 13 | message SubMessage { 14 | string optional_string = 1; 15 | } 16 | SubMessage sub_message = 2; 17 | } 18 | 19 | message OtherTestMessageLite3 { 20 | int32 optional_int = 1; 21 | } 22 | -------------------------------------------------------------------------------- /extensions/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.google.truth 9 | truth-parent 10 | HEAD-SNAPSHOT 11 | 12 | com.google.truth.extensions 13 | truth-extensions-parent 14 | pom 15 | Truth Extensions (Parent) 16 | 17 | Parent metdata for a collection of Truth extensions, Subjects, utilities for 18 | the Truth assertion framework. 19 | 20 | 21 | java8 22 | re2j 23 | liteproto 24 | proto 25 | 26 | 27 | -------------------------------------------------------------------------------- /extensions/proto/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.google.truth.extensions 9 | truth-extensions-parent 10 | HEAD-SNAPSHOT 11 | 12 | truth-proto-extension 13 | Truth Extension for Protocol Buffers 14 | 15 | An extension for the Truth test assertion framework supporting 16 | Protocol Buffers. 17 | 18 | 19 | 20 | com.google.truth 21 | truth 22 | 23 | 24 | com.google.truth.extensions 25 | truth-liteproto-extension 26 | 27 | 28 | com.google.guava 29 | guava 30 | 31 | 32 | org.jspecify 33 | jspecify 34 | 35 | 36 | com.google.auto.value 37 | auto-value-annotations 38 | 39 | 40 | com.google.errorprone 41 | error_prone_annotations 42 | 43 | 44 | com.google.protobuf 45 | protobuf-java 46 | 47 | 48 | 49 | 50 | 51 | ../.. 52 | 53 | LICENSE 54 | 55 | META-INF 56 | 57 | 58 | 59 | 60 | kr.motd.maven 61 | os-maven-plugin 62 | ${os-maven-plugin.version} 63 | 64 | 65 | 66 | 67 | 68 | maven-javadoc-plugin 69 | 70 | 71 | org.xolstice.maven.plugins 72 | protobuf-maven-plugin 73 | 74 | com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier} 75 | 76 | test_message2.proto 77 | test_message3.proto 78 | 79 | 80 | 81 | 82 | build-test-protos 83 | generate-test-sources 84 | 85 | test-compile 86 | 87 | 88 | 89 | 90 | 91 | maven-compiler-plugin 92 | 93 | 94 | 95 | com.google.auto.value 96 | auto-value 97 | ${auto-value.version} 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /extensions/proto/src/main/java/com/google/common/truth/extensions/proto/AnyUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.extensions.proto; 18 | 19 | import com.google.common.base.Optional; 20 | import com.google.common.base.Preconditions; 21 | import com.google.protobuf.Any; 22 | import com.google.protobuf.ByteString; 23 | import com.google.protobuf.Descriptors.Descriptor; 24 | import com.google.protobuf.Descriptors.FieldDescriptor; 25 | import com.google.protobuf.DynamicMessage; 26 | import com.google.protobuf.ExtensionRegistry; 27 | import com.google.protobuf.InvalidProtocolBufferException; 28 | import com.google.protobuf.Message; 29 | import com.google.protobuf.TypeRegistry; 30 | 31 | /** Helper methods for working with Any protos. */ 32 | class AnyUtils { 33 | private static final FieldDescriptor TYPE_URL_FIELD_DESCRIPTOR = 34 | Any.getDescriptor().findFieldByNumber(Any.TYPE_URL_FIELD_NUMBER); 35 | 36 | static FieldDescriptor typeUrlFieldDescriptor() { 37 | return TYPE_URL_FIELD_DESCRIPTOR; 38 | } 39 | 40 | private static final SubScopeId TYPE_URL_SUB_SCOPE_ID = SubScopeId.of(TYPE_URL_FIELD_DESCRIPTOR); 41 | 42 | static SubScopeId typeUrlSubScopeId() { 43 | return TYPE_URL_SUB_SCOPE_ID; 44 | } 45 | 46 | private static final FieldDescriptor VALUE_FIELD_DESCRIPTOR = 47 | Any.getDescriptor().findFieldByNumber(Any.VALUE_FIELD_NUMBER); 48 | 49 | static FieldDescriptor valueFieldDescriptor() { 50 | return VALUE_FIELD_DESCRIPTOR; 51 | } 52 | 53 | private static final SubScopeId VALUE_SUB_SCOPE_ID = SubScopeId.of(VALUE_FIELD_DESCRIPTOR); 54 | 55 | static SubScopeId valueSubScopeId() { 56 | return VALUE_SUB_SCOPE_ID; 57 | } 58 | 59 | private static final TypeRegistry DEFAULT_TYPE_REGISTRY = TypeRegistry.getEmptyTypeRegistry(); 60 | 61 | static TypeRegistry defaultTypeRegistry() { 62 | return DEFAULT_TYPE_REGISTRY; 63 | } 64 | 65 | private static final ExtensionRegistry DEFAULT_EXTENSION_REGISTRY = 66 | ExtensionRegistry.getEmptyRegistry(); 67 | 68 | static ExtensionRegistry defaultExtensionRegistry() { 69 | return DEFAULT_EXTENSION_REGISTRY; 70 | } 71 | 72 | /** Unpack an `Any` proto using the given TypeRegistry and ExtensionRegistry. */ 73 | static Optional unpack( 74 | Message any, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) { 75 | Preconditions.checkArgument( 76 | any.getDescriptorForType().equals(Any.getDescriptor()), 77 | "Expected type google.protobuf.Any, but was: %s", 78 | any.getDescriptorForType().getFullName()); 79 | 80 | String typeUrl = (String) any.getField(typeUrlFieldDescriptor()); 81 | ByteString value = (ByteString) any.getField(valueFieldDescriptor()); 82 | 83 | try { 84 | Descriptor descriptor = typeRegistry.getDescriptorForTypeUrl(typeUrl); 85 | if (descriptor == null) { 86 | return Optional.absent(); 87 | } 88 | 89 | Message defaultMessage = DynamicMessage.parseFrom(descriptor, value, extensionRegistry); 90 | return Optional.of(defaultMessage); 91 | } catch (InvalidProtocolBufferException e) { 92 | return Optional.absent(); 93 | } 94 | } 95 | 96 | private AnyUtils() {} 97 | } 98 | -------------------------------------------------------------------------------- /extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldDescriptorValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.extensions.proto; 18 | 19 | import static com.google.common.base.Preconditions.checkArgument; 20 | 21 | import com.google.protobuf.Descriptors.FieldDescriptor; 22 | import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; 23 | 24 | /** Various validators, to ensure that explicit comparison settings made by the user make sense. */ 25 | enum FieldDescriptorValidator { 26 | ALLOW_ALL() { 27 | @Override 28 | void validate(FieldDescriptor fieldDescriptor) {} 29 | }, 30 | IS_FIELD_WITH_ABSENCE() { 31 | @Override 32 | void validate(FieldDescriptor fieldDescriptor) { 33 | checkArgument( 34 | !fieldDescriptor.isRepeated(), 35 | "%s is a repeated field; repeated fields cannot be absent, only empty", 36 | fieldDescriptor); 37 | 38 | checkArgument( 39 | fieldDescriptor.hasPresence(), 40 | "%s is a field without presence; it cannot be absent", 41 | fieldDescriptor); 42 | } 43 | }, 44 | IS_FIELD_WITH_ORDER() { 45 | @Override 46 | void validate(FieldDescriptor fieldDescriptor) { 47 | checkArgument( 48 | !fieldDescriptor.isMapField(), "%s is a map field; it has no order", fieldDescriptor); 49 | checkArgument( 50 | fieldDescriptor.isRepeated(), 51 | "%s is not a repeated field; it has no order", 52 | fieldDescriptor); 53 | } 54 | }, 55 | IS_FIELD_WITH_EXTRA_ELEMENTS() { 56 | @Override 57 | void validate(FieldDescriptor fieldDescriptor) { 58 | checkArgument( 59 | fieldDescriptor.isRepeated(), 60 | "%s is not a repeated field or a map field; it cannot contain extra elements", 61 | fieldDescriptor); 62 | } 63 | }, 64 | IS_DOUBLE_FIELD() { 65 | @Override 66 | void validate(FieldDescriptor fieldDescriptor) { 67 | checkArgument( 68 | fieldDescriptor.getJavaType() == JavaType.DOUBLE, 69 | "%s is not a double field", 70 | fieldDescriptor); 71 | } 72 | }, 73 | IS_FLOAT_FIELD() { 74 | @Override 75 | void validate(FieldDescriptor fieldDescriptor) { 76 | checkArgument( 77 | fieldDescriptor.getJavaType() == JavaType.FLOAT, 78 | "%s is not a float field", 79 | fieldDescriptor); 80 | } 81 | }; 82 | 83 | /** Validates the given {@link FieldDescriptor} according to this instance's rules. */ 84 | abstract void validate(FieldDescriptor fieldDescriptor); 85 | } 86 | -------------------------------------------------------------------------------- /extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogicContainer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.extensions.proto; 18 | 19 | import com.google.protobuf.Descriptors.Descriptor; 20 | 21 | /** 22 | * Critical methods for anything which is, or contains a {@link FieldScopeLogic}. 23 | * 24 | *

All such containers must support invoking {@code subScope} for scoping to sub-messages, and 25 | * all must support validation of integer field numbers. 26 | */ 27 | interface FieldScopeLogicContainer> { 28 | 29 | /** Returns the analog of {@link FieldScopeLogic#subScope} for this container. */ 30 | T subScope(Descriptor rootDescriptor, SubScopeId subScopeId); 31 | 32 | /** Validates explicitly specified fields for this container. */ 33 | void validate(Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator); 34 | } 35 | -------------------------------------------------------------------------------- /extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.extensions.proto; 18 | 19 | /** 20 | * Whether or not a sub-message tree is considered part of the enclosing scope. 21 | * 22 | *

This enables {@link FieldScopeLogic}s and the {@code ProtoTruthMessageDifferencer} to work 23 | * together on traversing a message, instead of either class doing redundant work. The need for 24 | * {@code NONRECURSIVE} arises from sub-messages. For example: 25 | * 26 | *

27 | * message Foo { 28 | * optional Bar bar = 1; 29 | * } 30 | * 31 | * message Bar { 32 | * optional Baz baz = 1; 33 | * } 34 | * 35 | * message Baz { 36 | * optional string name = 1; 37 | * optional int64 id = 2; 38 | * } 39 | * 40 | * 41 | *

A {@link FieldScopeLogic} which excludes everything except 'Baz.name', when asked if 'Foo.bar' 42 | * should be ignored, cannot know whether it should be excluded or not without scanning all of 43 | * 'Foo.bar' for Baz submessages, and whether they have the name field set. We could scan the entire 44 | * message to make this decision, but the message differencer will be scanning anyway if we choose 45 | * not to excluded it, which creates redundant work. {@code NONRECURSIVE} is the solution to this 46 | * problem: The logic defers the decision back to the message differencer, which proceeds with the 47 | * complete scan of 'Foo.bar', and excludes the entire submessage if and only if nothing in 48 | * 'Foo.bar' was determined to be un-excludable. 49 | */ 50 | enum FieldScopeResult { 51 | /** This field is included in this scope, but children might be excludable. */ 52 | INCLUDED_NONRECURSIVELY(/* included= */ true, /* recursive= */ false), 53 | /** This field and all its children are included in the scope. */ 54 | INCLUDED_RECURSIVELY(/* included= */ true, /* recursive= */ true), 55 | /** This field is excluded from the scope, but children might be includable. */ 56 | EXCLUDED_NONRECURSIVELY(/* included= */ false, /* recursive= */ false), 57 | /** This field and all its children are excluded from the scope. */ 58 | EXCLUDED_RECURSIVELY(/* included= */ false, /* recursive= */ true); 59 | 60 | public static FieldScopeResult of(boolean included, boolean recursively) { 61 | if (included) { 62 | return recursively ? INCLUDED_RECURSIVELY : INCLUDED_NONRECURSIVELY; 63 | } else { 64 | return recursively ? EXCLUDED_RECURSIVELY : EXCLUDED_NONRECURSIVELY; 65 | } 66 | } 67 | 68 | private final boolean included; 69 | private final boolean recursive; 70 | 71 | FieldScopeResult(boolean included, boolean recursive) { 72 | this.included = included; 73 | this.recursive = recursive; 74 | } 75 | 76 | /** Whether this field should be included or not. */ 77 | boolean included() { 78 | return included; 79 | } 80 | 81 | /** 82 | * Whether this field's sub-children should also be unilaterally included or excluded, conditional 83 | * on {@link #included()} 84 | */ 85 | boolean recursive() { 86 | return recursive; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /extensions/proto/src/main/java/com/google/common/truth/extensions/proto/ProtoSubjectBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.extensions.proto; 18 | 19 | import com.google.common.collect.Multimap; 20 | import com.google.common.truth.CustomSubjectBuilder; 21 | import com.google.common.truth.FailureMetadata; 22 | import com.google.protobuf.Message; 23 | import com.google.protobuf.MessageLite; 24 | import java.util.Map; 25 | import org.jspecify.annotations.Nullable; 26 | 27 | /** 28 | * {@link CustomSubjectBuilder} which aggregates all Proto-related {@link 29 | * com.google.common.truth.Subject} classes into a single place. 30 | * 31 | *

To obtain an instance, call {@code assertAbout(ProtoTruth.protos())}. 32 | */ 33 | public final class ProtoSubjectBuilder extends CustomSubjectBuilder { 34 | 35 | /** Factory for ProtoSubjectBuilder. */ 36 | private static class Factory implements CustomSubjectBuilder.Factory { 37 | private static final Factory INSTANCE = new Factory(); 38 | 39 | @Override 40 | public ProtoSubjectBuilder createSubjectBuilder(FailureMetadata failureMetadata) { 41 | return new ProtoSubjectBuilder(failureMetadata); 42 | } 43 | } 44 | 45 | static CustomSubjectBuilder.Factory factory() { 46 | return Factory.INSTANCE; 47 | } 48 | 49 | private ProtoSubjectBuilder(FailureMetadata failureMetadata) { 50 | super(failureMetadata); 51 | } 52 | 53 | public LiteProtoSubject that(@Nullable MessageLite messageLite) { 54 | return new LiteProtoSubject(metadata(), messageLite); 55 | } 56 | 57 | public ProtoSubject that(@Nullable Message message) { 58 | return new ProtoSubject(metadata(), message); 59 | } 60 | 61 | public IterableOfProtosSubject that(@Nullable Iterable messages) { 62 | return new IterableOfProtosSubject(metadata(), messages); 63 | } 64 | 65 | public MapWithProtoValuesSubject that(@Nullable Map map) { 66 | return new MapWithProtoValuesSubject<>(metadata(), map); 67 | } 68 | 69 | public MultimapWithProtoValuesSubject that(@Nullable Multimap map) { 70 | return new MultimapWithProtoValuesSubject<>(metadata(), map); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /extensions/proto/src/main/java/com/google/common/truth/extensions/proto/SubScopeId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.extensions.proto; 18 | 19 | import com.google.auto.value.AutoOneOf; 20 | import com.google.protobuf.Descriptors.Descriptor; 21 | import com.google.protobuf.Descriptors.FieldDescriptor; 22 | 23 | @AutoOneOf(SubScopeId.Kind.class) 24 | abstract class SubScopeId { 25 | enum Kind { 26 | FIELD_DESCRIPTOR, 27 | UNKNOWN_FIELD_DESCRIPTOR, 28 | UNPACKED_ANY_VALUE_TYPE; 29 | } 30 | 31 | abstract Kind kind(); 32 | 33 | abstract FieldDescriptor fieldDescriptor(); 34 | 35 | abstract UnknownFieldDescriptor unknownFieldDescriptor(); 36 | 37 | abstract Descriptor unpackedAnyValueType(); 38 | 39 | /** Returns a short, human-readable version of this identifier. */ 40 | final String shortName() { 41 | switch (kind()) { 42 | case FIELD_DESCRIPTOR: 43 | return fieldDescriptor().isExtension() 44 | ? "[" + fieldDescriptor() + "]" 45 | : fieldDescriptor().getName(); 46 | case UNKNOWN_FIELD_DESCRIPTOR: 47 | return String.valueOf(unknownFieldDescriptor().fieldNumber()); 48 | case UNPACKED_ANY_VALUE_TYPE: 49 | return AnyUtils.valueFieldDescriptor().getName(); 50 | } 51 | throw new AssertionError(kind()); 52 | } 53 | 54 | static SubScopeId of(FieldDescriptor fieldDescriptor) { 55 | return AutoOneOf_SubScopeId.fieldDescriptor(fieldDescriptor); 56 | } 57 | 58 | static SubScopeId of(UnknownFieldDescriptor unknownFieldDescriptor) { 59 | return AutoOneOf_SubScopeId.unknownFieldDescriptor(unknownFieldDescriptor); 60 | } 61 | 62 | static SubScopeId ofUnpackedAnyValueType(Descriptor unpackedAnyValueType) { 63 | return AutoOneOf_SubScopeId.unpackedAnyValueType(unpackedAnyValueType); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /extensions/proto/src/main/java/com/google/common/truth/extensions/proto/UnknownFieldDescriptor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.extensions.proto; 18 | 19 | import com.google.auto.value.AutoValue; 20 | import com.google.common.collect.ImmutableList; 21 | import com.google.protobuf.UnknownFieldSet; 22 | import com.google.protobuf.WireFormat; 23 | import java.util.List; 24 | 25 | /** Convenience class encapsulating type information for unknown fields. */ 26 | @AutoValue 27 | abstract class UnknownFieldDescriptor { 28 | 29 | enum Type { 30 | VARINT(WireFormat.WIRETYPE_VARINT) { 31 | @Override 32 | public List getValues(UnknownFieldSet.Field field) { 33 | return field.getVarintList(); 34 | } 35 | }, 36 | FIXED32(WireFormat.WIRETYPE_FIXED32) { 37 | @Override 38 | public List getValues(UnknownFieldSet.Field field) { 39 | return field.getFixed32List(); 40 | } 41 | }, 42 | FIXED64(WireFormat.WIRETYPE_FIXED64) { 43 | @Override 44 | public List getValues(UnknownFieldSet.Field field) { 45 | return field.getFixed64List(); 46 | } 47 | }, 48 | LENGTH_DELIMITED(WireFormat.WIRETYPE_LENGTH_DELIMITED) { 49 | @Override 50 | public List getValues(UnknownFieldSet.Field field) { 51 | return field.getLengthDelimitedList(); 52 | } 53 | }, 54 | GROUP(WireFormat.WIRETYPE_START_GROUP) { 55 | @Override 56 | public List getValues(UnknownFieldSet.Field field) { 57 | return field.getGroupList(); 58 | } 59 | }; 60 | 61 | private static final ImmutableList TYPES = ImmutableList.copyOf(values()); 62 | 63 | static ImmutableList all() { 64 | return TYPES; 65 | } 66 | 67 | private final int wireType; 68 | 69 | Type(int wireType) { 70 | this.wireType = wireType; 71 | } 72 | 73 | /** Returns the corresponding values from the given field. */ 74 | abstract List getValues(UnknownFieldSet.Field field); 75 | 76 | /** Returns the {@link WireFormat} constant for this field type. */ 77 | final int wireType() { 78 | return wireType; 79 | } 80 | } 81 | 82 | static UnknownFieldDescriptor create(int fieldNumber, Type type) { 83 | return new AutoValue_UnknownFieldDescriptor(fieldNumber, type); 84 | } 85 | 86 | abstract int fieldNumber(); 87 | 88 | abstract Type type(); 89 | 90 | static ImmutableList descriptors( 91 | int fieldNumber, UnknownFieldSet.Field field) { 92 | ImmutableList.Builder builder = ImmutableList.builder(); 93 | for (Type type : Type.all()) { 94 | if (!type.getValues(field).isEmpty()) { 95 | builder.add(create(fieldNumber, type)); 96 | } 97 | } 98 | return builder.build(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /extensions/proto/src/main/java/com/google/common/truth/extensions/proto/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * Custom subjects for testing Protocol 19 | * Buffer instances. 20 | * 21 | *

This package is a part of the open-source Truth 22 | * project. 23 | */ 24 | @CheckReturnValue 25 | package com.google.common.truth.extensions.proto; 26 | 27 | import com.google.errorprone.annotations.CheckReturnValue; 28 | -------------------------------------------------------------------------------- /extensions/proto/src/test/java/com/google/common/truth/extensions/proto/MultiExpectFailure.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth.extensions.proto; 17 | 18 | import com.google.common.base.Preconditions; 19 | import com.google.common.truth.ExpectFailure; 20 | import com.google.common.truth.StandardSubjectBuilder; 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | import org.junit.rules.TestRule; 24 | import org.junit.runner.Description; 25 | import org.junit.runners.model.Statement; 26 | 27 | /** 28 | * A collection of {@link ExpectFailure} rules, for use in a single test case. 29 | * 30 | *

Users should instantiate {@code MultiExpectFailure} as a {@code @Rule}, then use {@link 31 | * #whenTesting()} and {@link #getFailure()} just like you would with an ordinary {@link 32 | * ExpectFailure} rule. Each call to {@link #whenTesting()} will clobber the previous {@link 33 | * #getFailure()} results. 34 | */ 35 | class MultiExpectFailure implements TestRule { 36 | 37 | private final List expectFailures; 38 | private int currentIndex = -1; 39 | 40 | MultiExpectFailure(int size) { 41 | expectFailures = new ArrayList<>(size); 42 | for (int i = 0; i < size; i++) { 43 | expectFailures.add(new ExpectFailure()); 44 | } 45 | } 46 | 47 | StandardSubjectBuilder whenTesting() { 48 | Preconditions.checkState( 49 | currentIndex < expectFailures.size() - 1, 50 | "Not enough ExpectFailures (%s)", 51 | expectFailures.size()); 52 | return expectFailures.get(++currentIndex).whenTesting(); 53 | } 54 | 55 | AssertionError getFailure() { 56 | Preconditions.checkState(currentIndex >= 0, "Must call 'whenTesting()' first."); 57 | return expectFailures.get(currentIndex).getFailure(); 58 | } 59 | 60 | @Override 61 | public Statement apply(Statement base, Description description) { 62 | Statement statement = base; 63 | for (ExpectFailure expectFailure : expectFailures) { 64 | statement = expectFailure.apply(statement, description); 65 | } 66 | return statement; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /extensions/proto/src/test/proto/test_message2.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto2"; 2 | 3 | package com.google.common.truth.extensions.proto; 4 | 5 | import "google/protobuf/any.proto"; 6 | 7 | option java_package = "com.google.common.truth.extensions.proto"; 8 | option java_multiple_files = true; 9 | 10 | // For brevity: o_ means 'optional', r_ means 'repeated' 11 | 12 | // This file must be kept in sync with test_message3.proto for tests to work. 13 | // Field names and field numbers should all match. Features supported in one 14 | // syntax but not the other are commented out in the other file. 15 | 16 | message TestMessage2 { 17 | enum TestEnum2 { 18 | DEFAULT = 0; 19 | ONE = 1; 20 | TWO = 2; 21 | } 22 | 23 | optional int32 o_int = 1; 24 | repeated string r_string = 2; 25 | optional int64 o_long_defaults_to_42 = 3 [default = 42]; 26 | optional TestEnum2 o_enum = 4; 27 | optional float o_float = 5; 28 | optional float o_float2 = 6; 29 | optional double o_double = 7; 30 | optional double o_double2 = 8; 31 | optional float o_float_defaults_to_42 = 9 [default = 42.0]; 32 | optional double o_double_defaults_to_42 = 10 [default = 42.0]; 33 | 34 | optional RequiredStringMessage2 o_required_string_message = 11; 35 | repeated RequiredStringMessage2 r_required_string_message = 12; 36 | optional TestMessage2 o_test_message = 13; 37 | repeated TestMessage2 r_test_message = 14; 38 | optional SubTestMessage2 o_sub_test_message = 15; 39 | repeated SubTestMessage2 r_sub_test_message = 16; 40 | map test_message_map = 17; 41 | optional .google.protobuf.Any o_any_message = 18; 42 | repeated .google.protobuf.Any r_any_message = 19; 43 | 44 | oneof oneof_field { 45 | TestMessage2 oneof_message1 = 20; 46 | TestMessage2 oneof_message2 = 21; 47 | } 48 | } 49 | 50 | message RequiredStringMessage2 { 51 | required string required_string = 1; 52 | } 53 | 54 | message SubTestMessage2 { 55 | optional int32 o_int = 1; 56 | repeated string r_string = 2; 57 | optional float o_float = 3; 58 | optional double o_double = 4; 59 | 60 | optional TestMessage2 o_test_message = 5; 61 | optional SubSubTestMessage2 o_sub_sub_test_message = 6; 62 | } 63 | 64 | message SubSubTestMessage2 { 65 | optional int32 o_int = 1; 66 | repeated string r_string = 2; 67 | optional float o_float = 3; 68 | optional double o_double = 4; 69 | } 70 | -------------------------------------------------------------------------------- /extensions/proto/src/test/proto/test_message3.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package com.google.common.truth.extensions.proto; 4 | 5 | import "google/protobuf/any.proto"; 6 | 7 | option java_package = "com.google.common.truth.extensions.proto"; 8 | option java_multiple_files = true; 9 | 10 | // For brevity: o_ means 'optional', r_ means 'repeated' 11 | 12 | // This file must be kept in sync with test_message2.proto for tests to work. 13 | // Field names and field numbers should all match. Features supported in one 14 | // syntax but not the other are commented out in the other file. 15 | 16 | message TestMessage3 { 17 | enum TestEnum3 { 18 | DEFAULT = 0; 19 | ONE = 1; 20 | TWO = 2; 21 | } 22 | 23 | int32 o_int = 1; 24 | repeated string r_string = 2; 25 | // optional int64 o_long_defaults_to_42 = 3 [default = 42]; 26 | TestEnum3 o_enum = 4; 27 | float o_float = 5; 28 | float o_float2 = 6; 29 | double o_double = 7; 30 | double o_double2 = 8; 31 | // optional float o_float_defaults_to_42 = 9 [default = 42.0]; 32 | // optional double o_double_defaults_to_42 = 10 [default = 42.0]; 33 | 34 | // optional RequiredStringMessage3 o_required_string_message = 11; 35 | // repeated RequiredStringMessage3 r_required_string_message = 12; 36 | TestMessage3 o_test_message = 13; 37 | repeated TestMessage3 r_test_message = 14; 38 | SubTestMessage3 o_sub_test_message = 15; 39 | repeated SubTestMessage3 r_sub_test_message = 16; 40 | map test_message_map = 17; 41 | .google.protobuf.Any o_any_message = 18; 42 | repeated .google.protobuf.Any r_any_message = 19; 43 | 44 | oneof oneof_field { 45 | TestMessage3 oneof_message1 = 20; 46 | TestMessage3 oneof_message2 = 21; 47 | } 48 | } 49 | 50 | // message RequiredStringMessage3 { 51 | // required string required_string = 1; 52 | // } 53 | 54 | message SubTestMessage3 { 55 | int32 o_int = 1; 56 | repeated string r_string = 2; 57 | float o_float = 3; 58 | double o_double = 4; 59 | 60 | TestMessage3 o_test_message = 5; 61 | SubSubTestMessage3 o_sub_sub_test_message = 6; 62 | } 63 | 64 | message SubSubTestMessage3 { 65 | int32 o_int = 1; 66 | repeated string r_string = 2; 67 | float o_float = 3; 68 | double o_double = 4; 69 | } 70 | -------------------------------------------------------------------------------- /extensions/re2j/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.google.truth.extensions 9 | truth-extensions-parent 10 | HEAD-SNAPSHOT 11 | 12 | truth-re2j-extension 13 | Truth Extension for RE2J 14 | 15 | An extension for the Truth test assertion framework supporting RE2J patterns 16 | 17 | 18 | 19 | com.google.truth 20 | truth 21 | 22 | 23 | com.google.re2j 24 | re2j 25 | 26 | 27 | 28 | 29 | 30 | ../.. 31 | 32 | LICENSE 33 | 34 | META-INF 35 | 36 | 37 | 38 | 39 | maven-javadoc-plugin 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /extensions/re2j/src/test/java/com/google/common/truth/extensions/re2j/Re2jSubjectsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.common.truth.extensions.re2j; 17 | 18 | import static com.google.common.truth.Truth.assertAbout; 19 | import static com.google.common.truth.extensions.re2j.Re2jSubjects.re2jString; 20 | 21 | import com.google.re2j.Pattern; 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.junit.runners.JUnit4; 25 | 26 | /** Unit tests for {@link Re2jSubjects}. */ 27 | @RunWith(JUnit4.class) 28 | public class Re2jSubjectsTest { 29 | private static final String PATTERN_STR = "(?:hello )+world"; 30 | private static final Pattern PATTERN = Pattern.compile(PATTERN_STR); 31 | 32 | @Test 33 | public void matches_string_succeeds() { 34 | assertAbout(re2jString()).that("hello world").matches(PATTERN_STR); 35 | } 36 | 37 | @Test 38 | public void matches_pattern_succeeds() { 39 | assertAbout(re2jString()).that("hello world").matches(PATTERN); 40 | } 41 | 42 | @Test 43 | public void doesNotMatch_string_succeeds() { 44 | assertAbout(re2jString()).that("world").doesNotMatch(PATTERN_STR); 45 | } 46 | 47 | @Test 48 | public void doesNotMatch_pattern_succeeds() { 49 | assertAbout(re2jString()).that("world").doesNotMatch(PATTERN); 50 | } 51 | 52 | @Test 53 | public void containsMatch_string_succeeds() { 54 | assertAbout(re2jString()).that("this is a hello world").containsMatch(PATTERN_STR); 55 | } 56 | 57 | @Test 58 | public void containsMatch_pattern_succeeds() { 59 | assertAbout(re2jString()).that("this is a hello world").containsMatch(PATTERN); 60 | } 61 | 62 | @Test 63 | public void doesNotContainMatch_string_succeeds() { 64 | assertAbout(re2jString()).that("hello cruel world").doesNotContainMatch(PATTERN_STR); 65 | } 66 | 67 | @Test 68 | public void doesNotContainMatch_pattern_succeeds() { 69 | assertAbout(re2jString()).that("hello cruel world").doesNotContainMatch(PATTERN); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /javadoc-link/j2objc-annotations/package-list: -------------------------------------------------------------------------------- 1 | com.google.j2objc.annotations 2 | -------------------------------------------------------------------------------- /overview.html: -------------------------------------------------------------------------------- 1 | 2 | Truth is a library for performing assertions in 3 | tests: 4 | 5 |

{@code
 6 | assertThat(notificationText).contains("testuser@google.com");
 7 | }
8 | 9 |

Truth is owned and maintained by the Guava team. It is used in the majority of the tests in Google’s own codebase. 11 | 12 |

For more information, see our introduction and 13 | other docs. 14 | 15 | -------------------------------------------------------------------------------- /refactorings/src/test/java/com/google/common/truth/refactorings/CorrespondenceSubclassToFactoryCallTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.refactorings; 18 | 19 | import com.google.errorprone.BugCheckerRefactoringTestHelper; 20 | import com.google.errorprone.CompilationTestHelper; 21 | import org.junit.Before; 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.junit.runners.JUnit4; 25 | 26 | /** @author cpovirk@google.com (Chris Povirk) */ 27 | @RunWith(JUnit4.class) 28 | public class CorrespondenceSubclassToFactoryCallTest { 29 | private BugCheckerRefactoringTestHelper refactoringHelper; 30 | private CompilationTestHelper compilationHelper; 31 | 32 | @Before 33 | public void setUp() { 34 | compilationHelper = 35 | CompilationTestHelper.newInstance(CorrespondenceSubclassToFactoryCall.class, getClass()); 36 | refactoringHelper = 37 | BugCheckerRefactoringTestHelper.newInstance( 38 | CorrespondenceSubclassToFactoryCall.class, getClass()); 39 | } 40 | 41 | @Test 42 | public void testPositiveCase() { 43 | compilationHelper 44 | .addSourceFile("testdata/CorrespondenceSubclassToFactoryCallPositiveCases.java") 45 | .doTest(); 46 | } 47 | 48 | @Test 49 | public void testPositiveCase2() { 50 | compilationHelper 51 | .addSourceFile("testdata/CorrespondenceSubclassToFactoryCallPositiveCases2.java") 52 | .doTest(); 53 | } 54 | 55 | @Test 56 | public void testNegativeCase() { 57 | compilationHelper 58 | .addSourceFile("testdata/CorrespondenceSubclassToFactoryCallNegativeCases.java") 59 | .doTest(); 60 | } 61 | 62 | @Test 63 | public void refactoring() { 64 | refactoringHelper 65 | .addInput("testdata/CorrespondenceSubclassToFactoryCallPositiveCases.java") 66 | .addOutput("testdata/CorrespondenceSubclassToFactoryCallPositiveCases_expected.java") 67 | .doTest(); 68 | } 69 | 70 | @Test 71 | public void refactoring2() { 72 | refactoringHelper 73 | .addInput("testdata/CorrespondenceSubclassToFactoryCallPositiveCases2.java") 74 | .addOutput("testdata/CorrespondenceSubclassToFactoryCallPositiveCases2_expected.java") 75 | .doTest(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /refactorings/src/test/java/com/google/common/truth/refactorings/FailWithFactsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.refactorings; 18 | 19 | import com.google.errorprone.CompilationTestHelper; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.junit.runners.JUnit4; 23 | 24 | /** @author cpovirk@google.com (Chris Povirk) */ 25 | @RunWith(JUnit4.class) 26 | public class FailWithFactsTest { 27 | private final CompilationTestHelper compilationHelper = 28 | CompilationTestHelper.newInstance(FailWithFacts.class, getClass()); 29 | 30 | @Test 31 | public void testPositiveCase() { 32 | compilationHelper.addSourceFile("testdata/FailWithFactsPositiveCases.java").doTest(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /refactorings/src/test/java/com/google/common/truth/refactorings/NamedToWithMessageTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.refactorings; 18 | 19 | import com.google.errorprone.CompilationTestHelper; 20 | import org.junit.Before; 21 | import org.junit.Test; 22 | import org.junit.runner.RunWith; 23 | import org.junit.runners.JUnit4; 24 | 25 | /** @author cpovirk@google.com (Chris Povirk) */ 26 | @RunWith(JUnit4.class) 27 | public class NamedToWithMessageTest { 28 | private CompilationTestHelper compilationHelper; 29 | 30 | @Before 31 | public void setUp() { 32 | compilationHelper = CompilationTestHelper.newInstance(NamedToWithMessage.class, getClass()); 33 | } 34 | 35 | @Test 36 | public void testPositiveCase() { 37 | compilationHelper.addSourceFile("NamedToWithMessagePositiveCases.java").doTest(); 38 | } 39 | 40 | @Test 41 | public void testNegativeCase() { 42 | compilationHelper.addSourceFile("NamedToWithMessageNegativeCases.java").doTest(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /refactorings/src/test/java/com/google/common/truth/refactorings/StoreActualValueInFieldTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019 Google, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.common.truth.refactorings; 18 | 19 | import com.google.errorprone.BugCheckerRefactoringTestHelper; 20 | import com.google.errorprone.CompilationTestHelper; 21 | import org.junit.Before; 22 | import org.junit.Test; 23 | import org.junit.runner.RunWith; 24 | import org.junit.runners.JUnit4; 25 | 26 | /** @author cpovirk@google.com (Chris Povirk) */ 27 | @RunWith(JUnit4.class) 28 | public class StoreActualValueInFieldTest { 29 | private BugCheckerRefactoringTestHelper refactoringHelper; 30 | private CompilationTestHelper compilationHelper; 31 | 32 | @Before 33 | public void setUp() { 34 | compilationHelper = 35 | CompilationTestHelper.newInstance(StoreActualValueInField.class, getClass()); 36 | refactoringHelper = 37 | BugCheckerRefactoringTestHelper.newInstance(new StoreActualValueInField(), getClass()); 38 | } 39 | 40 | @Test 41 | public void testPositiveCase() { 42 | compilationHelper.addSourceFile("StoreActualValueInFieldPositiveCases.java").doTest(); 43 | } 44 | 45 | @Test 46 | public void testNegativeCase() { 47 | compilationHelper.addSourceFile("StoreActualValueInFieldNegativeCases.java").doTest(); 48 | } 49 | 50 | @Test 51 | public void refactoring() { 52 | refactoringHelper 53 | .addInput("StoreActualValueInFieldPositiveCases.java") 54 | .addOutput("StoreActualValueInFieldPositiveCases_expected.java") 55 | .doTest(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /util/generate-latest-docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # A script to automatically deploy javadocs. 3 | # 4 | # This script is useful both in a CI regular build, where it will generate 5 | # javadocs (aggregated) via a maven build, and deploy them to github pages. This script 6 | # is derived from instructions given in this blog article: 7 | # http://benlimmer.com/2013/12/26/automatically-publish-javadoc-to-gh-pages-with-travis-ci/ 8 | # 9 | # If the RELEASE_VERSION environment variable is set, then it will perform a similar 10 | # action, but push to a versioned api docs folder, under the current user's credentials 11 | # rather than using an encrypted secret via github's GH_TOKEN mechanism. Users who 12 | # use the script this way must have a .ssh key which they have declared on github.com 13 | # per the instructions here: https://help.github.com/articles/generating-ssh-keys/ 14 | # 15 | set -euE 16 | 17 | echo -e "Publishing javadoc...\n" 18 | 19 | if [ -n "${RELEASE_VERSION:-}" ]; then 20 | # Release 21 | version_subdir=api/${RELEASE_VERSION} 22 | commit_message="Release $RELEASE_VERSION javadoc pushed to gh-pages." 23 | github_url="git@github.com:google/truth.git" 24 | else 25 | # CI 26 | version_subdir=api/latest 27 | commit_message="Latest javadoc on successful CI build auto-pushed to gh-pages." 28 | github_url="https://x-access-token:${GITHUB_TOKEN}@github.com/google/truth.git" 29 | fi 30 | 31 | mvn javadoc:aggregate 32 | target_dir="$(pwd)/target" 33 | cd ${target_dir} 34 | rm -rf gh-pages 35 | git clone --quiet --branch=gh-pages "${github_url}" gh-pages > /dev/null 36 | cd gh-pages 37 | 38 | if [[ -z "${RELEASE_VERSION:-}" ]]; then 39 | git config --global user.name "$GITHUB_ACTOR" 40 | git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com" 41 | fi 42 | api_version_dir="${target_dir}/gh-pages/${version_subdir}" 43 | git rm -rf ${api_version_dir} || true 44 | cp -ar ${target_dir}/reports/apidocs ${api_version_dir} 45 | git add -A -f ${api_version_dir} 46 | git commit -m "${commit_message}" 47 | git push -fq origin gh-pages > /dev/null 48 | 49 | echo -e "Published Javadoc to gh-pages.\n" 50 | --------------------------------------------------------------------------------