aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorGravatar lberki <lberki@google.com>2017-05-30 12:35:33 +0200
committerGravatar László Csomor <laszlocsomor@google.com>2017-05-30 12:51:57 +0200
commitaea56b36af994b269800602e36000c293cabd00b (patch)
tree794f6b3b2528353cc39bd383730d408d4ff25233
parent229f393bf460700594ae032a551879e026bd0b91 (diff)
Migrate Java tests to Truth.
RELNOTES: None. PiperOrigin-RevId: 157446717
-rw-r--r--src/java_tools/buildjar/javatests/com/google/devtools/build/java/bazel/BazelJavaCompilerTest.java15
-rw-r--r--src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD1
-rw-r--r--src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java8
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/SignalHandlersTest.java6
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java31
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestNameListenerTest.java51
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestXmlListenerTest.java24
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/MemoizingRequestTest.java8
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4ConfigTest.java20
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4OptionsTest.java46
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4RunnerTest.java117
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4TestModelBuilderTest.java27
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestCaseNodeTest.java19
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestIntervalTest.java23
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestSuiteNodeTest.java5
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/XmlWriterTest.java6
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/RoundRobinShardingFilterTest.java26
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingEnvironmentTest.java13
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingFiltersTest.java11
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed/InternationalCharsTest.java4
-rw-r--r--src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java33
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ConcatenateStrategyTest.java29
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/CopyEntryFilterTest.java13
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/DefaultJarEntryFilterTest.java40
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/FakeZipFile.java43
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/MockSimpleFileSystem.java14
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/OptionFileExpanderTest.java18
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/PrefixListPathFilterTest.java14
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/SingleJarTest.java12
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ZipCombinerTest.java99
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipReaderTest.java18
-rw-r--r--src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java23
-rw-r--r--src/test/java/com/google/devtools/build/docgen/DocCheckerUtilsTest.java21
-rw-r--r--src/test/java/com/google/devtools/build/docgen/RuleDocumentationAttributeTest.java54
-rw-r--r--src/test/java/com/google/devtools/build/docgen/RuleDocumentationTest.java50
-rw-r--r--src/test/java/com/google/devtools/build/docgen/RuleLinkExpanderTest.java16
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporterTest.java55
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/ArtifactFactoryTest.java70
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/ArtifactTest.java65
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/CompositeRunfilesSupplierTest.java3
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/ConcurrentMultimapWithHeadElementTest.java54
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/CustomCommandLineTest.java38
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/DigestUtilsTest.java43
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/ExecutableSymlinkActionTest.java12
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/FailActionTest.java12
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/LocalHostResourceManagerLinuxTest.java30
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/ResourceManagerTest.java170
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/ResourceSetTest.java12
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/RootTest.java33
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/cache/CompactPersistentActionCacheTest.java50
-rw-r--r--src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java141
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/AnalysisCachingTest.java80
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/AspectAwareAttributeMapperTest.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/BlazeDirectoriesTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/BuildViewTest.java119
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/CircularDependencyTest.java15
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/CompilationHelperTest.java31
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/ConfigurationsForLateBoundTargetsTest.java10
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/ConfiguredAttributeMapperTest.java41
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/DependencyResolverTest.java8
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/DependencyTest.java2
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/DuplicateActionTest.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/LabelExpanderTest.java14
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/LicensingTests.java27
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/MakeVariableExpanderTest.java8
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/RunfilesTest.java33
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/TopLevelArtifactHelperTest.java25
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/UtilTest.java8
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/actions/FileWriteActionTestCase.java18
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/actions/ParamFileWriteActionTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java121
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkActionTest.java16
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/actions/TemplateExpansionActionTest.java19
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationTest.java95
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/config/BuildOptionsTest.java31
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/config/PerLabelOptionsTest.java20
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/config/RunUnderConverterTest.java16
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/config/StampTest.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/constraints/ConstraintsTest.java122
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/select/AbstractAttributeMapperTest.java38
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/select/AggregatingAttributeMapperTest.java32
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/select/NonconfigurableAttributeMapperTest.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/select/RawAttributeMapperTest.java33
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestBase.java7
-rw-r--r--src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java52
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java3
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java16
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/repository/cache/RepositoryCacheTest.java22
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryContextTest.java12
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryIntegrationTest.java18
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java3
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleCommandSubstitutionTest.java9
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleConfiguredTargetTest.java87
-rw-r--r--src/test/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemanticsTest.java32
-rw-r--r--src/test/java/com/google/devtools/build/lib/buildtool/SymlinkForestTest.java35
-rw-r--r--src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java128
-rw-r--r--src/test/java/com/google/devtools/build/lib/cmdline/LabelValidatorTest.java156
-rw-r--r--src/test/java/com/google/devtools/build/lib/cmdline/PackageIdentifierTest.java18
-rw-r--r--src/test/java/com/google/devtools/build/lib/cmdline/RepositoryNameTest.java17
-rw-r--r--src/test/java/com/google/devtools/build/lib/cmdline/TargetPatternTest.java85
-rw-r--r--src/test/java/com/google/devtools/build/lib/collect/CollectionUtilsTest.java59
-rw-r--r--src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyListMultimapTest.java117
-rw-r--r--src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyMapTest.java30
-rw-r--r--src/test/java/com/google/devtools/build/lib/collect/IterablesChainTest.java23
-rw-r--r--src/test/java/com/google/devtools/build/lib/collect/nestedset/ExpanderTestBase.java30
-rw-r--r--src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetImplTest.java46
-rw-r--r--src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetViewTest.java28
-rw-r--r--src/test/java/com/google/devtools/build/lib/collect/nestedset/OrderTest.java2
-rw-r--r--src/test/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitorTest.java93
-rw-r--r--src/test/java/com/google/devtools/build/lib/concurrent/KeyedLockerTest.java83
-rw-r--r--src/test/java/com/google/devtools/build/lib/concurrent/MoreFuturesTest.java33
-rw-r--r--src/test/java/com/google/devtools/build/lib/events/AbstractEventHandlerTest.java19
-rw-r--r--src/test/java/com/google/devtools/build/lib/events/EventCollectorTest.java30
-rw-r--r--src/test/java/com/google/devtools/build/lib/events/EventSensorTest.java20
-rw-r--r--src/test/java/com/google/devtools/build/lib/events/EventTest.java9
-rw-r--r--src/test/java/com/google/devtools/build/lib/events/LocationTest.java46
-rw-r--r--src/test/java/com/google/devtools/build/lib/events/ReporterTest.java11
-rw-r--r--src/test/java/com/google/devtools/build/lib/events/SimpleReportersTest.java4
-rw-r--r--src/test/java/com/google/devtools/build/lib/events/StoredErrorEventHandlerTest.java24
-rw-r--r--src/test/java/com/google/devtools/build/lib/exec/DigestTest.java66
-rw-r--r--src/test/java/com/google/devtools/build/lib/exec/MiddlemanActionTest.java32
-rw-r--r--src/test/java/com/google/devtools/build/lib/exec/ParameterFileTest.java14
-rw-r--r--src/test/java/com/google/devtools/build/lib/exec/SingleBuildFileCacheTest.java24
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/AttributeContainerTest.java34
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/AttributeTest.java88
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/BuildTypeTest.java98
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/EnvironmentGroupTest.java26
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/ExportsFilesTest.java23
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/ExternalPackageTest.java9
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunctionTest.java20
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/InputFileTest.java29
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/LicenseTest.java22
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/OutputFileTest.java32
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java124
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/PackageGroupStaticInitializationTest.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/PackageGroupTest.java9
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/RelativePackageNameResolverTest.java5
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/RuleClassBuilderTest.java32
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/RuleClassTest.java227
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/RuleFactoryTest.java58
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/RuleTest.java44
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/TargetUtilsTest.java43
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/TestSizeTest.java47
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/TestTargetUtilsTest.java31
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/TestTimeoutTest.java67
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/WorkspaceFactoryTest.java10
-rw-r--r--src/test/java/com/google/devtools/build/lib/packages/util/PackageFactoryTestBase.java31
-rw-r--r--src/test/java/com/google/devtools/build/lib/pkgcache/IncrementalLoadingTest.java33
-rw-r--r--src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java44
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/AbstractCommandTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/AllIncompatibleChangesExpansionTest.java2
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcherRcoptionsTest.java39
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptionsTest.java11
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/BlazeVersionInfoTest.java24
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerModuleTest.java2
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerTest.java127
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/ExperimentalStateTrackerTest.java283
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyAllowValuesTest.java3
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyDisallowValuesTest.java5
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/TestResultAnalyzerTest.java23
-rw-r--r--src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java39
-rw-r--r--src/test/java/com/google/devtools/build/lib/sandbox/SandboxOptionsTest.java29
-rw-r--r--src/test/java/com/google/devtools/build/lib/shell/CommandLargeInputsTest.java35
-rw-r--r--src/test/java/com/google/devtools/build/lib/shell/CommandTest.java140
-rw-r--r--src/test/java/com/google/devtools/build/lib/shell/ConsumersTest.java14
-rw-r--r--src/test/java/com/google/devtools/build/lib/shell/FutureConsumptionTest.java14
-rw-r--r--src/test/java/com/google/devtools/build/lib/shell/InterruptibleTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/shell/ShellUtilsTest.java36
-rw-r--r--src/test/java/com/google/devtools/build/lib/shell/ToTruncatedStringTest.java15
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/ASTFileLookupFunctionTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/ActionDataTest.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/ActionExecutionInactivityWatchdogTest.java9
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/ArtifactFunctionTest.java50
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/ConfigurationsForTargetsWithDynamicConfigurationsTest.java2
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/ContainingPackageLookupFunctionTest.java19
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/DiffAwarenessManagerTest.java83
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/FileFunctionTest.java189
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/FilesetEntryFunctionTest.java9
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/FilesystemValueCheckerTest.java54
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/GlobFunctionTest.java34
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java35
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/PackageLookupFunctionTest.java83
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/PackageProgressReceiverTest.java28
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/ParallelBuilderTest.java24
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java17
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionTest.java20
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfTargetsUnderDirectoryFunctionTest.java23
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/RecursiveFilesystemTraversalFunctionTest.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/RecursivePkgFunctionTest.java40
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTest.java9
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTestCase.java5
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/SkylarkFileContentHashTests.java17
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/SkylarkImportLookupFunctionTest.java34
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/TargetMarkerFunctionTest.java29
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderMediumTest.java125
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderTest.java83
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactBuildTest.java112
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactMetadataTest.java2
-rw-r--r--src/test/java/com/google/devtools/build/lib/skyframe/WorkspaceFileFunctionTest.java18
-rw-r--r--src/test/java/com/google/devtools/build/lib/skylark/SkylarkFileHelperTest.java7
-rw-r--r--src/test/java/com/google/devtools/build/lib/skylark/SkylarkIntegrationTest.java36
-rw-r--r--src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleClassFunctionsTest.java184
-rw-r--r--src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleContextTest.java87
-rw-r--r--src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleImplementationFunctionsTest.java127
-rw-r--r--src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java20
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/BaseFunctionTest.java25
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/BuildFileASTTest.java42
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/EnvironmentTest.java165
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/EvalUtilsTest.java37
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/EvaluationTest.java21
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/ExceptionTest.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/FunctionTest.java86
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/GlobCriteriaTest.java30
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/GlobListTest.java33
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/LexerTest.java386
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/LineNumberTableTest.java71
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java3
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/ParserInputSourceTest.java23
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/ParserTest.java214
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/PrinterTest.java85
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/SkylarkEvaluationTest.java16
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/SkylarkListTest.java51
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/SkylarkNestedSetTest.java2
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/TypeTest.java69
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/ValidationTest.java16
-rw-r--r--src/test/java/com/google/devtools/build/lib/syntax/util/EvaluationTestCase.java2
-rw-r--r--src/test/java/com/google/devtools/build/lib/testutil/MoreAsserts.java6
-rw-r--r--src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java15
-rw-r--r--src/test/java/com/google/devtools/build/lib/testutil/TestSizeAnnotationTest.java30
-rw-r--r--src/test/java/com/google/devtools/build/lib/unix/ProcMeminfoParserTest.java8
-rw-r--r--src/test/java/com/google/devtools/build/lib/unix/UnixFileSystemTest.java24
-rw-r--r--src/test/java/com/google/devtools/build/lib/unix/UnixPathEqualityTest.java19
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/CommandBuilderTest.java10
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/DependencySetTest.java10
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/FileTypeTest.java38
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/GroupedListTest.java30
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/LongArrayListTest.java104
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/OptionsUtilsTest.java29
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/PairTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/PathFragmentFilterTest.java8
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/PersistentMapTest.java47
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/RegexFilterTest.java15
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/StringCanonicalizerTest.java3
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/StringIndexerTest.java54
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/StringTrieTest.java41
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/StringUtilTest.java24
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/StringUtilitiesTest.java34
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/io/AnsiTerminalPrinterTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/io/OutErrTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/io/PositionAwareAnsiTerminalWriterTest.java26
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/io/RecordingOutErrTest.java11
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/io/StreamDemultiplexerTest.java15
-rw-r--r--src/test/java/com/google/devtools/build/lib/util/io/StreamMultiplexerTest.java20
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/FileSystemTest.java250
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/FileSystemUtilsTest.java289
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/FileSystemsTest.java13
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/GlobTest.java40
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/JavaIoFileSystemTest.java8
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/NativePathTest.java59
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/PathFragmentTest.java265
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/PathFragmentWindowsTest.java130
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/PathGetParentTest.java15
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/PathTest.java77
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/RecursiveGlobTest.java14
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/ScopeEscapableFileSystemTest.java121
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/SearchPathTest.java12
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/SymlinkAwareFileSystemTest.java227
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/UnionFileSystemTest.java136
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/ZipFileSystemTest.java41
-rw-r--r--src/test/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryFileSystemTest.java106
-rw-r--r--src/test/java/com/google/devtools/build/skyframe/CycleDeduperTest.java22
-rw-r--r--src/test/java/com/google/devtools/build/skyframe/EagerInvalidatorTest.java88
-rw-r--r--src/test/java/com/google/devtools/build/skyframe/ErrorInfoTest.java3
-rw-r--r--src/test/java/com/google/devtools/build/skyframe/GraphTest.java47
-rw-r--r--src/test/java/com/google/devtools/build/skyframe/GraphTester.java11
-rw-r--r--src/test/java/com/google/devtools/build/skyframe/InMemoryNodeEntryTest.java255
-rw-r--r--src/test/java/com/google/devtools/build/skyframe/MemoizingEvaluatorTest.java413
-rw-r--r--src/test/java/com/google/devtools/build/skyframe/ParallelEvaluatorTest.java248
-rw-r--r--src/tools/benchmark/javatests/com/google/devtools/build/benchmark/MainTest.java23
-rw-r--r--src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/BUILD1
-rw-r--r--src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorHelperTest.java35
-rw-r--r--src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorTest.java14
283 files changed, 6335 insertions, 6696 deletions
diff --git a/src/java_tools/buildjar/javatests/com/google/devtools/build/java/bazel/BazelJavaCompilerTest.java b/src/java_tools/buildjar/javatests/com/google/devtools/build/java/bazel/BazelJavaCompilerTest.java
index 53f1ecc463..3e289ad91b 100644
--- a/src/java_tools/buildjar/javatests/com/google/devtools/build/java/bazel/BazelJavaCompilerTest.java
+++ b/src/java_tools/buildjar/javatests/com/google/devtools/build/java/bazel/BazelJavaCompilerTest.java
@@ -14,8 +14,7 @@
package com.google.devtools.build.java.bazel;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import java.io.File;
@@ -53,13 +52,13 @@ public class BazelJavaCompilerTest {
public void testCompilerNewInstance() throws Exception {
JavaCompiler javac = BazelJavaCompiler.newInstance();
- assertNotNull(javac.getStandardFileManager(null, null, null));
+ assertThat(javac.getStandardFileManager(null, null, null)).isNotNull();
// This is a simplified pattern of invoking the compiler API. Note, however, that
// many examples cast to JavacTask or JavacTaskImpl and invoke the phases separately.
// Currently, either cast will fail with something that looks like classloader issues:
// "com.sun.tools.javac.api.JavacTask cannot be cast to com.sun.tools.javac.api.JavacTask"
- assertNotNull(javac.getTask(null, null, null, null, null, null));
+ assertThat(javac.getTask(null, null, null, null, null, null)).isNotNull();
}
@Test
@@ -88,8 +87,8 @@ public class BazelJavaCompilerTest {
// the default options include the correct -encoding (which is loaded from
// JavaBuilder), and that BazelJavaCompiler is appending the -bootclasspath.
List<String> opts = BazelJavaCompiler.getDefaultJavacopts();
- assertTrue(opts.contains("UTF-8"));
- assertTrue(opts.contains("-bootclasspath"));
+ assertThat(opts).contains("UTF-8");
+ assertThat(opts).contains("-bootclasspath");
}
private void assertCompileSucceeds(final String uri, final String content) throws Exception {
@@ -107,7 +106,7 @@ public class BazelJavaCompilerTest {
DiagnosticCollector<JavaFileObject> messages = new DiagnosticCollector<>();
JavaCompiler.CompilationTask task =
javac.getTask(null, fileManager, messages, null, null, Collections.singletonList(source));
- assertTrue(task.call());
- assertTrue(messages.getDiagnostics().isEmpty());
+ assertThat(task.call()).isTrue();
+ assertThat(messages.getDiagnostics()).isEmpty();
}
}
diff --git a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD
index 1d95f1b11d..016ac78046 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD
+++ b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD
@@ -7,6 +7,7 @@ java_library(
deps = [
"//src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding",
"//src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/api",
+ "//third_party:guava",
"//third_party:junit4",
"//third_party:truth",
],
diff --git a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java
index 178b8264f7..cd17c5d929 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java
+++ b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java
@@ -14,6 +14,8 @@
package com.google.testing.junit.runner.sharding.testing;
+import static com.google.common.truth.Truth.assertThat;
+
import com.google.testing.junit.runner.sharding.api.ShardingFilterFactory;
import java.util.ArrayList;
import java.util.Collection;
@@ -90,7 +92,7 @@ public abstract class ShardingFilterTestCase extends TestCase {
public final void testShouldRunTestSuite() {
Description testSuiteDescription = createTestSuiteDescription();
Filter filter = createShardingFilterFactory().createFilter(TEST_DESCRIPTIONS, 0, 1);
- assertTrue(filter.shouldRun(testSuiteDescription));
+ assertThat(filter.shouldRun(testSuiteDescription)).isTrue();
}
/**
@@ -210,13 +212,13 @@ public abstract class ShardingFilterTestCase extends TestCase {
List<Filter> filters, List<Description> descriptions) {
Map<Filter, List<Description>> run1 = simulateTestRun(filters, descriptions);
Map<Filter, List<Description>> run2 = simulateTestRun(filters, descriptions);
- assertEquals(run1, run2);
+ assertThat(run2).isEqualTo(run1);
Map<Filter, List<Description>> randomizedRun1 =
simulateSelfRandomizingTestRun(filters, descriptions);
Map<Filter, List<Description>> randomizedRun2 =
simulateSelfRandomizingTestRun(filters, descriptions);
- assertEquals(randomizedRun1, randomizedRun2);
+ assertThat(randomizedRun2).isEqualTo(randomizedRun1);
}
private static void addDescriptionForFilterToMap(
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/SignalHandlersTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/SignalHandlersTest.java
index 038b427759..9da84292cc 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/SignalHandlersTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/SignalHandlersTest.java
@@ -14,7 +14,7 @@
package com.google.testing.junit.runner.internal;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertWithMessage;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -40,7 +40,9 @@ public class SignalHandlersTest {
@Override
public SignalHandler install(Signal signal, SignalHandler handler) {
SignalHandler previousHandler = currentHandler;
- assertEquals("This fake only supports the TERM signal", TERM_SIGNAL, signal);
+ assertWithMessage("This fake only supports the TERM signal")
+ .that(signal)
+ .isEqualTo(TERM_SIGNAL);
currentHandler = handler;
return previousHandler;
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java
index f89c7ab277..7bd9a10b6f 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java
@@ -14,10 +14,7 @@
package com.google.testing.junit.runner.internal.junit4;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import java.util.Arrays;
@@ -103,9 +100,9 @@ public class CancellableRequestFactoryTest {
fail("exception expected");
} catch (ExecutionException e) {
Throwable runnerException = e.getCause();
- assertTrue(runnerException instanceof RuntimeException);
- assertEquals("Test run interrupted", runnerException.getMessage());
- assertTrue(runnerException.getCause() instanceof StoppedByUserException);
+ assertThat(runnerException).isInstanceOf(RuntimeException.class);
+ assertThat(runnerException).hasMessageThat().isEqualTo("Test run interrupted");
+ assertThat(runnerException).hasCauseThat().isInstanceOf(StoppedByUserException.class);
}
executor.shutdownNow();
@@ -131,11 +128,11 @@ public class CancellableRequestFactoryTest {
core.run(request);
fail("exception expected");
} catch (RuntimeException e) {
- assertEquals("Test run interrupted", e.getMessage());
- assertTrue(e.getCause() instanceof StoppedByUserException);
+ assertThat(e).hasMessageThat().isEqualTo("Test run interrupted");
+ assertThat(e).hasCauseThat().isInstanceOf(StoppedByUserException.class);
}
- assertFalse(testRan.get());
+ assertThat(testRan.get()).isFalse();
}
@Test
@@ -154,9 +151,9 @@ public class CancellableRequestFactoryTest {
JUnitCore core = new JUnitCore();
Result result = core.run(request);
- assertTrue(testRan.get());
- assertEquals(1, result.getRunCount());
- assertEquals(0, result.getFailureCount());
+ assertThat(testRan.get()).isTrue();
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(0);
}
@Test
@@ -177,10 +174,10 @@ public class CancellableRequestFactoryTest {
JUnitCore core = new JUnitCore();
Result result = core.run(request);
- assertTrue(testRan.get());
- assertEquals(1, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertSame(expectedFailure, result.getFailures().get(0).getException());
+ assertThat(testRan.get()).isTrue();
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getFailures().get(0).getException()).isSameAs(expectedFailure);
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestNameListenerTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestNameListenerTest.java
index a63788779b..1c3073454c 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestNameListenerTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestNameListenerTest.java
@@ -15,8 +15,7 @@
package com.google.testing.junit.runner.internal.junit4;
import static com.google.common.base.Throwables.throwIfUnchecked;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
import com.google.testing.junit.runner.util.TestNameProvider;
import java.util.concurrent.ExecutorService;
@@ -53,26 +52,26 @@ public class JUnit4TestNameListenerTest {
@Test
public void testJUnit4Listener_normalUsage() throws Exception {
- assertNull(testNameProviderForTesting);
+ assertThat(testNameProviderForTesting).isNull();
Description description = Description.createSuiteDescription(FakeTest.class);
testNameListener.testRunStarted(description);
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
description = Description.createTestDescription(FakeTest.class, "methodName");
testNameListener.testStarted(description);
- assertEquals(description, testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isEqualTo(description);
testNameListener.testFinished(description);
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
description = Description.createTestDescription(FakeTest.class, "anotherMethodName");
testNameListener.testStarted(description);
- assertEquals(description, testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isEqualTo(description);
testNameListener.testFinished(description);
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
testNameListener.testRunFinished(null);
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
}
@Test
@@ -82,9 +81,11 @@ public class JUnit4TestNameListenerTest {
description = Description.createTestDescription(this.getClass(), name.getMethodName());
testNameListener.testStarted(description);
- assertEquals("testJUnit4Listener_hasExpectedDisplayName("
- + JUnit4TestNameListenerTest.class.getCanonicalName() + ")",
- testNameProviderForTesting.get().getDisplayName());
+ assertThat(testNameProviderForTesting.get().getDisplayName())
+ .isEqualTo(
+ "testJUnit4Listener_hasExpectedDisplayName("
+ + JUnit4TestNameListenerTest.class.getCanonicalName()
+ + ")");
}
@Test
@@ -96,49 +97,49 @@ public class JUnit4TestNameListenerTest {
Description.createTestDescription(FakeTest.class, "anotherMethodName");
testNameListener.testRunStarted(Description.createSuiteDescription(FakeTest.class));
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
testNameListener.testStarted(description1);
- assertEquals(description1, testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isEqualTo(description1);
Future<?> startSecondTestFuture =
executorService.submit(
new Runnable() {
@Override
public void run() {
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
try {
testNameListener.testStarted(description2);
} catch (Exception e) {
throwIfUnchecked(e);
throw new RuntimeException(e);
}
- assertEquals(description2, testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isEqualTo(description2);
}
});
startSecondTestFuture.get();
- assertEquals(description1, testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isEqualTo(description1);
testNameListener.testFinished(description1);
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
Future<?> endSecondTestFuture =
executorService.submit(
new Runnable() {
@Override
public void run() {
- assertEquals(description2, testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isEqualTo(description2);
try {
testNameListener.testFinished(description2);
} catch (Exception e) {
throwIfUnchecked(e);
throw new RuntimeException(e);
}
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
}
});
endSecondTestFuture.get();
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
}
/**
@@ -158,16 +159,16 @@ public class JUnit4TestNameListenerTest {
testNameListener.testStarted(description1);
testNameListener.testStarted(description1);
- assertEquals(description1, testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isEqualTo(description1);
testNameListener.testStarted(description2);
- assertEquals(description2, testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isEqualTo(description2);
testNameListener.testFinished(description1);
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
testNameListener.testFinished(description2);
- assertNull(testNameProviderForTesting.get());
+ assertThat(testNameProviderForTesting.get()).isNull();
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestXmlListenerTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestXmlListenerTest.java
index 11d35c7888..51f10a059a 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestXmlListenerTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/JUnit4TestXmlListenerTest.java
@@ -14,8 +14,8 @@
package com.google.testing.junit.runner.internal.junit4;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import static org.mockito.Matchers.any;
@@ -77,13 +77,17 @@ public class JUnit4TestXmlListenerTest {
when(mockModelSupplier.get()).thenReturn(mockModel);
listener.testRunStarted(suiteDescription);
- assertEquals(1, fakeSignalHandlers.handlers.size());
+ assertThat(fakeSignalHandlers.handlers).hasSize(1);
fakeSignalHandlers.handlers.get(0).handle(new Signal("TERM"));
String errOutput = errStream.toString(CHARSET);
- assertTrue("expected signal name in stderr", errOutput.contains("SIGTERM"));
- assertTrue("expected message in stderr", errOutput.contains("Done writing test XML"));
+ assertWithMessage("expected signal name in stderr")
+ .that(errOutput.contains("SIGTERM"))
+ .isTrue();
+ assertWithMessage("expected message in stderr")
+ .that(errOutput.contains("Done writing test XML"))
+ .isTrue();
InOrder inOrder = inOrder(mockRequestFactory, mockModel);
inOrder.verify(mockRequestFactory).cancelRun();
@@ -106,7 +110,7 @@ public class JUnit4TestXmlListenerTest {
core.addListener(listener);
core.run(Request.classWithoutSuiteMethod(PassingTest.class));
- assertEquals("no output to stderr expected", 0, errStream.size());
+ assertWithMessage("no output to stderr expected").that(errStream.size()).isEqualTo(0);
verify(mockModel).writeAsXml(mockXmlStream);
verify(mockRequestFactory, never()).cancelRun();
}
@@ -130,7 +134,7 @@ public class JUnit4TestXmlListenerTest {
core.addListener(listener);
core.run(request);
- assertEquals("no output to stderr expected", 0, errStream.size());
+ assertWithMessage("no output to stderr expected").that(errStream.size()).isEqualTo(0);
InOrder inOrder = inOrder(mockModel);
inOrder.verify(mockModel).testSkipped(testDescription);
inOrder.verify(mockModel).writeAsXml(mockXmlStream);
@@ -156,7 +160,7 @@ public class JUnit4TestXmlListenerTest {
core.addListener(listener);
core.run(request);
- assertEquals("no output to stderr expected", 0, errStream.size());
+ assertWithMessage("no output to stderr expected").that(errStream.size()).isEqualTo(0);
InOrder inOrder = inOrder(mockModel);
inOrder.verify(mockModel).testSkipped(suiteDescription);
inOrder.verify(mockModel).writeAsXml(mockXmlStream);
@@ -182,7 +186,7 @@ public class JUnit4TestXmlListenerTest {
core.addListener(listener);
core.run(request);
- assertEquals("no output to stderr expected", 0, errStream.size());
+ assertWithMessage("no output to stderr expected").that(errStream.size()).isEqualTo(0);
InOrder inOrder = inOrder(mockModel);
inOrder.verify(mockModel).testFailure(eq(testDescription), any(Throwable.class));
inOrder.verify(mockModel).writeAsXml(mockXmlStream);
@@ -208,7 +212,7 @@ public class JUnit4TestXmlListenerTest {
core.addListener(listener);
core.run(request);
- assertEquals("no output to stderr expected", 0, errStream.size());
+ assertWithMessage("no output to stderr expected").that(errStream.size()).isEqualTo(0);
InOrder inOrder = inOrder(mockModel);
inOrder.verify(mockModel).testSuppressed(testDescription);
inOrder.verify(mockModel).writeAsXml(mockXmlStream);
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/MemoizingRequestTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/MemoizingRequestTest.java
index a2818eb453..ab383f0990 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/MemoizingRequestTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/MemoizingRequestTest.java
@@ -14,6 +14,7 @@
package com.google.testing.junit.runner.internal.junit4;
+import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.RETURNS_MOCKS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -21,7 +22,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import junit.framework.TestCase;
-
import org.junit.runner.Request;
import org.junit.runner.Runner;
@@ -49,7 +49,7 @@ public class MemoizingRequestTest extends TestCase {
Runner firstRunner = memoizingRequest.getRunner();
Runner secondRunner = memoizingRequest.getRunner();
- assertSame(firstRunner, secondRunner);
+ assertThat(secondRunner).isSameAs(firstRunner);
verify(mockRequestDelegate).getRunner();
verifyNoMoreInteractions(mockRequestDelegate);
}
@@ -66,8 +66,8 @@ public class MemoizingRequestTest extends TestCase {
Runner firstRunner = memoizingRequest.getRunner();
Runner secondRunner = memoizingRequest.getRunner();
- assertSame(stubRunner, firstRunner);
- assertSame(firstRunner, secondRunner);
+ assertThat(firstRunner).isSameAs(stubRunner);
+ assertThat(secondRunner).isSameAs(firstRunner);
verifyZeroInteractions(mockRequestDelegate);
}
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4ConfigTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4ConfigTest.java
index 9ddc682657..5410de1b20 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4ConfigTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4ConfigTest.java
@@ -14,11 +14,9 @@
package com.google.testing.junit.runner.junit4;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.testing.junit.runner.junit4.JUnit4Config.JUNIT_API_VERSION_PROPERTY;
import static com.google.testing.junit.runner.junit4.JUnit4Config.SHOULD_INSTALL_SECURITY_MANAGER_PROPERTY;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.testing.junit.runner.util.GoogleTestSecurityManager;
@@ -46,7 +44,7 @@ public class JUnit4ConfigTest {
@Test
public void testGetJUnitRunnerApiVersion_defaultValue() {
JUnit4Config config = createConfigWithApiVersion("1");
- assertEquals(1, config.getJUnitRunnerApiVersion());
+ assertThat(config.getJUnitRunnerApiVersion()).isEqualTo(1);
}
@Test
@@ -57,7 +55,7 @@ public class JUnit4ConfigTest {
config.getJUnitRunnerApiVersion();
fail("exception expected");
} catch (IllegalStateException expected) {
- assertTrue(expected.getMessage().contains("I love pesto"));
+ assertThat(expected).hasMessageThat().contains("I love pesto");
}
}
@@ -69,7 +67,7 @@ public class JUnit4ConfigTest {
config.getJUnitRunnerApiVersion();
fail("exception expected");
} catch (IllegalStateException expected) {
- assertTrue(expected.getMessage().contains("3.14"));
+ assertThat(expected).hasMessageThat().contains("3.14");
}
}
@@ -81,14 +79,14 @@ public class JUnit4ConfigTest {
config.getJUnitRunnerApiVersion();
fail("exception expected");
} catch (IllegalStateException expected) {
- assertTrue(expected.getMessage().contains("13"));
+ assertThat(expected).hasMessageThat().contains("13");
}
}
@Test
public void testGetJUnitRunnerApiVersion_oneIsValid() {
JUnit4Config config = createConfigWithApiVersion("1");
- assertEquals(1, config.getJUnitRunnerApiVersion());
+ assertThat(config.getJUnitRunnerApiVersion()).isEqualTo(1);
}
@Test
@@ -96,7 +94,7 @@ public class JUnit4ConfigTest {
GoogleTestSecurityManager.uninstallIfInstalled();
JUnit4Config config = createConfigWithProperties(new Properties());
- assertTrue(config.shouldInstallSecurityManager());
+ assertThat(config.shouldInstallSecurityManager()).isTrue();
}
@Test
@@ -105,7 +103,7 @@ public class JUnit4ConfigTest {
properties.put("java.security.manager", "MySecurityManager");
properties.put(SHOULD_INSTALL_SECURITY_MANAGER_PROPERTY, "true");
JUnit4Config config = createConfigWithProperties(properties);
- assertFalse(config.shouldInstallSecurityManager());
+ assertThat(config.shouldInstallSecurityManager()).isFalse();
}
@Test
@@ -113,6 +111,6 @@ public class JUnit4ConfigTest {
Properties properties = new Properties();
properties.put(SHOULD_INSTALL_SECURITY_MANAGER_PROPERTY, "false");
JUnit4Config config = createConfigWithProperties(properties);
- assertFalse(config.shouldInstallSecurityManager());
+ assertThat(config.shouldInstallSecurityManager()).isFalse();
}
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4OptionsTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4OptionsTest.java
index 699c5883bb..f92f1dcd5c 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4OptionsTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4OptionsTest.java
@@ -14,9 +14,7 @@
package com.google.testing.junit.runner.junit4;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -38,46 +36,46 @@ public class JUnit4OptionsTest {
@Test
public void testParse_noArgs() throws Exception {
JUnit4Options options = JUnit4Options.parse(EMPTY_ENV, ImmutableList.<String>of());
- assertNull(options.getTestIncludeFilter());
- assertEquals(0, options.getUnparsedArgs().length);
+ assertThat(options.getTestIncludeFilter()).isNull();
+ assertThat(options.getUnparsedArgs()).isEmpty();
}
@Test
public void testParse_onlyUnparsedArgs() {
JUnit4Options options = JUnit4Options.parse(EMPTY_ENV, ImmutableList.of("--bar", "baz"));
- assertNull(options.getTestIncludeFilter());
- assertArrayEquals(new String[] {"--bar", "baz"}, options.getUnparsedArgs());
+ assertThat(options.getTestIncludeFilter()).isNull();
+ assertThat(options.getUnparsedArgs()).isEqualTo(new String[] {"--bar", "baz"});
}
@Test
public void testParse_withTwoArgTestFilter() throws Exception {
JUnit4Options options = JUnit4Options.parse(
EMPTY_ENV, ImmutableList.of("--test_filter", "foo"));
- assertEquals("foo", options.getTestIncludeFilter());
- assertEquals(0, options.getUnparsedArgs().length);
+ assertThat(options.getTestIncludeFilter()).isEqualTo("foo");
+ assertThat(options.getUnparsedArgs()).isEmpty();
}
@Test
public void testParse_withOneArgTestFilter() throws Exception {
JUnit4Options options = JUnit4Options.parse(EMPTY_ENV, ImmutableList.of("--test_filter=foo"));
- assertEquals("foo", options.getTestIncludeFilter());
- assertEquals(0, options.getUnparsedArgs().length);
+ assertThat(options.getTestIncludeFilter()).isEqualTo("foo");
+ assertThat(options.getUnparsedArgs()).isEmpty();
}
@Test
public void testParse_testFilterAndUnparsedArgs() throws Exception {
JUnit4Options options = JUnit4Options.parse(
EMPTY_ENV, ImmutableList.of("--bar", "--test_filter=foo", "--baz"));
- assertEquals("foo", options.getTestIncludeFilter());
- assertArrayEquals(new String[] {"--bar", "--baz"}, options.getUnparsedArgs());
+ assertThat(options.getTestIncludeFilter()).isEqualTo("foo");
+ assertThat(options.getUnparsedArgs()).isEqualTo(new String[] {"--bar", "--baz"});
}
@Test
public void testParse_testLastTestFilterWins() throws Exception {
JUnit4Options options =
JUnit4Options.parse(EMPTY_ENV, ImmutableList.of("--test_filter=foo", "--test_filter=bar"));
- assertEquals("bar", options.getTestIncludeFilter());
- assertEquals(0, options.getUnparsedArgs().length);
+ assertThat(options.getTestIncludeFilter()).isEqualTo("bar");
+ assertThat(options.getUnparsedArgs()).isEmpty();
}
@Test
@@ -94,23 +92,23 @@ public class JUnit4OptionsTest {
public void testParse_testFilterExcludeWithTwoArgTestFilter() throws Exception {
JUnit4Options options = JUnit4Options.parse(
EMPTY_ENV, ImmutableList.of("--test_exclude_filter", "foo"));
- assertEquals("foo", options.getTestExcludeFilter());
- assertEquals(0, options.getUnparsedArgs().length);
+ assertThat(options.getTestExcludeFilter()).isEqualTo("foo");
+ assertThat(options.getUnparsedArgs()).isEmpty();
}
@Test
public void testParse_testFilterExcludewithOneArgTestFilter() throws Exception {
JUnit4Options options = JUnit4Options.parse(
EMPTY_ENV, ImmutableList.of("--test_exclude_filter=foo"));
- assertEquals("foo", options.getTestExcludeFilter());
- assertEquals(0, options.getUnparsedArgs().length);
+ assertThat(options.getTestExcludeFilter()).isEqualTo("foo");
+ assertThat(options.getUnparsedArgs()).isEmpty();
}
@Test
public void testParse_unknownOptionName() throws Exception {
JUnit4Options options = JUnit4Options.parse(
EMPTY_ENV, ImmutableList.of("--unknown=foo"));
- assertArrayEquals(new String[] {"--unknown=foo"}, options.getUnparsedArgs());
+ assertThat(options.getUnparsedArgs()).isEqualTo(new String[] {"--unknown=foo"});
}
@Test
@@ -118,8 +116,8 @@ public class JUnit4OptionsTest {
Map<String, String> env = new HashMap<>();
env.put("TESTBRIDGE_TEST_ONLY", "foo");
JUnit4Options options = JUnit4Options.parse(env, ImmutableList.<String>of());
- assertEquals("foo", options.getTestIncludeFilter());
- assertEquals(0, options.getUnparsedArgs().length);
+ assertThat(options.getTestIncludeFilter()).isEqualTo("foo");
+ assertThat(options.getUnparsedArgs()).isEmpty();
}
@Test
@@ -127,7 +125,7 @@ public class JUnit4OptionsTest {
Map<String, String> env = new HashMap<>();
env.put("TESTBRIDGE_TEST_ONLY", "foo");
JUnit4Options options = JUnit4Options.parse(env, ImmutableList.of("--test_filter=bar"));
- assertEquals("bar", options.getTestIncludeFilter());
- assertEquals(0, options.getUnparsedArgs().length);
+ assertThat(options.getTestIncludeFilter()).isEqualTo("bar");
+ assertThat(options.getUnparsedArgs()).isEmpty();
}
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4RunnerTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4RunnerTest.java
index 6dd9bf32e2..b8bff631eb 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4RunnerTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4RunnerTest.java
@@ -15,8 +15,7 @@
package com.google.testing.junit.runner.junit4;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyListOf;
@@ -126,9 +125,9 @@ public class JUnit4RunnerTest {
Result result = runner.run();
- assertEquals(1, result.getRunCount());
- assertEquals(0, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(0);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
assertPassingTestHasExpectedOutput(stdoutByteStream, SamplePassingTest.class);
@@ -154,13 +153,16 @@ public class JUnit4RunnerTest {
Result result = runner.run();
- assertEquals(1, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
- assertTrue(extractOutput(stdoutByteStream).contains(
- "1) testThatAlwaysFails(" + SampleFailingTest.class.getName() + ")\n" +
- "java.lang.AssertionError: expected"));
+ assertThat(extractOutput(stdoutByteStream))
+ .contains(
+ "1) testThatAlwaysFails("
+ + SampleFailingTest.class.getName()
+ + ")\n"
+ + "java.lang.AssertionError: expected");
InOrder inOrder = inOrder(mockRunListener);
@@ -186,14 +188,14 @@ public class JUnit4RunnerTest {
Result result = runner.run();
- assertEquals(1, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
String output = new String(stdoutByteStream.toByteArray(), StandardCharsets.UTF_8);
// Intentionally swapped "Test 日\u672C." / "Test \u65E5本." to make sure that the "raw"
// character does not get corrupted (would become ? in both cases and we would not notice).
- assertTrue(output.contains("expected:<Test [Japan].> but was:<Test [日\u672C].>"));
+ assertThat(output).contains("expected:<Test [Japan].> but was:<Test [日\u672C].>");
InOrder inOrder = inOrder(mockRunListener);
@@ -222,9 +224,10 @@ public class JUnit4RunnerTest {
runner.run();
fail("exception expected");
} catch (RuntimeException e) {
- assertEquals("Test run interrupted", e.getMessage());
- assertTrue("Expected cause to be a StoppedByUserException",
- e.getCause() instanceof StoppedByUserException);
+ assertThat(e).hasMessageThat().isEqualTo("Test run interrupted");
+ assertWithMessage("Expected cause to be a StoppedByUserException")
+ .that(e.getCause() instanceof StoppedByUserException)
+ .isTrue();
InOrder inOrder = inOrder(mockRunListener);
inOrder.verify(mockRunListener).testRunStarted(any(Description.class));
@@ -255,9 +258,9 @@ public class JUnit4RunnerTest {
JUnit4Runner runner = createRunner(SampleExitingTest.class);
Result result = runner.run();
- assertEquals(1, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
}
@Test
@@ -275,13 +278,13 @@ public class JUnit4RunnerTest {
verify(shardingEnvironment).touchShardFile();
- assertEquals(2, result.getRunCount());
+ assertThat(result.getRunCount()).isEqualTo(2);
if (result.getFailureCount() > 1) {
fail("Too many failures: " + result.getFailures());
}
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
- assertEquals(2, runner.getModel().getNumTestCases());
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
+ assertThat(runner.getModel().getNumTestCases()).isEqualTo(2);
}
@Test
@@ -290,12 +293,12 @@ public class JUnit4RunnerTest {
JUnit4Runner runner = createRunner(SampleSuite.class);
Result result = runner.run();
- assertEquals(1, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
- assertEquals(
- Description.createTestDescription(SampleFailingTest.class, "testThatAlwaysFails"),
- result.getFailures().get(0).getDescription());
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
+ assertThat(result.getFailures().get(0).getDescription())
+ .isEqualTo(
+ Description.createTestDescription(SampleFailingTest.class, "testThatAlwaysFails"));
}
@Test
@@ -304,10 +307,10 @@ public class JUnit4RunnerTest {
JUnit4Runner runner = createRunner(SampleSuite.class);
Result result = runner.run();
- assertEquals(1, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
- assertTrue(result.getFailures().get(0).getMessage().contains("No tests found"));
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
+ assertThat(result.getFailures().get(0).getMessage()).contains("No tests found");
}
@Test
@@ -316,12 +319,12 @@ public class JUnit4RunnerTest {
JUnit4Runner runner = createRunner(SampleSuite.class);
Result result = runner.run();
- assertEquals(2, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
- assertEquals(
- Description.createTestDescription(SampleFailingTest.class, "testThatAlwaysFails"),
- result.getFailures().get(0).getDescription());
+ assertThat(result.getRunCount()).isEqualTo(2);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
+ assertThat(result.getFailures().get(0).getDescription())
+ .isEqualTo(
+ Description.createTestDescription(SampleFailingTest.class, "testThatAlwaysFails"));
}
@Test
@@ -339,12 +342,12 @@ public class JUnit4RunnerTest {
verify(shardingEnvironment).touchShardFile();
- assertEquals(2, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
- assertEquals(
- Description.createTestDescription(SampleFailingTest.class, "testThatAlwaysFails"),
- result.getFailures().get(0).getDescription());
+ assertThat(result.getRunCount()).isEqualTo(2);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
+ assertThat(result.getFailures().get(0).getDescription())
+ .isEqualTo(
+ Description.createTestDescription(SampleFailingTest.class, "testThatAlwaysFails"));
}
@Test
@@ -361,9 +364,9 @@ public class JUnit4RunnerTest {
verify(shardingEnvironment).touchShardFile();
- assertEquals(0, result.getRunCount());
- assertEquals(0, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
+ assertThat(result.getRunCount()).isEqualTo(0);
+ assertThat(result.getFailureCount()).isEqualTo(0);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
}
@Test
@@ -379,10 +382,10 @@ public class JUnit4RunnerTest {
JUnit4Runner runner = createRunner(SampleSuite.class);
Result result = runner.run();
- assertEquals(1, result.getRunCount());
- assertEquals(1, result.getFailureCount());
- assertEquals(0, result.getIgnoreCount());
- assertTrue(result.getFailures().get(0).getMessage().contains("No tests found"));
+ assertThat(result.getRunCount()).isEqualTo(1);
+ assertThat(result.getFailureCount()).isEqualTo(1);
+ assertThat(result.getIgnoreCount()).isEqualTo(0);
+ assertThat(result.getFailures().get(0).getMessage()).contains("No tests found");
verify(shardingEnvironment).touchShardFile();
verify(shardingFilters).createShardingFilter(anyListOf(Description.class));
@@ -397,7 +400,7 @@ public class JUnit4RunnerTest {
runner.run();
fail();
} catch (IllegalStateException e) {
- assertThat(e.getMessage()).startsWith("Unsupported JUnit Runner API version");
+ assertThat(e).hasMessageThat().startsWith("Unsupported JUnit Runner API version");
}
}
@@ -417,7 +420,7 @@ public class JUnit4RunnerTest {
Class<?> testClass) {
ByteArrayOutputStream expectedOutputStream = getExpectedOutput(testClass);
- assertEquals(extractOutput(expectedOutputStream), extractOutput(outputStream));
+ assertThat(extractOutput(outputStream)).isEqualTo(extractOutput(expectedOutputStream));
}
private String extractOutput(ByteArrayOutputStream outputStream) {
@@ -487,7 +490,7 @@ public class JUnit4RunnerTest {
@Test
public void testThatAlwaysFails() {
- assertEquals("Test Japan.", "Test \u65E5本.");
+ assertThat("Test \u65E5本.").isEqualTo("Test Japan.");
}
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4TestModelBuilderTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4TestModelBuilderTest.java
index 8a355842c2..b409163617 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4TestModelBuilderTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/junit4/JUnit4TestModelBuilderTest.java
@@ -14,9 +14,8 @@
package com.google.testing.junit.runner.junit4;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.testing.junit.runner.sharding.ShardingFilters.DEFAULT_SHARDING_STRATEGY;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -106,16 +105,16 @@ public class JUnit4TestModelBuilderTest {
TestSuiteModel model = modelBuilder.get();
TestNode suiteNode = Iterables.getOnlyElement(model.getTopLevelTestSuites());
- assertEquals(suite, suiteNode.getDescription());
+ assertThat(suiteNode.getDescription()).isEqualTo(suite);
List<TestNode> testCases = suiteNode.getChildren();
- assertEquals(2, testCases.size());
+ assertThat(testCases).hasSize(2);
TestNode testOneNode = testCases.get(0);
TestNode testTwoNode = testCases.get(1);
- assertEquals(testOne, testOneNode.getDescription());
- assertEquals(testTwo, testTwoNode.getDescription());
- assertTrue(testOneNode.getChildren().isEmpty());
- assertTrue(testTwoNode.getChildren().isEmpty());
- assertEquals(2, model.getNumTestCases());
+ assertThat(testOneNode.getDescription()).isEqualTo(testOne);
+ assertThat(testTwoNode.getDescription()).isEqualTo(testTwo);
+ assertThat(testOneNode.getChildren()).isEmpty();
+ assertThat(testTwoNode.getChildren()).isEmpty();
+ assertThat(model.getNumTestCases()).isEqualTo(2);
}
@Test
@@ -132,13 +131,13 @@ public class JUnit4TestModelBuilderTest {
TestSuiteModel model = modelBuilder.get();
TestNode topSuiteNode = Iterables.getOnlyElement(model.getTopLevelTestSuites());
- assertEquals(topSuite, topSuiteNode.getDescription());
+ assertThat(topSuiteNode.getDescription()).isEqualTo(topSuite);
TestNode innerSuiteNode = Iterables.getOnlyElement(topSuiteNode.getChildren());
- assertEquals(innerSuite, innerSuiteNode.getDescription());
+ assertThat(innerSuiteNode.getDescription()).isEqualTo(innerSuite);
TestNode testOneNode = Iterables.getOnlyElement(innerSuiteNode.getChildren());
- assertEquals(testOne, testOneNode.getDescription());
- assertTrue(testOneNode.getChildren().isEmpty());
- assertEquals(1, model.getNumTestCases());
+ assertThat(testOneNode.getDescription()).isEqualTo(testOne);
+ assertThat(testOneNode.getChildren()).isEmpty();
+ assertThat(model.getNumTestCases()).isEqualTo(1);
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestCaseNodeTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestCaseNodeTest.java
index 07a768cbff..852dd7b2f2 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestCaseNodeTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestCaseNodeTest.java
@@ -14,10 +14,7 @@
package com.google.testing.junit.runner.model;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -44,7 +41,7 @@ public class TestCaseNodeTest {
@Test
public void assertIsTestCase() {
- assertTrue(new TestCaseNode(testCase, new TestSuiteNode(suite)).isTestCase());
+ assertThat(new TestCaseNode(testCase, new TestSuiteNode(suite)).isTestCase()).isTrue();
}
@Test
@@ -144,16 +141,16 @@ public class TestCaseNodeTest {
private void assertStatusAndTiming(
TestCaseNode testCase, TestResult.Status status, long start, long duration) {
TestResult result = testCase.getResult();
- assertEquals(status, result.getStatus());
- assertNotNull(result.getRunTimeInterval());
- assertEquals(start, result.getRunTimeInterval().getStartMillis());
- assertEquals(duration, result.getRunTimeInterval().toDurationMillis());
+ assertThat(result.getStatus()).isEqualTo(status);
+ assertThat(result.getRunTimeInterval()).isNotNull();
+ assertThat(result.getRunTimeInterval().getStartMillis()).isEqualTo(start);
+ assertThat(result.getRunTimeInterval().toDurationMillis()).isEqualTo(duration);
}
private void assertStatusWithoutTiming(TestCaseNode testCase, TestResult.Status status) {
TestResult result = testCase.getResult();
- assertEquals(status, result.getStatus());
- assertNull(result.getRunTimeInterval());
+ assertThat(result.getStatus()).isEqualTo(status);
+ assertThat(result.getRunTimeInterval()).isNull();
}
static class TestSuite {
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestIntervalTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestIntervalTest.java
index ebab4a7cd5..26573e8f55 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestIntervalTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestIntervalTest.java
@@ -14,7 +14,7 @@
package com.google.testing.junit.runner.model;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import java.util.Date;
import java.util.TimeZone;
@@ -31,12 +31,12 @@ public class TestIntervalTest {
@Test
public void testCreation() {
TestInterval interval = new TestInterval(123456, 234567);
- assertEquals(123456, interval.getStartMillis());
- assertEquals(234567, interval.getEndMillis());
+ assertThat(interval.getStartMillis()).isEqualTo(123456);
+ assertThat(interval.getEndMillis()).isEqualTo(234567);
interval = new TestInterval(123456, 123456);
- assertEquals(123456, interval.getStartMillis());
- assertEquals(123456, interval.getEndMillis());
+ assertThat(interval.getStartMillis()).isEqualTo(123456);
+ assertThat(interval.getEndMillis()).isEqualTo(123456);
}
@Test
@@ -48,18 +48,17 @@ public class TestIntervalTest {
@Test
public void testToDuration() {
- assertEquals(100, new TestInterval(50, 150).toDurationMillis());
- assertEquals(0, new TestInterval(100, 100).toDurationMillis());
+ assertThat(new TestInterval(50, 150).toDurationMillis()).isEqualTo(100);
+ assertThat(new TestInterval(100, 100).toDurationMillis()).isEqualTo(0);
}
@Test
public void testDateFormat() {
Date date = new Date(1471709734000L);
TestInterval interval = new TestInterval(date.getTime(), date.getTime() + 100);
- assertEquals(
- "2016-08-20T12:15:34.000-04:00",
- interval.startInstantToString(TimeZone.getTimeZone("America/New_York")));
- assertEquals(
- "2016-08-20T16:15:34.000Z", interval.startInstantToString(TimeZone.getTimeZone("GMT")));
+ assertThat(interval.startInstantToString(TimeZone.getTimeZone("America/New_York")))
+ .isEqualTo("2016-08-20T12:15:34.000-04:00");
+ assertThat(interval.startInstantToString(TimeZone.getTimeZone("GMT")))
+ .isEqualTo("2016-08-20T16:15:34.000Z");
}
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestSuiteNodeTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestSuiteNodeTest.java
index 61b97cdd6f..e6448c55ef 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestSuiteNodeTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/TestSuiteNodeTest.java
@@ -14,11 +14,12 @@
package com.google.testing.junit.runner.model;
-import static org.junit.Assert.assertFalse;
+import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.Description;
@@ -45,7 +46,7 @@ public class TestSuiteNodeTest {
@Test
public void testIsTestCase() {
- assertFalse(testSuiteNode.isTestCase());
+ assertThat(testSuiteNode.isTestCase()).isFalse();
verifyZeroInteractions(testCaseNode);
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/XmlWriterTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/XmlWriterTest.java
index 423d1f4f3d..1fed6a319b 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/XmlWriterTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/model/XmlWriterTest.java
@@ -14,7 +14,7 @@
package com.google.testing.junit.runner.model;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Joiner;
import java.io.ByteArrayOutputStream;
@@ -226,7 +226,7 @@ public class XmlWriterTest {
private void assertHasContents(String... contents) throws UnsupportedEncodingException {
Object[] expected = contents;
-
- assertEquals(LINE_JOINER.join(expected).trim(), outputStream.toString("UTF-8").trim());
+
+ assertThat(outputStream.toString("UTF-8").trim()).isEqualTo(LINE_JOINER.join(expected).trim());
}
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/RoundRobinShardingFilterTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/RoundRobinShardingFilterTest.java
index 5aa55aa467..8fe314d269 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/RoundRobinShardingFilterTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/RoundRobinShardingFilterTest.java
@@ -14,19 +14,17 @@
package com.google.testing.junit.runner.sharding;
+import static com.google.common.truth.Truth.assertThat;
+
import com.google.testing.junit.runner.sharding.api.ShardingFilterFactory;
import com.google.testing.junit.runner.sharding.testing.RoundRobinShardingFilterFactory;
import com.google.testing.junit.runner.sharding.testing.ShardingFilterTestCase;
-
-import org.junit.runner.Description;
-import org.junit.runner.manipulation.Filter;
-
import java.util.List;
import java.util.Map;
+import org.junit.runner.Description;
+import org.junit.runner.manipulation.Filter;
-/**
- * Tests for the {@link RoundRobinShardingFilter}.
- */
+/** Tests for the {@link RoundRobinShardingFilter}. */
public class RoundRobinShardingFilterTest extends ShardingFilterTestCase {
private static final List<Description> GENERIC_TEST_DESCRIPTIONS =
@@ -39,15 +37,15 @@ public class RoundRobinShardingFilterTest extends ShardingFilterTestCase {
public void testShardingIsBalanced() {
Map<Filter, List<Description>> run1 = simulateTestRun(FILTERS_1, GENERIC_TEST_DESCRIPTIONS);
- assertEquals(2, run1.get(FILTERS_1.get(0)).size());
- assertEquals(2, run1.get(FILTERS_1.get(1)).size());
- assertEquals(2, run1.get(FILTERS_1.get(2)).size());
+ assertThat(run1.get(FILTERS_1.get(0))).hasSize(2);
+ assertThat(run1.get(FILTERS_1.get(1))).hasSize(2);
+ assertThat(run1.get(FILTERS_1.get(2))).hasSize(2);
Map<Filter, List<Description>> run2 = simulateTestRun(FILTERS_2, GENERIC_TEST_DESCRIPTIONS);
- assertEquals(2, run2.get(FILTERS_2.get(0)).size());
- assertEquals(2, run2.get(FILTERS_2.get(1)).size());
- assertEquals(1, run2.get(FILTERS_2.get(2)).size());
- assertEquals(1, run2.get(FILTERS_2.get(3)).size());
+ assertThat(run2.get(FILTERS_2.get(0))).hasSize(2);
+ assertThat(run2.get(FILTERS_2.get(1))).hasSize(2);
+ assertThat(run2.get(FILTERS_2.get(2))).hasSize(1);
+ assertThat(run2.get(FILTERS_2.get(3))).hasSize(1);
}
public void testShouldRun_throwsExceptionForUnknownDescription() {
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingEnvironmentTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingEnvironmentTest.java
index b8ab333ca2..69d9f20601 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingEnvironmentTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingEnvironmentTest.java
@@ -14,18 +14,15 @@
package com.google.testing.junit.runner.sharding;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.testutil.TestUtils;
+import java.io.File;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.File;
-/**
- * Tests interactions with the test environment related to sharding.
- */
+/** Tests interactions with the test environment related to sharding. */
@RunWith(JUnit4.class)
public class ShardingEnvironmentTest {
@@ -33,10 +30,10 @@ public class ShardingEnvironmentTest {
@Test
public void testTouchShardingFile() {
File shardFile = new File(TestUtils.tmpDirFile(), "shard_file_123");
- assertFalse(shardFile.exists());
+ assertThat(shardFile.exists()).isFalse();
try {
ShardingEnvironment.touchShardFile(shardFile);
- assertTrue(shardFile.exists());
+ assertThat(shardFile.exists()).isTrue();
} finally {
shardFile.delete();
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingFiltersTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingFiltersTest.java
index ec55f91a56..2495cfa103 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingFiltersTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/sharding/ShardingFiltersTest.java
@@ -15,7 +15,6 @@
package com.google.testing.junit.runner.sharding;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import com.google.testing.junit.runner.sharding.api.ShardingFilterFactory;
@@ -51,9 +50,9 @@ public class ShardingFiltersTest {
assertThat(filter).isInstanceOf(RoundRobinShardingFilter.class);
RoundRobinShardingFilter shardingFilter = (RoundRobinShardingFilter) filter;
- assertEquals(expectedFilter.testToShardMap, shardingFilter.testToShardMap);
- assertEquals(expectedFilter.shardIndex, shardingFilter.shardIndex);
- assertEquals(expectedFilter.totalShards, shardingFilter.totalShards);
+ assertThat(shardingFilter.testToShardMap).isEqualTo(expectedFilter.testToShardMap);
+ assertThat(shardingFilter.shardIndex).isEqualTo(expectedFilter.shardIndex);
+ assertThat(shardingFilter.totalShards).isEqualTo(expectedFilter.totalShards);
}
@Test
@@ -68,8 +67,8 @@ public class ShardingFiltersTest {
ShardingFilters shardingFilters = new ShardingFilters(mockShardingEnvironment);
Filter filter = shardingFilters.createShardingFilter(descriptions);
- assertEquals("com.google.testing.junit.runner.sharding.ShardingFiltersTest.TestFilter",
- filter.getClass().getCanonicalName());
+ assertThat(filter.getClass().getCanonicalName())
+ .isEqualTo("com.google.testing.junit.runner.sharding.ShardingFiltersTest.TestFilter");
}
public static class TestFilterFactory implements ShardingFilterFactory {
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed/InternationalCharsTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed/InternationalCharsTest.java
index ee7979ee74..7d3c1c8d30 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed/InternationalCharsTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/testbed/InternationalCharsTest.java
@@ -14,6 +14,8 @@
package com.google.testing.junit.runner.testbed;
+import static com.google.common.truth.Truth.assertThat;
+
import junit.framework.TestCase;
/**
@@ -22,6 +24,6 @@ import junit.framework.TestCase;
*/
public class InternationalCharsTest extends TestCase {
public void testThatAlwaysFails() {
- assertEquals("Test Japan.", "Test \u65E5本.");
+ assertThat("Test \u65E5本.").isEqualTo("Test Japan.");
}
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java
index ab0c704a2e..077342870d 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java
@@ -14,9 +14,8 @@
package com.google.testing.junit.runner.util;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import java.security.Permission;
@@ -57,7 +56,7 @@ public class GoogleTestSecurityManagerTest {
private void installTestSecurityManager() {
SecurityManager previousSecurityManager = System.getSecurityManager();
- assertNull(previousSecurityManager);
+ assertThat(previousSecurityManager).isNull();
installedSecurityManager = new GoogleTestSecurityManager();
System.setSecurityManager(installedSecurityManager);
@@ -96,7 +95,7 @@ public class GoogleTestSecurityManagerTest {
// create a security manager to use, but don't install it.
GoogleTestSecurityManager sm = new GoogleTestSecurityManager();
- assertTrue(sm.isEnabled());
+ assertThat(sm.isEnabled()).isTrue();
try {
sm.checkExit(0);
fail("GoogleTestSecurityManager allowed exit while enabled.");
@@ -105,12 +104,12 @@ public class GoogleTestSecurityManagerTest {
}
sm.setEnabled(false);
- assertTrue(!sm.isEnabled());
+ assertThat(!sm.isEnabled()).isTrue();
sm.checkExit(0); // should allow
sm.setEnabled(true);
- assertTrue(sm.isEnabled());
+ assertThat(sm.isEnabled()).isTrue();
try {
sm.checkExit(0);
fail("GoogleTestSecurityManager allowed exit while enabled.");
@@ -123,16 +122,22 @@ public class GoogleTestSecurityManagerTest {
public void testUninstallIfInstalled_whenInstalled() {
installTestSecurityManager();
GoogleTestSecurityManager.uninstallIfInstalled();
-
- assertTrue("Security manager should be enabled", installedSecurityManager.isEnabled());
- assertNull("Security manager should be uninstalled", System.getSecurityManager());
+
+ assertWithMessage("Security manager should be enabled")
+ .that(installedSecurityManager.isEnabled())
+ .isTrue();
+ assertWithMessage("Security manager should be uninstalled")
+ .that(System.getSecurityManager())
+ .isNull();
}
@Test
public void testUninstallIfInstalled_whenNoSecurityManagerInstalled() {
GoogleTestSecurityManager.uninstallIfInstalled();
-
- assertNull("No security manager should be uninstalled", System.getSecurityManager());
+
+ assertWithMessage("No security manager should be uninstalled")
+ .that(System.getSecurityManager())
+ .isNull();
}
@Test
@@ -140,8 +145,8 @@ public class GoogleTestSecurityManagerTest {
PermissiveSecurityManager otherSecurityManager = new PermissiveSecurityManager();
System.setSecurityManager(otherSecurityManager);
GoogleTestSecurityManager.uninstallIfInstalled();
-
- assertSame(otherSecurityManager, System.getSecurityManager());
+
+ assertThat(System.getSecurityManager()).isSameAs(otherSecurityManager);
System.setSecurityManager(null);
}
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ConcatenateStrategyTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ConcatenateStrategyTest.java
index 45c78dd324..1d46ffa8a3 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ConcatenateStrategyTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ConcatenateStrategyTest.java
@@ -14,20 +14,17 @@
package com.google.devtools.build.singlejar;
+import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
-/**
- * Unit tests for {@link ConcatenateStrategy}.
- */
+/** Unit tests for {@link ConcatenateStrategy}. */
@RunWith(JUnit4.class)
public class ConcatenateStrategyTest {
@@ -51,25 +48,25 @@ public class ConcatenateStrategyTest {
@Test
public void testSingleInput() throws IOException {
- assertEquals("a", merge("a"));
- assertEquals("a", mergeNoNewLine("a"));
+ assertThat(merge("a")).isEqualTo("a");
+ assertThat(mergeNoNewLine("a")).isEqualTo("a");
}
@Test
public void testTwoInputs() throws IOException {
- assertEquals("a\nb", merge("a\n", "b"));
- assertEquals("a\nb", mergeNoNewLine("a\n", "b"));
+ assertThat(merge("a\n", "b")).isEqualTo("a\nb");
+ assertThat(mergeNoNewLine("a\n", "b")).isEqualTo("a\nb");
}
@Test
public void testAutomaticNewline() throws IOException {
- assertEquals("a\nb", merge("a", "b"));
- assertEquals("ab", mergeNoNewLine("a", "b"));
+ assertThat(merge("a", "b")).isEqualTo("a\nb");
+ assertThat(mergeNoNewLine("a", "b")).isEqualTo("ab");
}
@Test
public void testAutomaticNewlineAndEmptyFile() throws IOException {
- assertEquals("a\nb", merge("a", "", "b"));
- assertEquals("ab", mergeNoNewLine("a", "", "b"));
+ assertThat(merge("a", "", "b")).isEqualTo("a\nb");
+ assertThat(mergeNoNewLine("a", "", "b")).isEqualTo("ab");
}
}
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/CopyEntryFilterTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/CopyEntryFilterTest.java
index 68bebafb7f..47f4a361d0 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/CopyEntryFilterTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/CopyEntryFilterTest.java
@@ -14,18 +14,15 @@
package com.google.devtools.build.singlejar;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
+import java.io.IOException;
+import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.IOException;
-import java.util.Arrays;
-
-/**
- * Unit tests for {@link CopyEntryFilter}.
- */
+/** Unit tests for {@link CopyEntryFilter}. */
@RunWith(JUnit4.class)
public class CopyEntryFilterTest {
@@ -33,7 +30,7 @@ public class CopyEntryFilterTest {
public void testSingleInput() throws IOException {
RecordingCallback callback = new RecordingCallback();
new CopyEntryFilter().accept("abc", callback);
- assertEquals(Arrays.asList("copy"), callback.calls);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("copy"));
}
}
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/DefaultJarEntryFilterTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/DefaultJarEntryFilterTest.java
index df92ee62c1..6b9799da15 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/DefaultJarEntryFilterTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/DefaultJarEntryFilterTest.java
@@ -14,16 +14,15 @@
package com.google.devtools.build.singlejar;
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
+import static com.google.common.truth.Truth.assertThat;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.jar.JarFile;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Unit tests for {@link DefaultJarEntryFilter}.
@@ -37,55 +36,56 @@ public class DefaultJarEntryFilterTest {
public void testSingleInput() throws IOException {
RecordingCallback callback = new RecordingCallback();
new DefaultJarEntryFilter().accept("abc", callback);
- assertEquals(Arrays.asList("copy"), callback.calls);
- assertEquals(Arrays.asList(DOS_EPOCH), callback.dates);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("copy"));
+ assertThat(callback.dates).isEqualTo(Arrays.asList(DOS_EPOCH));
}
@Test
public void testProtobufExtensionsInput() throws IOException {
RecordingCallback callback = new RecordingCallback();
new DefaultJarEntryFilter().accept("protobuf.meta", callback);
- assertEquals(Arrays.asList("customMerge"), callback.calls);
- assertEquals(Arrays.asList(DOS_EPOCH), callback.dates);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("customMerge"));
+ assertThat(callback.dates).isEqualTo(Arrays.asList(DOS_EPOCH));
}
@Test
public void testManifestInput() throws IOException {
RecordingCallback callback = new RecordingCallback();
new DefaultJarEntryFilter().accept(JarFile.MANIFEST_NAME, callback);
- assertEquals(Arrays.asList("skip"), callback.calls);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("skip"));
}
@Test
public void testServiceInput() throws IOException {
RecordingCallback callback = new RecordingCallback();
new DefaultJarEntryFilter().accept("META-INF/services/any.service", callback);
- assertEquals(Arrays.asList("customMerge"), callback.calls);
- assertEquals(Arrays.asList(DOS_EPOCH), callback.dates);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("customMerge"));
+ assertThat(callback.dates).isEqualTo(Arrays.asList(DOS_EPOCH));
}
@Test
public void testSpringHandlers() throws IOException {
RecordingCallback callback = new RecordingCallback();
new DefaultJarEntryFilter().accept("META-INF/spring.handlers", callback);
- assertEquals(Arrays.asList("customMerge"), callback.calls);
- assertEquals(Arrays.asList(DOS_EPOCH), callback.dates);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("customMerge"));
+ assertThat(callback.dates).isEqualTo(Arrays.asList(DOS_EPOCH));
}
@Test
public void testSpringSchemas() throws IOException {
RecordingCallback callback = new RecordingCallback();
new DefaultJarEntryFilter().accept("META-INF/spring.schemas", callback);
- assertEquals(Arrays.asList("customMerge"), callback.calls);
- assertEquals(Arrays.asList(DOS_EPOCH), callback.dates);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("customMerge"));
+ assertThat(callback.dates).isEqualTo(Arrays.asList(DOS_EPOCH));
}
@Test
public void testClassInput() throws IOException {
RecordingCallback callback = new RecordingCallback();
new DefaultJarEntryFilter().accept("a.class", callback);
- assertEquals(Arrays.asList("copy"), callback.calls);
- assertEquals(Arrays.asList(DefaultJarEntryFilter.DOS_EPOCH_PLUS_2_SECONDS), callback.dates);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("copy"));
+ assertThat(callback.dates)
+ .isEqualTo(Arrays.asList(DefaultJarEntryFilter.DOS_EPOCH_PLUS_2_SECONDS));
}
@Test
@@ -95,7 +95,7 @@ public class DefaultJarEntryFilterTest {
filter.accept("a.SF", callback);
filter.accept("a.DSA", callback);
filter.accept("a.RSA", callback);
- assertEquals(Arrays.asList("skip", "skip", "skip"), callback.calls);
- assertEquals(Arrays.<Date>asList(), callback.dates);
+ assertThat(callback.calls).isEqualTo(Arrays.asList("skip", "skip", "skip"));
+ assertThat(callback.dates).isEqualTo(Arrays.<Date>asList());
}
}
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/FakeZipFile.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/FakeZipFile.java
index cdddd0d0e7..8b9bdf75bf 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/FakeZipFile.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/FakeZipFile.java
@@ -14,15 +14,12 @@
package com.google.devtools.build.singlejar;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import com.google.devtools.build.singlejar.SingleJarTest.EntryMode;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -54,9 +51,9 @@ public final class FakeZipFile {
private static void assertSameByteArray(byte[] expected, byte[] actual) {
if (expected == null) {
- assertNull(actual);
+ assertThat(actual).isNull();
} else {
- assertArrayEquals(expected, actual);
+ assertThat(actual).isEqualTo(expected);
}
}
@@ -111,7 +108,7 @@ public final class FakeZipFile {
public void assertNext(ZipInputStream zipInput) throws IOException {
ZipEntry zipEntry = zipInput.getNextEntry();
- assertNotNull(zipEntry);
+ assertThat(zipEntry).isNotNull();
switch (mode) {
case EXPECT_DEFLATE:
assertEquals(ZipEntry.DEFLATED, zipEntry.getMethod());
@@ -123,9 +120,9 @@ public final class FakeZipFile {
// we don't care.
break;
}
- assertEquals(name, zipEntry.getName());
+ assertThat(zipEntry.getName()).isEqualTo(name);
if (date != null) {
- assertEquals(date.getTime(), zipEntry.getTime());
+ assertThat(zipEntry.getTime()).isEqualTo(date.getTime());
}
assertSameByteArray(extra, zipEntry.getExtra());
content.validate(readZipEntryContent(zipInput));
@@ -210,20 +207,20 @@ public final class FakeZipFile {
offset += preamble.length;
length -= offset;
byte[] maybePreamble = Arrays.copyOfRange(data, 0, offset);
- assertTrue(Arrays.equals(preamble, maybePreamble));
+ assertThat(maybePreamble).isEqualTo(preamble);
}
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(data, offset, length));
for (FakeZipEntry entry : entries) {
entry.assertNext(zipInput);
}
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
// Verify that the end of central directory data is correct.
// This assumes that the end of directory is at the end of input and that there is no zip file
// comment.
int count = getUnsignedShort(data, data.length-14);
- assertEquals(entries.size(), count);
+ assertThat(count).isEqualTo(entries.size());
count = getUnsignedShort(data, data.length-12);
- assertEquals(entries.size(), count);
+ assertThat(count).isEqualTo(entries.size());
}
/**
@@ -244,22 +241,26 @@ public final class FakeZipFile {
parseZipEntry(expectedZip, expectedFileList, expectedEntries, expectedEntryContents);
parseZipEntry(actualZip, actualFileList, actualEntries, actualEntryContents);
// Compare the ordered file list first.
- assertEquals(expectedFileList.toString(), actualFileList.toString());
+ assertThat(actualFileList.toString()).isEqualTo(expectedFileList.toString());
// Then compare each entry.
for (String name : expectedEntries.keySet()) {
ZipEntry expectedEntry = expectedEntries.get(name);
ZipEntry actualEntry = actualEntries.get(name);
- assertEquals("Time differs for " + name, expectedEntry.getTime(), actualEntry.getTime());
- assertArrayEquals("Extraneous content differs for " + name,
- expectedEntry.getExtra(), actualEntry.getExtra());
- assertArrayEquals("Content differs for " + name,
- expectedEntryContents.get(name), actualEntryContents.get(name));
+ assertWithMessage("Time differs for " + name)
+ .that(actualEntry.getTime())
+ .isEqualTo(expectedEntry.getTime());
+ assertWithMessage("Extraneous content differs for " + name)
+ .that(actualEntry.getExtra())
+ .isEqualTo(expectedEntry.getExtra());
+ assertWithMessage("Content differs for " + name)
+ .that(actualEntryContents.get(name))
+ .isEqualTo(expectedEntryContents.get(name));
}
// Finally do a binary array comparison to be sure that test fails if files are different in
// some way we don't test.
- assertArrayEquals(expected, actual);
+ assertThat(actual).isEqualTo(expected);
}
private static void parseZipEntry(ZipInputStream expectedZip, StringBuffer expectedFileList,
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/MockSimpleFileSystem.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/MockSimpleFileSystem.java
index ce1d3cc4c7..6ebef2001f 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/MockSimpleFileSystem.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/MockSimpleFileSystem.java
@@ -14,10 +14,8 @@
package com.google.devtools.build.singlejar;
+import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -61,8 +59,8 @@ public final class MockSimpleFileSystem implements SimpleFileSystem {
@Override
public OutputStream getOutputStream(String filename) {
- assertEquals(outputFileName, filename);
- assertNull(out);
+ assertThat(filename).isEqualTo(outputFileName);
+ assertThat(out).isNull();
out = new ByteArrayOutputStream();
return out;
}
@@ -89,14 +87,14 @@ public final class MockSimpleFileSystem implements SimpleFileSystem {
@Override
public boolean delete(String filename) {
- assertEquals(outputFileName, filename);
- assertNotNull(out);
+ assertThat(filename).isEqualTo(outputFileName);
+ assertThat(out).isNotNull();
out = null;
return true;
}
public byte[] toByteArray() {
- assertNotNull(out);
+ assertThat(out).isNotNull();
return out.toByteArray();
}
}
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/OptionFileExpanderTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/OptionFileExpanderTest.java
index 86e6b375d8..8c380d4e4c 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/OptionFileExpanderTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/OptionFileExpanderTest.java
@@ -14,16 +14,11 @@
package com.google.devtools.build.singlejar;
+import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.devtools.build.singlejar.OptionFileExpander.OptionFileProvider;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -31,6 +26,9 @@ import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Unit tests for {@link OptionFileExpander}.
@@ -59,8 +57,8 @@ public class OptionFileExpanderTest {
@Test
public void testNoExpansion() throws IOException {
OptionFileExpander expander = new OptionFileExpander(new StoredOptionFileProvider());
- assertEquals(Arrays.asList("--some", "option", "list"),
- expander.expandArguments(Arrays.asList("--some", "option", "list")));
+ assertThat(expander.expandArguments(Arrays.asList("--some", "option", "list")))
+ .isEqualTo(Arrays.asList("--some", "option", "list"));
}
@Test
@@ -68,8 +66,8 @@ public class OptionFileExpanderTest {
StoredOptionFileProvider provider = new StoredOptionFileProvider();
provider.addFile("options", "--some option list");
OptionFileExpander expander = new OptionFileExpander(provider);
- assertEquals(Arrays.asList("--some", "option", "list"),
- expander.expandArguments(Arrays.asList("@options")));
+ assertThat(expander.expandArguments(Arrays.asList("@options")))
+ .isEqualTo(Arrays.asList("--some", "option", "list"));
}
@Test
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/PrefixListPathFilterTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/PrefixListPathFilterTest.java
index 4c588bfd51..030ae277a5 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/PrefixListPathFilterTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/PrefixListPathFilterTest.java
@@ -14,12 +14,10 @@
package com.google.devtools.build.singlejar;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.singlejar.DefaultJarEntryFilter.PathFilter;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -43,12 +41,14 @@ public class PrefixListPathFilterTest {
}
private void assertExcluded(String path) {
- assertFalse(path + " should have been excluded, but was included",
- filter.allowed(path));
+ assertWithMessage(path + " should have been excluded, but was included")
+ .that(filter.allowed(path))
+ .isFalse();
}
private void assertIncluded(String path) {
- assertTrue(path + " should have been included but was not",
- filter.allowed(path));
+ assertWithMessage(path + " should have been included but was not")
+ .that(filter.allowed(path))
+ .isTrue();
}
}
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/SingleJarTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/SingleJarTest.java
index 4b66d13e51..3e89489b0b 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/SingleJarTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/SingleJarTest.java
@@ -16,7 +16,6 @@ package com.google.devtools.build.singlejar;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
@@ -65,8 +64,8 @@ public class SingleJarTest {
Collections.sort(expectedBuildInfos);
String[] actualBuildInfos = actualBuildInfo.split("\n");
Arrays.sort(actualBuildInfos);
- assertEquals(LINEFEED_JOINER.join(expectedBuildInfos),
- LINEFEED_JOINER.join(actualBuildInfos));
+ assertThat(LINEFEED_JOINER.join(actualBuildInfos))
+ .isEqualTo(LINEFEED_JOINER.join(expectedBuildInfos));
}
}
@@ -91,7 +90,8 @@ public class SingleJarTest {
String actualManifest = new String(content, StandardCharsets.UTF_8);
String[] actualManifestLines = actualManifest.trim().split("\r\n");
Arrays.sort(actualManifestLines);
- assertEquals(LINEFEED_JOINER.join(manifestLines), LINEFEED_JOINER.join(actualManifestLines));
+ assertThat(LINEFEED_JOINER.join(actualManifestLines))
+ .isEqualTo(LINEFEED_JOINER.join(manifestLines));
}
}
@@ -145,7 +145,7 @@ public class SingleJarTest {
private void assertStripFirstLine(String expected, String testCase) {
byte[] result = SingleJar.stripFirstLine(testCase.getBytes(StandardCharsets.UTF_8));
- assertEquals(expected, new String(result, UTF_8));
+ assertThat(new String(result, UTF_8)).isEqualTo(expected);
}
@Test
@@ -596,7 +596,7 @@ public class SingleJarTest {
"--resources", "a/b/c", "a/b/c"));
fail();
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains("already contains a file named 'a/b/c'.");
+ assertThat(e).hasMessageThat().contains("already contains a file named 'a/b/c'.");
}
}
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ZipCombinerTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ZipCombinerTest.java
index c1a94e2490..bb287637ea 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ZipCombinerTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/ZipCombinerTest.java
@@ -17,10 +17,6 @@ package com.google.devtools.build.singlejar;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ArrayListMultimap;
@@ -31,14 +27,6 @@ import com.google.devtools.build.zip.ExtraData;
import com.google.devtools.build.zip.ZipFileEntry;
import com.google.devtools.build.zip.ZipReader;
import com.google.devtools.build.zip.ZipUtil;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -63,6 +51,12 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Unit tests for {@link ZipCombiner}.
@@ -113,16 +107,16 @@ public class ZipCombinerTest {
private void assertEntry(ZipInputStream zipInput, String filename, long time, byte[] content)
throws IOException {
ZipEntry zipEntry = zipInput.getNextEntry();
- assertNotNull(zipEntry);
- assertEquals(filename, zipEntry.getName());
- assertEquals(time, zipEntry.getTime());
+ assertThat(zipEntry).isNotNull();
+ assertThat(zipEntry.getName()).isEqualTo(filename);
+ assertThat(zipEntry.getTime()).isEqualTo(time);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesCopied;
while ((bytesCopied = zipInput.read(buffer)) != -1) {
out.write(buffer, 0, bytesCopied);
}
- assertTrue(Arrays.equals(content, out.toByteArray()));
+ assertThat(out.toByteArray()).isEqualTo(content);
}
private void assertEntry(ZipInputStream zipInput, String filename, byte[] content)
@@ -209,7 +203,7 @@ public class ZipCombinerTest {
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!");
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -221,7 +215,7 @@ public class ZipCombinerTest {
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!");
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -234,7 +228,7 @@ public class ZipCombinerTest {
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!");
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -246,7 +240,7 @@ public class ZipCombinerTest {
}
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -258,7 +252,7 @@ public class ZipCombinerTest {
zipCombiner.addZip(writeInputStreamToFile(new ByteArrayInputStream(new byte[] {1, 2, 3, 4})));
}
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
private InputStream asStream(String content) {
@@ -273,7 +267,7 @@ public class ZipCombinerTest {
}
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -285,7 +279,7 @@ public class ZipCombinerTest {
}
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
static final class MergeStrategyPlaceHolder implements CustomMergeStrategy {
@@ -352,7 +346,7 @@ public class ZipCombinerTest {
try (ZipCombiner zipCombiner = new ZipCombiner(mockFilter, out)) {
zipCombiner.addZip(sampleZip());
}
- assertEquals(Arrays.asList("hello.txt"), mockFilter.calls);
+ assertThat(mockFilter.calls).containsExactly("hello.txt");
}
@Test
@@ -363,7 +357,7 @@ public class ZipCombinerTest {
zipCombiner.addZip(sampleZip());
zipCombiner.addZip(sampleZip());
}
- assertEquals(Arrays.asList("hello.txt"), mockFilter.calls);
+ assertThat(mockFilter.calls).containsExactly("hello.txt");
}
@Test
@@ -375,11 +369,11 @@ public class ZipCombinerTest {
zipCombiner.addZip(sampleZip());
zipCombiner.addZip(sampleZipWithTwoEntries());
}
- assertEquals(Arrays.asList("hello.txt", "hello2.txt"), mockFilter.calls);
+ assertThat(mockFilter.calls).containsExactly("hello.txt", "hello2.txt").inOrder();
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
assertEntry(zipInput, "hello.txt", "Hello World!\nHello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -392,10 +386,10 @@ public class ZipCombinerTest {
zipCombiner.addZip(sampleZipWithTwoUncompressedEntries());
zipCombiner.addZip(sampleZipWithTwoUncompressedEntries());
}
- assertEquals(Arrays.asList("hello.txt", "hello2.txt"), mockFilter.calls);
+ assertThat(mockFilter.calls).isEqualTo(Arrays.asList("hello.txt", "hello2.txt"));
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!\nHello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -407,11 +401,11 @@ public class ZipCombinerTest {
zipCombiner.addZip(sampleZip());
zipCombiner.addZip(sampleZipWithTwoEntries());
}
- assertEquals(Arrays.asList("hello.txt", "hello2.txt"), mockFilter.calls);
+ assertThat(mockFilter.calls).isEqualTo(Arrays.asList("hello.txt", "hello2.txt"));
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
assertEntry(zipInput, "hello.txt", "Hello World!Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -424,10 +418,10 @@ public class ZipCombinerTest {
zipCombiner.addZip(sampleZipWithTwoUncompressedEntries());
zipCombiner.addZip(sampleZipWithTwoUncompressedEntries());
}
- assertEquals(Arrays.asList("hello.txt", "hello2.txt"), mockFilter.calls);
+ assertThat(mockFilter.calls).containsExactly("hello.txt", "hello2.txt").inOrder();
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
private File specialZipWithMinusOne() throws IOException {
@@ -444,29 +438,30 @@ public class ZipCombinerTest {
try (ZipCombiner zipCombiner = new ZipCombiner(mockFilter, out)) {
zipCombiner.addZip(specialZipWithMinusOne());
}
- assertEquals(Arrays.asList("hello.txt"), mockFilter.calls);
+ assertThat(mockFilter.calls).containsExactly("hello.txt");
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", new byte[] { -1 });
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
public void testCopyDateHandling() throws IOException {
final Date date = new GregorianCalendar(2009, 8, 2, 0, 0, 0).getTime();
- ZipEntryFilter mockFilter = new ZipEntryFilter() {
- @Override
- public void accept(String filename, StrategyCallback callback) throws IOException {
- assertEquals("hello.txt", filename);
- callback.copy(date);
- }
- };
+ ZipEntryFilter mockFilter =
+ new ZipEntryFilter() {
+ @Override
+ public void accept(String filename, StrategyCallback callback) throws IOException {
+ assertThat(filename).isEqualTo("hello.txt");
+ callback.copy(date);
+ }
+ };
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipCombiner zipCombiner = new ZipCombiner(mockFilter, out)) {
zipCombiner.addZip(sampleZip());
}
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", date, "Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -479,11 +474,11 @@ public class ZipCombinerTest {
zipCombiner.addZip(sampleZip());
zipCombiner.addZip(sampleZipWithTwoEntries());
}
- assertEquals(Arrays.asList("hello.txt", "hello2.txt"), mockFilter.calls);
+ assertThat(mockFilter.calls).containsExactly("hello.txt", "hello2.txt").inOrder();
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello2.txt", ZipCombiner.DOS_EPOCH, "Hello World 2!");
assertEntry(zipInput, "hello.txt", mockFilter.date, "Hello World!\nHello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
@Test
@@ -543,7 +538,7 @@ public class ZipCombinerTest {
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello.txt", "Hello World!");
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
// This test verifies that multiple entries with the same name can be
@@ -568,7 +563,7 @@ public class ZipCombinerTest {
assertEntry(zipInput, "world1.txt", "Hello World 2!");
assertEntry(zipInput, "hello2.txt", "Hello World!");
assertEntry(zipInput, "world2.txt", "Hello World 2!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
// This tests verifies that an attempt to rename an entry to a
@@ -596,7 +591,7 @@ public class ZipCombinerTest {
assertEntry(zipInput, "hello1.txt", "Hello World!");
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
assertEntry(zipInput, "hello3.txt", "Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
// This tests verifies that if an entry has been copied, then
@@ -622,7 +617,7 @@ public class ZipCombinerTest {
assertEntry(zipInput, "hello1.txt", "Hello World!");
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
assertEntry(zipInput, "hello3.txt", "Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
// This tests verifies that if an entry has been skipped, then
@@ -647,7 +642,7 @@ public class ZipCombinerTest {
ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(out.toByteArray()));
assertEntry(zipInput, "hello1.txt", "Hello World!");
assertEntry(zipInput, "hello3.txt", "Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
// This test verifies that renaming works when input and output
@@ -675,7 +670,7 @@ public class ZipCombinerTest {
assertEntry(zipInput, "hello1.txt", "Hello World!");
assertEntry(zipInput, "hello2.txt", "Hello World 2!");
assertEntry(zipInput, "hello3.txt", "Hello World!");
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
}
// The next two tests check that ZipCombiner can handle a ZIP with an data
@@ -802,7 +797,7 @@ public class ZipCombinerTest {
for (int i = 0; i < fileCount; i++) {
assertEntry(zipInput, "hello" + i, "Hello " + i + "!");
}
- assertNull(zipInput.getNextEntry());
+ assertThat(zipInput.getNextEntry()).isNull();
new ZipTester(out.toByteArray()).validate();
}
}
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipReaderTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipReaderTest.java
index 0830b56acb..80f0dc694b 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipReaderTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipReaderTest.java
@@ -21,15 +21,6 @@ import static org.junit.Assert.fail;
import com.google.common.io.ByteStreams;
import com.google.devtools.build.zip.ZipFileEntry.Compression;
import com.google.devtools.build.zip.ZipFileEntry.Feature;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -45,6 +36,13 @@ import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ZipReaderTest {
@@ -467,7 +465,7 @@ public class ZipReaderTest {
fooIn.read(fooData);
assertThat(fooData).isEqualTo(expectedFooData);
assertThat(fooEntry.getName()).isEqualTo("entry");
- assertThat(fooEntry.getComment()).isEqualTo("");
+ assertThat(fooEntry.getComment()).isEmpty();
assertThat(fooEntry.getMethod()).isEqualTo(Compression.STORED);
assertThat(fooEntry.getVersionNeeded()).isEqualTo(Feature.ZIP64_SIZE.getMinVersion());
assertThat(fooEntry.getSize()).isEqualTo(expectedFooData.length);
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java
index 681d3cec94..05f4797eaf 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java
@@ -20,15 +20,6 @@ import static org.junit.Assert.fail;
import com.google.common.primitives.Bytes;
import com.google.devtools.build.zip.ZipFileEntry.Compression;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -39,6 +30,13 @@ import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ZipWriterTest {
@@ -92,8 +90,11 @@ public class ZipWriterTest {
writer.write(new byte[] { 0xf, 0xa, 0xb });
fail("Expected ZipException");
} catch (ZipException e) {
- assertThat(e.getMessage()).contains("Cannot write zip contents without first setting a"
- + " ZipEntry or starting a prefix file.");
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "Cannot write zip contents without first setting a"
+ + " ZipEntry or starting a prefix file.");
}
try (ZipFile zipFile = new ZipFile(test)) {
diff --git a/src/test/java/com/google/devtools/build/docgen/DocCheckerUtilsTest.java b/src/test/java/com/google/devtools/build/docgen/DocCheckerUtilsTest.java
index 6e40baceed..c67f71f890 100644
--- a/src/test/java/com/google/devtools/build/docgen/DocCheckerUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/docgen/DocCheckerUtilsTest.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.docgen;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -28,17 +27,19 @@ public class DocCheckerUtilsTest {
@Test
public void testUnclosedTags() {
- assertNull(DocCheckerUtils.getFirstUnclosedTag("<html></html>"));
- assertEquals("ol", DocCheckerUtils.getFirstUnclosedTag("<html><ol></html>"));
- assertEquals("ol", DocCheckerUtils.getFirstUnclosedTag("<html><ol><li>foo</li></html>"));
- assertEquals("ol", DocCheckerUtils.getFirstUnclosedTag("<html><ol><li/>foo<li/>bar</html>"));
+ assertThat(DocCheckerUtils.getFirstUnclosedTag("<html></html>")).isNull();
+ assertThat(DocCheckerUtils.getFirstUnclosedTag("<html><ol></html>")).isEqualTo("ol");
+ assertThat(DocCheckerUtils.getFirstUnclosedTag("<html><ol><li>foo</li></html>"))
+ .isEqualTo("ol");
+ assertThat(DocCheckerUtils.getFirstUnclosedTag("<html><ol><li/>foo<li/>bar</html>"))
+ .isEqualTo("ol");
}
@Test
public void testUncheckedTagsDontFire() {
- assertNull(DocCheckerUtils.getFirstUnclosedTag("<html><br></html>"));
- assertNull(DocCheckerUtils.getFirstUnclosedTag("<html><li></html>"));
- assertNull(DocCheckerUtils.getFirstUnclosedTag("<html><ul></html>"));
- assertNull(DocCheckerUtils.getFirstUnclosedTag("<html><p></html>"));
+ assertThat(DocCheckerUtils.getFirstUnclosedTag("<html><br></html>")).isNull();
+ assertThat(DocCheckerUtils.getFirstUnclosedTag("<html><li></html>")).isNull();
+ assertThat(DocCheckerUtils.getFirstUnclosedTag("<html><ul></html>")).isNull();
+ assertThat(DocCheckerUtils.getFirstUnclosedTag("<html><p></html>")).isNull();
}
}
diff --git a/src/test/java/com/google/devtools/build/docgen/RuleDocumentationAttributeTest.java b/src/test/java/com/google/devtools/build/docgen/RuleDocumentationAttributeTest.java
index 953f1e8886..403f5183ac 100644
--- a/src/test/java/com/google/devtools/build/docgen/RuleDocumentationAttributeTest.java
+++ b/src/test/java/com/google/devtools/build/docgen/RuleDocumentationAttributeTest.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.docgen;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.docgen.testutil.TestData.BaseRule;
@@ -39,67 +38,68 @@ public class RuleDocumentationAttributeTest {
public void testDirectChild() {
RuleDocumentationAttribute attr1 = RuleDocumentationAttribute.create(
IntermediateRule.class, "", "", 0, "", NO_FLAGS);
- assertEquals(1, attr1.getDefinitionClassAncestryLevel(TestRule.class, null));
+ assertThat(attr1.getDefinitionClassAncestryLevel(TestRule.class, null)).isEqualTo(1);
}
@Test
public void testTransitiveChild() {
RuleDocumentationAttribute attr2 = RuleDocumentationAttribute.create(
BaseRule.class, "", "", 0, "", NO_FLAGS);
- assertEquals(2, attr2.getDefinitionClassAncestryLevel(TestRule.class, null));
+ assertThat(attr2.getDefinitionClassAncestryLevel(TestRule.class, null)).isEqualTo(2);
}
@Test
public void testClassIsNotChild() {
RuleDocumentationAttribute attr2 = RuleDocumentationAttribute.create(
IntermediateRule.class, "", "", 0, "", NO_FLAGS);
- assertEquals(-1, attr2.getDefinitionClassAncestryLevel(BaseRule.class, null));
+ assertThat(attr2.getDefinitionClassAncestryLevel(BaseRule.class, null)).isEqualTo(-1);
}
@Test
public void testClassIsSame() {
RuleDocumentationAttribute attr3 = RuleDocumentationAttribute.create(
TestRule.class, "", "", 0, "", NO_FLAGS);
- assertEquals(0, attr3.getDefinitionClassAncestryLevel(TestRule.class, null));
+ assertThat(attr3.getDefinitionClassAncestryLevel(TestRule.class, null)).isEqualTo(0);
}
@Test
public void testHasFlags() {
RuleDocumentationAttribute attr = RuleDocumentationAttribute.create(
TestRule.class, "", "", 0, "", ImmutableSet.<String>of("SOME_FLAG"));
- assertTrue(attr.hasFlag("SOME_FLAG"));
+ assertThat(attr.hasFlag("SOME_FLAG")).isTrue();
}
@Test
public void testCompareTo() {
- assertEquals(
- -1,
- RuleDocumentationAttribute.create(TestRule.class, "a", "", 0, "", NO_FLAGS).compareTo(
- RuleDocumentationAttribute.create(TestRule.class, "b", "", 0, "", NO_FLAGS)));
+ assertThat(
+ RuleDocumentationAttribute.create(TestRule.class, "a", "", 0, "", NO_FLAGS)
+ .compareTo(
+ RuleDocumentationAttribute.create(TestRule.class, "b", "", 0, "", NO_FLAGS)))
+ .isEqualTo(-1);
}
@Test
public void testCompareToWithPriorityAttributeName() {
- assertEquals(
- 1,
- RuleDocumentationAttribute.create(TestRule.class, "a", "", 0, "", NO_FLAGS).compareTo(
- RuleDocumentationAttribute.create(TestRule.class, "name", "", 0, "", NO_FLAGS)));
+ assertThat(
+ RuleDocumentationAttribute.create(TestRule.class, "a", "", 0, "", NO_FLAGS)
+ .compareTo(
+ RuleDocumentationAttribute.create(TestRule.class, "name", "", 0, "", NO_FLAGS)))
+ .isEqualTo(1);
}
@Test
public void testEquals() {
- assertEquals(
- RuleDocumentationAttribute.create(TestRule.class, "a", "", 0, "", NO_FLAGS),
- RuleDocumentationAttribute.create(IntermediateRule.class, "a", "", 0, "", NO_FLAGS));
+ assertThat(RuleDocumentationAttribute.create(IntermediateRule.class, "a", "", 0, "", NO_FLAGS))
+ .isEqualTo(RuleDocumentationAttribute.create(TestRule.class, "a", "", 0, "", NO_FLAGS));
}
@Test
public void testHashCode() {
- assertEquals(
- RuleDocumentationAttribute.create(TestRule.class, "a", "", 0, "", NO_FLAGS)
- .hashCode(),
- RuleDocumentationAttribute.create(IntermediateRule.class, "a", "", 0, "", NO_FLAGS)
- .hashCode());
+ assertThat(
+ RuleDocumentationAttribute.create(IntermediateRule.class, "a", "", 0, "", NO_FLAGS)
+ .hashCode())
+ .isEqualTo(
+ RuleDocumentationAttribute.create(TestRule.class, "a", "", 0, "", NO_FLAGS).hashCode());
}
@Test
@@ -111,7 +111,7 @@ public class RuleDocumentationAttributeTest {
TestRule.class, "testrule", "", 0, "", NO_FLAGS);
attributeDoc.setAttribute(attribute);
String doc = attributeDoc.getSynopsis();
- assertEquals("String; optional; default is \"" + defaultValue + "\"", doc);
+ assertThat(doc).isEqualTo("String; optional; default is \"" + defaultValue + "\"");
}
@Test
@@ -123,7 +123,7 @@ public class RuleDocumentationAttributeTest {
TestRule.class, "testrule", "", 0, "", NO_FLAGS);
attributeDoc.setAttribute(attribute);
String doc = attributeDoc.getSynopsis();
- assertEquals("Integer; optional; default is " + defaultValue, doc);
+ assertThat(doc).isEqualTo("Integer; optional; default is " + defaultValue);
}
@Test
@@ -136,7 +136,7 @@ public class RuleDocumentationAttributeTest {
TestRule.class, "testrule", "", 0, "", NO_FLAGS);
attributeDoc.setAttribute(attribute);
String doc = attributeDoc.getSynopsis();
- assertEquals("List of <a href=\"../build-ref.html#labels\">labels</a>; optional", doc);
+ assertThat(doc).isEqualTo("List of <a href=\"../build-ref.html#labels\">labels</a>; optional");
}
@Test
@@ -149,6 +149,6 @@ public class RuleDocumentationAttributeTest {
TestRule.class, "testrule", "", 0, "", NO_FLAGS);
attributeDoc.setAttribute(attribute);
String doc = attributeDoc.getSynopsis();
- assertEquals("<a href=\"../build-ref.html#labels\">Label</a>; required", doc);
+ assertThat(doc).isEqualTo("<a href=\"../build-ref.html#labels\">Label</a>; required");
}
}
diff --git a/src/test/java/com/google/devtools/build/docgen/RuleDocumentationTest.java b/src/test/java/com/google/devtools/build/docgen/RuleDocumentationTest.java
index d7c6f6c4bc..54d1c2b3c6 100644
--- a/src/test/java/com/google/devtools/build/docgen/RuleDocumentationTest.java
+++ b/src/test/java/com/google/devtools/build/docgen/RuleDocumentationTest.java
@@ -13,16 +13,14 @@
// limitations under the License.
package com.google.devtools.build.docgen;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.docgen.testutil.TestData.TestRule;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -38,7 +36,9 @@ public class RuleDocumentationTest {
TestRuleClassProvider.getRuleClassProvider();
private static void assertContains(String base, String value) {
- assertTrue(base + " is expected to contain " + value, base.contains(value));
+ assertWithMessage(base + " is expected to contain " + value)
+ .that(base.contains(value))
+ .isTrue();
}
private void checkAttributeForRule(RuleDocumentation rule, RuleDocumentationAttribute attr,
@@ -65,7 +65,7 @@ public class RuleDocumentationTest {
"z"}),
0, "", ImmutableSet.<String>of(), provider);
ruleDoc.addDocVariable("VAR", "y");
- assertEquals("x\ny\nz", ruleDoc.getHtmlDocumentation());
+ assertThat(ruleDoc.getHtmlDocumentation()).isEqualTo("x\ny\nz");
}
@Test
@@ -97,7 +97,7 @@ public class RuleDocumentationTest {
RuleDocumentation ruleDoc = new RuleDocumentation(
"rule", "OTHER", "FOO", "x", 0, "", ImmutableSet.<String>of("DEPRECATED"), provider);
ruleDoc.addDocVariable("VAR", "y");
- assertEquals("x", ruleDoc.getHtmlDocumentation());
+ assertThat(ruleDoc.getHtmlDocumentation()).isEqualTo("x");
}
@Test
@@ -113,7 +113,7 @@ public class RuleDocumentationTest {
RuleDocumentationAttribute attributeDoc = RuleDocumentationAttribute.create(TestRule.class,
"srcs", "attribute doc", 0, "", NO_FLAGS);
ruleDoc.addAttribute(attributeDoc);
- assertEquals("\nx\ny\nz\n\n", ruleDoc.getCommandLineDocumentation());
+ assertThat(ruleDoc.getCommandLineDocumentation()).isEqualTo("\nx\ny\nz\n\n");
}
@Test
@@ -130,7 +130,7 @@ public class RuleDocumentationTest {
"<!-- #BLAZE_RULE.END_EXAMPLE -->",
"z"}),
0, "", ImmutableSet.<String>of(), provider);
- assertEquals(ImmutableSet.<String>of("a\n", "b\n"), ruleDoc.extractExamples());
+ assertThat(ruleDoc.extractExamples()).isEqualTo(ImmutableSet.<String>of("a\n", "b\n"));
}
@Test
@@ -138,34 +138,40 @@ public class RuleDocumentationTest {
RuleDocumentation ruleDoc = new RuleDocumentation(
"foo_binary", "OTHER", "FOO", "", 10, "foo.txt", NO_FLAGS, provider);
BuildEncyclopediaDocException e = ruleDoc.createException("msg");
- assertEquals("Error in foo.txt:10: msg", e.getMessage());
+ assertThat(e).hasMessageThat().isEqualTo("Error in foo.txt:10: msg");
}
@Test
public void testEquals() throws BuildEncyclopediaDocException {
- assertEquals(
- new RuleDocumentation("rule", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider),
- new RuleDocumentation("rule", "OTHER", "FOO", "y", 0, "", NO_FLAGS, provider));
+ assertThat(new RuleDocumentation("rule", "OTHER", "FOO", "y", 0, "", NO_FLAGS, provider))
+ .isEqualTo(new RuleDocumentation("rule", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider));
}
@Test
public void testNotEquals() throws BuildEncyclopediaDocException {
- assertFalse(
- new RuleDocumentation("rule1", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider).equals(
- new RuleDocumentation("rule2", "OTHER", "FOO", "y", 0, "", NO_FLAGS, provider)));
+ assertThat(
+ new RuleDocumentation("rule1", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider)
+ .equals(
+ new RuleDocumentation("rule2", "OTHER", "FOO", "y", 0, "", NO_FLAGS, provider)))
+ .isFalse();
}
@Test
public void testCompareTo() throws BuildEncyclopediaDocException {
- assertEquals(-1,
- new RuleDocumentation("rule1", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider).compareTo(
- new RuleDocumentation("rule2", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider)));
+ assertThat(
+ new RuleDocumentation("rule1", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider)
+ .compareTo(
+ new RuleDocumentation("rule2", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider)))
+ .isEqualTo(-1);
}
@Test
public void testHashCode() throws BuildEncyclopediaDocException {
- assertEquals(
- new RuleDocumentation("rule", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider).hashCode(),
- new RuleDocumentation("rule", "OTHER", "FOO", "y", 0, "", NO_FLAGS, provider).hashCode());
+ assertThat(
+ new RuleDocumentation("rule", "OTHER", "FOO", "y", 0, "", NO_FLAGS, provider)
+ .hashCode())
+ .isEqualTo(
+ new RuleDocumentation("rule", "OTHER", "FOO", "x", 0, "", NO_FLAGS, provider)
+ .hashCode());
}
}
diff --git a/src/test/java/com/google/devtools/build/docgen/RuleLinkExpanderTest.java b/src/test/java/com/google/devtools/build/docgen/RuleLinkExpanderTest.java
index cea22dace2..bc16b1d2f1 100644
--- a/src/test/java/com/google/devtools/build/docgen/RuleLinkExpanderTest.java
+++ b/src/test/java/com/google/devtools/build/docgen/RuleLinkExpanderTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.docgen;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
@@ -41,11 +41,11 @@ public class RuleLinkExpanderTest {
}
private void checkExpandSingle(String docs, String expected) {
- assertEquals(expected, singlePageExpander.expand(docs));
+ assertThat(singlePageExpander.expand(docs)).isEqualTo(expected);
}
private void checkExpandMulti(String docs, String expected) {
- assertEquals(expected, multiPageExpander.expand(docs));
+ assertThat(multiPageExpander.expand(docs)).isEqualTo(expected);
}
@Test public void testRule() {
@@ -151,11 +151,9 @@ public class RuleLinkExpanderTest {
}
@Test public void testExpandRef() {
- assertEquals(
- "java.html#java_binary.runtime_deps",
- multiPageExpander.expandRef("java_binary.runtime_deps"));
- assertEquals(
- "#java_binary.runtime_deps",
- singlePageExpander.expandRef("java_binary.runtime_deps"));
+ assertThat(multiPageExpander.expandRef("java_binary.runtime_deps"))
+ .isEqualTo("java.html#java_binary.runtime_deps");
+ assertThat(singlePageExpander.expandRef("java_binary.runtime_deps"))
+ .isEqualTo("#java_binary.runtime_deps");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporterTest.java b/src/test/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporterTest.java
index 6a67892f88..ccfdaf9c94 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporterTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/ActionExecutionStatusReporterTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.actions;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import com.google.common.base.Splitter;
@@ -26,20 +25,16 @@ import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.events.util.EventCollectionApparatus;
import com.google.devtools.build.lib.util.Clock;
import com.google.devtools.build.lib.util.Preconditions;
-
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Test for the {@link ActionExecutionStatusReporter} class.
- */
+/** Test for the {@link ActionExecutionStatusReporter} class. */
@RunWith(JUnit4.class)
public class ActionExecutionStatusReporterTest {
private static final class MockClock implements Clock {
@@ -98,18 +93,32 @@ public class ActionExecutionStatusReporterTest {
private void verifyOutput(String... lines) throws Exception {
events.clear();
statusReporter.showCurrentlyExecutingActions("");
- assertThat(Splitter.on('\n').omitEmptyStrings().trimResults().split(
- Iterables.getOnlyElement(events.collector()).getMessage().replaceAll(" +", " ")))
- .containsExactlyElementsIn(Arrays.asList(lines)).inOrder();
+ assertThat(
+ Splitter.on('\n')
+ .omitEmptyStrings()
+ .trimResults()
+ .split(
+ Iterables.getOnlyElement(events.collector())
+ .getMessage()
+ .replaceAll(" +", " ")))
+ .containsExactlyElementsIn(Arrays.asList(lines))
+ .inOrder();
}
private void verifyWarningOutput(String... lines) throws Exception {
events.setFailFast(false);
events.clear();
statusReporter.warnAboutCurrentlyExecutingActions();
- assertThat(Splitter.on('\n').omitEmptyStrings().trimResults().split(
- Iterables.getOnlyElement(events.collector()).getMessage().replaceAll(" +", " ")))
- .containsExactlyElementsIn(Arrays.asList(lines)).inOrder();
+ assertThat(
+ Splitter.on('\n')
+ .omitEmptyStrings()
+ .trimResults()
+ .split(
+ Iterables.getOnlyElement(events.collector())
+ .getMessage()
+ .replaceAll(" +", " ")))
+ .containsExactlyElementsIn(Arrays.asList(lines))
+ .inOrder();
}
@Test
@@ -262,18 +271,18 @@ public class ActionExecutionStatusReporterTest {
@Test
public void testWaitTimeCalculation() throws Exception {
// --progress_report_interval=0
- assertEquals(10, ActionExecutionStatusReporter.getWaitTime(0, 0));
- assertEquals(30, ActionExecutionStatusReporter.getWaitTime(0, 10));
- assertEquals(60, ActionExecutionStatusReporter.getWaitTime(0, 30));
- assertEquals(60, ActionExecutionStatusReporter.getWaitTime(0, 60));
+ assertThat(ActionExecutionStatusReporter.getWaitTime(0, 0)).isEqualTo(10);
+ assertThat(ActionExecutionStatusReporter.getWaitTime(0, 10)).isEqualTo(30);
+ assertThat(ActionExecutionStatusReporter.getWaitTime(0, 30)).isEqualTo(60);
+ assertThat(ActionExecutionStatusReporter.getWaitTime(0, 60)).isEqualTo(60);
// --progress_report_interval=42
- assertEquals(42, ActionExecutionStatusReporter.getWaitTime(42, 0));
- assertEquals(42, ActionExecutionStatusReporter.getWaitTime(42, 42));
+ assertThat(ActionExecutionStatusReporter.getWaitTime(42, 0)).isEqualTo(42);
+ assertThat(ActionExecutionStatusReporter.getWaitTime(42, 42)).isEqualTo(42);
// --progress_report_interval=30 (looks like one of the default timeout stages)
- assertEquals(30, ActionExecutionStatusReporter.getWaitTime(30, 0));
- assertEquals(30, ActionExecutionStatusReporter.getWaitTime(30, 30));
+ assertThat(ActionExecutionStatusReporter.getWaitTime(30, 0)).isEqualTo(30);
+ assertThat(ActionExecutionStatusReporter.getWaitTime(30, 30)).isEqualTo(30);
}
private void setScheduling(ActionExecutionMetadata action) {
diff --git a/src/test/java/com/google/devtools/build/lib/actions/ArtifactFactoryTest.java b/src/test/java/com/google/devtools/build/lib/actions/ArtifactFactoryTest.java
index e9bb9b335f..f70bb59416 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/ArtifactFactoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/ArtifactFactoryTest.java
@@ -14,12 +14,9 @@
package com.google.devtools.build.lib.actions;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ARTIFACT_OWNER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -106,46 +103,51 @@ public class ArtifactFactoryTest {
@Test
public void testGetSourceArtifactYieldsSameArtifact() throws Exception {
- assertSame(artifactFactory.getSourceArtifact(fooRelative, clientRoot),
- artifactFactory.getSourceArtifact(fooRelative, clientRoot));
+ assertThat(artifactFactory.getSourceArtifact(fooRelative, clientRoot))
+ .isSameAs(artifactFactory.getSourceArtifact(fooRelative, clientRoot));
}
@Test
public void testGetSourceArtifactUnnormalized() throws Exception {
- assertSame(artifactFactory.getSourceArtifact(fooRelative, clientRoot),
- artifactFactory.getSourceArtifact(PathFragment.create("foo/./foosource.txt"),
- clientRoot));
+ assertThat(
+ artifactFactory.getSourceArtifact(
+ PathFragment.create("foo/./foosource.txt"), clientRoot))
+ .isSameAs(artifactFactory.getSourceArtifact(fooRelative, clientRoot));
}
@Test
public void testResolveArtifact_noDerived_simpleSource() throws Exception {
- assertSame(artifactFactory.getSourceArtifact(fooRelative, clientRoot),
- artifactFactory.resolveSourceArtifact(fooRelative, MAIN));
- assertSame(artifactFactory.getSourceArtifact(barRelative, clientRoRoot),
- artifactFactory.resolveSourceArtifact(barRelative, MAIN));
+ assertThat(artifactFactory.resolveSourceArtifact(fooRelative, MAIN))
+ .isSameAs(artifactFactory.getSourceArtifact(fooRelative, clientRoot));
+ assertThat(artifactFactory.resolveSourceArtifact(barRelative, MAIN))
+ .isSameAs(artifactFactory.getSourceArtifact(barRelative, clientRoRoot));
}
@Test
public void testResolveArtifact_inExternalRepo() throws Exception {
- assertSame(
- artifactFactory.getSourceArtifact(alienRelative, alienRoot),
- artifactFactory.resolveSourceArtifact(alienRelative, MAIN));
+ Artifact a1 = artifactFactory.getSourceArtifact(alienRelative, alienRoot);
+ Artifact a2 = artifactFactory.resolveSourceArtifact(alienRelative, MAIN);
+ assertThat(a1).isSameAs(a2);
}
@Test
public void testResolveArtifact_noDerived_derivedRoot() throws Exception {
- assertNull(artifactFactory.resolveSourceArtifact(
- outRoot.getPath().getRelative(fooRelative).relativeTo(execRoot), MAIN));
- assertNull(artifactFactory.resolveSourceArtifact(
- outRoot.getPath().getRelative(barRelative).relativeTo(execRoot), MAIN));
+ assertThat(
+ artifactFactory.resolveSourceArtifact(
+ outRoot.getPath().getRelative(fooRelative).relativeTo(execRoot), MAIN))
+ .isNull();
+ assertThat(
+ artifactFactory.resolveSourceArtifact(
+ outRoot.getPath().getRelative(barRelative).relativeTo(execRoot), MAIN))
+ .isNull();
}
@Test
public void testResolveArtifact_noDerived_simpleSource_other() throws Exception {
Artifact actual = artifactFactory.resolveSourceArtifact(fooRelative, MAIN);
- assertSame(artifactFactory.getSourceArtifact(fooRelative, clientRoot), actual);
+ assertThat(actual).isSameAs(artifactFactory.getSourceArtifact(fooRelative, clientRoot));
actual = artifactFactory.resolveSourceArtifact(barRelative, MAIN);
- assertSame(artifactFactory.getSourceArtifact(barRelative, clientRoRoot), actual);
+ assertThat(actual).isSameAs(artifactFactory.getSourceArtifact(barRelative, clientRoRoot));
}
@Test
@@ -158,9 +160,11 @@ public class ArtifactFactoryTest {
PathFragment outsideWorkspace = PathFragment.create("../foo");
PathFragment insideWorkspace =
PathFragment.create("../" + clientRoot.getPath().getBaseName() + "/foo");
- assertNull(artifactFactory.resolveSourceArtifact(outsideWorkspace, MAIN));
- assertNull("Up-level-containing paths that descend into the right workspace aren't allowed",
- artifactFactory.resolveSourceArtifact(insideWorkspace, MAIN));
+ assertThat(artifactFactory.resolveSourceArtifact(outsideWorkspace, MAIN)).isNull();
+ assertWithMessage(
+ "Up-level-containing paths that descend into the right workspace aren't allowed")
+ .that(artifactFactory.resolveSourceArtifact(insideWorkspace, MAIN))
+ .isNull();
MockPackageRootResolver packageRootResolver = new MockPackageRootResolver();
packageRootResolver.setPackageRoots(packageRoots);
Map<PathFragment, Artifact> result = new HashMap<>();
@@ -176,7 +180,7 @@ public class ArtifactFactoryTest {
Artifact fooArtifact = artifactFactory.getSourceArtifact(fooRelative, clientRoot);
artifactFactory.clear();
setupRoots();
- assertNotSame(fooArtifact, artifactFactory.getSourceArtifact(fooRelative, clientRoot));
+ assertThat(artifactFactory.getSourceArtifact(fooRelative, clientRoot)).isNotSameAs(fooArtifact);
}
@Test
@@ -200,8 +204,8 @@ public class ArtifactFactoryTest {
actionGraph.registerAction(action);
fail();
} catch (ActionConflictException e) {
- assertSame(a, e.getArtifact());
- assertSame(originalAction, actionGraph.getGeneratingAction(a));
+ assertThat(e.getArtifact()).isSameAs(a);
+ assertThat(actionGraph.getGeneratingAction(a)).isSameAs(originalAction);
}
}
@@ -209,10 +213,10 @@ public class ArtifactFactoryTest {
public void testGetDerivedArtifact() throws Exception {
PathFragment toolPath = PathFragment.create("_bin/tool");
Artifact artifact = artifactFactory.getDerivedArtifact(toolPath, execRoot);
- assertEquals(toolPath, artifact.getExecPath());
- assertEquals(Root.asDerivedRoot(execRoot), artifact.getRoot());
- assertEquals(execRoot.getRelative(toolPath), artifact.getPath());
- assertNull(artifact.getOwner());
+ assertThat(artifact.getExecPath()).isEqualTo(toolPath);
+ assertThat(artifact.getRoot()).isEqualTo(Root.asDerivedRoot(execRoot));
+ assertThat(artifact.getPath()).isEqualTo(execRoot.getRelative(toolPath));
+ assertThat(artifact.getOwner()).isNull();
}
@Test
@@ -250,7 +254,7 @@ public class ArtifactFactoryTest {
}
return result;
}
-
+
@Override
@Nullable
public Map<PathFragment, Root> findPackageRoots(Iterable<PathFragment> execPaths) {
diff --git a/src/test/java/com/google/devtools/build/lib/actions/ArtifactTest.java b/src/test/java/com/google/devtools/build/lib/actions/ArtifactTest.java
index b7bb9d1ae8..296703eef6 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/ArtifactTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/ArtifactTest.java
@@ -13,12 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -68,12 +63,9 @@ public class ArtifactTest {
public void testEquivalenceRelation() throws Exception {
PathFragment aPath = PathFragment.create("src/a");
PathFragment bPath = PathFragment.create("src/b");
- assertEquals(new Artifact(aPath, rootDir),
- new Artifact(aPath, rootDir));
- assertEquals(new Artifact(bPath, rootDir),
- new Artifact(bPath, rootDir));
- assertFalse(new Artifact(aPath, rootDir).equals(
- new Artifact(bPath, rootDir)));
+ assertThat(new Artifact(aPath, rootDir)).isEqualTo(new Artifact(aPath, rootDir));
+ assertThat(new Artifact(bPath, rootDir)).isEqualTo(new Artifact(bPath, rootDir));
+ assertThat(new Artifact(aPath, rootDir).equals(new Artifact(bPath, rootDir))).isFalse();
}
@Test
@@ -88,24 +80,24 @@ public class ArtifactTest {
PathFragment bPath = PathFragment.create("src/b");
Artifact aArtifact = new Artifact(aPath, rootDir);
Artifact bArtifact = new Artifact(bPath, rootDir);
- assertEquals(-1, Artifact.EXEC_PATH_COMPARATOR.compare(aArtifact, bArtifact));
- assertEquals(0, Artifact.EXEC_PATH_COMPARATOR.compare(aArtifact, aArtifact));
- assertEquals(0, Artifact.EXEC_PATH_COMPARATOR.compare(bArtifact, bArtifact));
- assertEquals(1, Artifact.EXEC_PATH_COMPARATOR.compare(bArtifact, aArtifact));
+ assertThat(Artifact.EXEC_PATH_COMPARATOR.compare(aArtifact, bArtifact)).isEqualTo(-1);
+ assertThat(Artifact.EXEC_PATH_COMPARATOR.compare(aArtifact, aArtifact)).isEqualTo(0);
+ assertThat(Artifact.EXEC_PATH_COMPARATOR.compare(bArtifact, bArtifact)).isEqualTo(0);
+ assertThat(Artifact.EXEC_PATH_COMPARATOR.compare(bArtifact, aArtifact)).isEqualTo(1);
}
@Test
public void testRootPrefixedExecPath_normal() throws IOException {
Path f1 = scratch.file("/exec/root/dir/file.ext");
Artifact a1 = new Artifact(f1, rootDir, f1.relativeTo(execDir));
- assertEquals("root:dir/file.ext", Artifact.asRootPrefixedExecPath(a1));
+ assertThat(Artifact.asRootPrefixedExecPath(a1)).isEqualTo("root:dir/file.ext");
}
@Test
public void testRootPrefixedExecPath_noRoot() throws IOException {
Path f1 = scratch.file("/exec/dir/file.ext");
Artifact a1 = new Artifact(f1.relativeTo(execDir), Root.asDerivedRoot(execDir));
- assertEquals(":dir/file.ext", Artifact.asRootPrefixedExecPath(a1));
+ assertThat(Artifact.asRootPrefixedExecPath(a1)).isEqualTo(":dir/file.ext");
}
@Test
@@ -140,10 +132,10 @@ public class ArtifactTest {
Artifact generatedHeader = new Artifact(scratch.file("/foo/bar.proto.h"), root);
Artifact generatedCc = new Artifact(scratch.file("/foo/bar.proto.cc"), root);
Artifact aCPlusPlusFile = new Artifact(scratch.file("/foo/bar.cc"), root);
- assertTrue(JavaSemantics.JAVA_SOURCE.matches(javaFile.getFilename()));
- assertTrue(CppFileTypes.CPP_HEADER.matches(generatedHeader.getFilename()));
- assertTrue(CppFileTypes.CPP_SOURCE.matches(generatedCc.getFilename()));
- assertTrue(CppFileTypes.CPP_SOURCE.matches(aCPlusPlusFile.getFilename()));
+ assertThat(JavaSemantics.JAVA_SOURCE.matches(javaFile.getFilename())).isTrue();
+ assertThat(CppFileTypes.CPP_HEADER.matches(generatedHeader.getFilename())).isTrue();
+ assertThat(CppFileTypes.CPP_SOURCE.matches(generatedCc.getFilename())).isTrue();
+ assertThat(CppFileTypes.CPP_SOURCE.matches(aCPlusPlusFile.getFilename())).isTrue();
}
@Test
@@ -156,7 +148,7 @@ public class ArtifactTest {
@Test
public void testMangledPath() {
String path = "dir/sub_dir/name:end";
- assertEquals("dir_Ssub_Udir_Sname_Cend", Actions.escapedPath(path));
+ assertThat(Actions.escapedPath(path)).isEqualTo("dir_Ssub_Udir_Sname_Cend");
}
private List<Artifact> getFooBarArtifacts(MutableActionGraph actionGraph, boolean collapsedList)
@@ -179,7 +171,7 @@ public class ArtifactTest {
List<String> paths = new ArrayList<>();
MutableActionGraph actionGraph = new MapBasedActionGraph();
Artifact.addExecPaths(getFooBarArtifacts(actionGraph, false), paths);
- assertThat(paths).containsExactlyElementsIn(ImmutableList.of("bar1.h", "bar2.h"));
+ assertThat(paths).containsExactly("bar1.h", "bar2.h");
}
@Test
@@ -229,7 +221,7 @@ public class ArtifactTest {
List<String> paths = new ArrayList<>();
MutableActionGraph actionGraph = new MapBasedActionGraph();
Artifact.addExecPaths(getFooBarArtifacts(actionGraph, false), paths);
- assertThat(paths).containsExactlyElementsIn(ImmutableList.of("bar1.h", "bar2.h"));
+ assertThat(paths).containsExactly("bar1.h", "bar2.h");
}
@Test
@@ -279,14 +271,14 @@ public class ArtifactTest {
public void testRootRelativePathIsSameAsExecPath() throws Exception {
Root root = Root.asSourceRoot(scratch.dir("/foo"));
Artifact a = new Artifact(scratch.file("/foo/bar1.h"), root);
- assertSame(a.getExecPath(), a.getRootRelativePath());
+ assertThat(a.getRootRelativePath()).isSameAs(a.getExecPath());
}
@Test
public void testToDetailString() throws Exception {
Artifact a = new Artifact(scratch.file("/a/b/c"), Root.asDerivedRoot(scratch.dir("/a/b")),
PathFragment.create("b/c"));
- assertEquals("[[/a]b]c", a.toDetailString());
+ assertThat(a.toDetailString()).isEqualTo("[[/a]b]c");
}
@Test
@@ -303,9 +295,10 @@ public class ArtifactTest {
@Test
public void testSerializeToString() throws Exception {
- assertEquals("b/c /3",
- new Artifact(scratch.file("/a/b/c"),
- Root.asDerivedRoot(scratch.dir("/a"))).serializeToString());
+ assertThat(
+ new Artifact(scratch.file("/a/b/c"), Root.asDerivedRoot(scratch.dir("/a")))
+ .serializeToString())
+ .isEqualTo("b/c /3");
}
@Test
@@ -314,15 +307,19 @@ public class ArtifactTest {
Root root = Root.asDerivedRoot(scratch.dir("/aaa/bbb"));
PathFragment execPath = PathFragment.create("bbb/ccc");
- assertEquals("bbb/ccc /3", new Artifact(path, root, execPath).serializeToString());
+ assertThat(new Artifact(path, root, execPath).serializeToString()).isEqualTo("bbb/ccc /3");
}
@Test
public void testSerializeToStringWithOwner() throws Exception {
- assertEquals("b/c /3 //foo:bar",
- new Artifact(scratch.file("/aa/b/c"), Root.asDerivedRoot(scratch.dir("/aa")),
- PathFragment.create("b/c"),
- new LabelArtifactOwner(Label.parseAbsoluteUnchecked("//foo:bar"))).serializeToString());
+ assertThat(
+ new Artifact(
+ scratch.file("/aa/b/c"),
+ Root.asDerivedRoot(scratch.dir("/aa")),
+ PathFragment.create("b/c"),
+ new LabelArtifactOwner(Label.parseAbsoluteUnchecked("//foo:bar")))
+ .serializeToString())
+ .isEqualTo("b/c /3 //foo:bar");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/actions/CompositeRunfilesSupplierTest.java b/src/test/java/com/google/devtools/build/lib/actions/CompositeRunfilesSupplierTest.java
index 559deb12ef..4366b17833 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/CompositeRunfilesSupplierTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/CompositeRunfilesSupplierTest.java
@@ -69,8 +69,7 @@ public class CompositeRunfilesSupplierTest {
when(mockSecond.getRunfilesDirs()).thenReturn(ImmutableSet.of(second, shared));
CompositeRunfilesSupplier underTest = new CompositeRunfilesSupplier(mockFirst, mockSecond);
- assertThat(underTest.getRunfilesDirs()).containsExactlyElementsIn(
- ImmutableSet.of(first, second, shared));
+ assertThat(underTest.getRunfilesDirs()).containsExactly(first, second, shared);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/actions/ConcurrentMultimapWithHeadElementTest.java b/src/test/java/com/google/devtools/build/lib/actions/ConcurrentMultimapWithHeadElementTest.java
index 1ed396aae6..d48cc5d2ec 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/ConcurrentMultimapWithHeadElementTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/ConcurrentMultimapWithHeadElementTest.java
@@ -13,10 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.testing.GcFinalization;
import com.google.devtools.build.lib.concurrent.AbstractQueueVisitor;
@@ -40,54 +37,54 @@ public class ConcurrentMultimapWithHeadElementTest {
public void testSmoke() throws Exception {
ConcurrentMultimapWithHeadElement<String, String> multimap =
new ConcurrentMultimapWithHeadElement<>();
- assertEquals("val", multimap.putAndGet("key", "val"));
- assertEquals("val", multimap.get("key"));
- assertEquals("val", multimap.putAndGet("key", "val2"));
+ assertThat(multimap.putAndGet("key", "val")).isEqualTo("val");
+ assertThat(multimap.get("key")).isEqualTo("val");
+ assertThat(multimap.putAndGet("key", "val2")).isEqualTo("val");
multimap.remove("key", "val2");
- assertEquals("val", multimap.get("key"));
- assertEquals("val", multimap.putAndGet("key", "val2"));
+ assertThat(multimap.get("key")).isEqualTo("val");
+ assertThat(multimap.putAndGet("key", "val2")).isEqualTo("val");
multimap.remove("key", "val");
- assertEquals("val2", multimap.get("key"));
+ assertThat(multimap.get("key")).isEqualTo("val2");
}
@Test
public void testDuplicate() throws Exception {
ConcurrentMultimapWithHeadElement<String, String> multimap =
new ConcurrentMultimapWithHeadElement<>();
- assertEquals("val", multimap.putAndGet("key", "val"));
- assertEquals("val", multimap.get("key"));
- assertEquals("val", multimap.putAndGet("key", "val"));
+ assertThat(multimap.putAndGet("key", "val")).isEqualTo("val");
+ assertThat(multimap.get("key")).isEqualTo("val");
+ assertThat(multimap.putAndGet("key", "val")).isEqualTo("val");
multimap.remove("key", "val");
- assertNull(multimap.get("key"));
+ assertThat(multimap.get("key")).isNull();
}
@Test
public void testDuplicateWithEqualsObject() throws Exception {
ConcurrentMultimapWithHeadElement<String, String> multimap =
new ConcurrentMultimapWithHeadElement<>();
- assertEquals("val", multimap.putAndGet("key", "val"));
- assertEquals("val", multimap.get("key"));
- assertEquals("val", multimap.putAndGet("key", "val"));
+ assertThat(multimap.putAndGet("key", "val")).isEqualTo("val");
+ assertThat(multimap.get("key")).isEqualTo("val");
+ assertThat(multimap.putAndGet("key", "val")).isEqualTo("val");
multimap.remove("key", "val");
- assertNull(multimap.get("key"));
+ assertThat(multimap.get("key")).isNull();
}
@Test
public void testFailedRemoval() throws Exception {
ConcurrentMultimapWithHeadElement<String, String> multimap =
new ConcurrentMultimapWithHeadElement<>();
- assertEquals("val", multimap.putAndGet("key", "val"));
+ assertThat(multimap.putAndGet("key", "val")).isEqualTo("val");
multimap.remove("key", "val2");
- assertEquals("val", multimap.get("key"));
+ assertThat(multimap.get("key")).isEqualTo("val");
}
@Test
public void testNotEmpty() throws Exception {
ConcurrentMultimapWithHeadElement<String, String> multimap =
new ConcurrentMultimapWithHeadElement<>();
- assertEquals("val", multimap.putAndGet("key", "val"));
+ assertThat(multimap.putAndGet("key", "val")).isEqualTo("val");
multimap.remove("key", "val2");
- assertEquals("val", multimap.get("key"));
+ assertThat(multimap.get("key")).isEqualTo("val");
}
@Test
@@ -95,7 +92,7 @@ public class ConcurrentMultimapWithHeadElementTest {
String key = new String("key");
ConcurrentMultimapWithHeadElement<String, String> multimap =
new ConcurrentMultimapWithHeadElement<>();
- assertEquals("val", multimap.putAndGet(key, "val"));
+ assertThat(multimap.putAndGet(key, "val")).isEqualTo("val");
WeakReference<String> weakKey = new WeakReference<>(key);
multimap.remove(key, "val");
key = null;
@@ -109,7 +106,7 @@ public class ConcurrentMultimapWithHeadElementTest {
// Because we have two threads racing, run the test many times. Before fixed, there was a 90%
// chance of failure in 10,000 runs.
for (int i = 0; i < 10000; i++) {
- assertEquals("val", multimap.putAndGet("key", "val"));
+ assertThat(multimap.putAndGet("key", "val")).isEqualTo("val");
final CountDownLatch threadStart = new CountDownLatch(1);
TestThread testThread = new TestThread() {
@Override
@@ -119,9 +116,10 @@ public class ConcurrentMultimapWithHeadElementTest {
}
};
testThread.start();
- assertTrue(threadStart.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
- assertNotNull(multimap.putAndGet("key", "val2")); // Removal may not have happened yet.
- assertNotNull(multimap.get("key")); // If put failed, this will be null.
+ assertThat(threadStart.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue();
+ assertThat(multimap.putAndGet("key", "val2"))
+ .isNotNull(); // Removal may not have happened yet.
+ assertThat(multimap.get("key")).isNotNull(); // If put failed, this will be null.
testThread.joinAndAssertState(2000);
multimap.clear();
}
@@ -148,7 +146,7 @@ public class ConcurrentMultimapWithHeadElementTest {
new Runnable() {
@Override
public void run() {
- assertNotNull(multimap.putAndGet(key, add));
+ assertThat(multimap.putAndGet(key, add)).isNotNull();
multimap.remove(key, remove);
doRandom();
}
diff --git a/src/test/java/com/google/devtools/build/lib/actions/CustomCommandLineTest.java b/src/test/java/com/google/devtools/build/lib/actions/CustomCommandLineTest.java
index eff6c637c1..ea061beb2d 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/CustomCommandLineTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/CustomCommandLineTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.actions;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
@@ -61,27 +60,27 @@ public class CustomCommandLineTest {
@Test
public void testStringArgs() {
CustomCommandLine cl = CustomCommandLine.builder().add("--arg1").add("--arg2").build();
- assertEquals(ImmutableList.of("--arg1", "--arg2"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("--arg1", "--arg2"));
}
@Test
public void testLabelArgs() throws LabelSyntaxException {
CustomCommandLine cl = CustomCommandLine.builder().add(Label.parseAbsolute("//a:b")).build();
- assertEquals(ImmutableList.of("//a:b"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("//a:b"));
}
@Test
public void testStringsArgs() {
CustomCommandLine cl = CustomCommandLine.builder().add("--arg",
ImmutableList.of("a", "b")).build();
- assertEquals(ImmutableList.of("--arg", "a", "b"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("--arg", "a", "b"));
}
@Test
public void testArtifactJoinStringArgs() {
CustomCommandLine cl = CustomCommandLine.builder().addJoinStrings("--path", ":",
ImmutableList.of("foo", "bar")).build();
- assertEquals(ImmutableList.of("--path", "foo:bar"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("--path", "foo:bar"));
}
@Test
@@ -100,54 +99,55 @@ public class CustomCommandLineTest {
}
})
.build();
- assertEquals(ImmutableList.of("--path", "FOO:BAR:BAZ"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("--path", "FOO:BAR:BAZ"));
}
@Test
public void testArtifactExecPathArgs() {
CustomCommandLine cl = CustomCommandLine.builder().addExecPath("--path", artifact1).build();
- assertEquals(ImmutableList.of("--path", "dir/file1.txt"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("--path", "dir/file1.txt"));
}
@Test
public void testArtifactExecPathsArgs() {
CustomCommandLine cl = CustomCommandLine.builder().addExecPaths("--path",
ImmutableList.of(artifact1, artifact2)).build();
- assertEquals(ImmutableList.of("--path", "dir/file1.txt", "dir/file2.txt"), cl.arguments());
+ assertThat(cl.arguments())
+ .isEqualTo(ImmutableList.of("--path", "dir/file1.txt", "dir/file2.txt"));
}
@Test
public void testNestedSetArtifactExecPathsArgs() {
CustomCommandLine cl = CustomCommandLine.builder().addExecPaths(
NestedSetBuilder.<Artifact>stableOrder().add(artifact1).add(artifact2).build()).build();
- assertEquals(ImmutableList.of("dir/file1.txt", "dir/file2.txt"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("dir/file1.txt", "dir/file2.txt"));
}
@Test
public void testArtifactJoinExecPathArgs() {
CustomCommandLine cl = CustomCommandLine.builder().addJoinExecPaths("--path", ":",
ImmutableList.of(artifact1, artifact2)).build();
- assertEquals(ImmutableList.of("--path", "dir/file1.txt:dir/file2.txt"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("--path", "dir/file1.txt:dir/file2.txt"));
}
@Test
public void testPathArgs() {
CustomCommandLine cl = CustomCommandLine.builder().addPath(artifact1.getExecPath()).build();
- assertEquals(ImmutableList.of("dir/file1.txt"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("dir/file1.txt"));
}
@Test
public void testJoinPathArgs() {
CustomCommandLine cl = CustomCommandLine.builder().addJoinPaths(":",
ImmutableList.of(artifact1.getExecPath(), artifact2.getExecPath())).build();
- assertEquals(ImmutableList.of("dir/file1.txt:dir/file2.txt"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("dir/file1.txt:dir/file2.txt"));
}
@Test
public void testPathsArgs() {
CustomCommandLine cl = CustomCommandLine.builder().addPaths("%s:%s",
artifact1.getExecPath(), artifact1.getRootRelativePath()).build();
- assertEquals(ImmutableList.of("dir/file1.txt:dir/file1.txt"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("dir/file1.txt:dir/file1.txt"));
}
@Test
@@ -158,7 +158,7 @@ public class CustomCommandLineTest {
return "--arg";
}
}).build();
- assertEquals(ImmutableList.of("--arg"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("--arg"));
}
@Test
@@ -169,7 +169,7 @@ public class CustomCommandLineTest {
return ImmutableList.of("--arg1", "--arg2");
}
}).build();
- assertEquals(ImmutableList.of("--arg1", "--arg2"), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of("--arg1", "--arg2"));
}
@Test
@@ -180,8 +180,10 @@ public class CustomCommandLineTest {
.addExecPaths("--path1", ImmutableList.of(artifact1))
.addExecPath("--path2", artifact2)
.build();
- assertEquals(ImmutableList.of("--arg", "--args", "abc", "--path1", "dir/file1.txt", "--path2",
- "dir/file2.txt"), cl.arguments());
+ assertThat(cl.arguments())
+ .isEqualTo(
+ ImmutableList.of(
+ "--arg", "--args", "abc", "--path1", "dir/file1.txt", "--path2", "dir/file2.txt"));
}
@Test
@@ -191,7 +193,7 @@ public class CustomCommandLineTest {
.addExecPaths(null, ImmutableList.of(artifact1))
.addExecPath(null, null)
.build();
- assertEquals(ImmutableList.of(), cl.arguments());
+ assertThat(cl.arguments()).isEqualTo(ImmutableList.of());
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/actions/DigestUtilsTest.java b/src/test/java/com/google/devtools/build/lib/actions/DigestUtilsTest.java
index b37eb4c830..20ef2cfd05 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/DigestUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/DigestUtilsTest.java
@@ -13,12 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.base.Strings;
@@ -116,10 +111,10 @@ public class DigestUtilsTest {
thread1.start();
thread2.start();
if (!expectConcurrent) { // Synchronized case.
- // Wait until at least one thread reached getMD5Digest().
- assertTrue(readyLatch.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
- // Only 1 thread should be inside getMD5Digest().
- assertEquals(1, barrierLatch.getCount());
+ // Wait until at least one thread reached getMD5Digest().
+ assertThat(readyLatch.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue();
+ // Only 1 thread should be inside getMD5Digest().
+ assertThat(barrierLatch.getCount()).isEqualTo(1);
barrierLatch.countDown(); // Release barrier latch, allowing both threads to proceed.
}
// Test successful execution within 5 seconds.
@@ -158,9 +153,9 @@ public class DigestUtilsTest {
for (HashFunction hf : hashFunctions) {
FileSystem.setDigestFunctionForTesting(hf);
byte[] result = DigestUtils.getDigestOrFail(path, 1);
- assertArrayEquals(path.getDigest(), result);
- assertNotSame(malformed, result);
- assertTrue(path.isValidDigest(result));
+ assertThat(result).isEqualTo(path.getDigest());
+ assertThat(result).isNotSameAs(malformed);
+ assertThat(path.isValidDigest(result)).isTrue();
}
}
@@ -182,7 +177,7 @@ public class DigestUtilsTest {
@Test
public void testRecoverFromMalformedDigestWithCache() throws Exception {
DigestUtils.configureCache(10);
- assertNotNull(DigestUtils.getCacheStats()); // Ensure the cache is enabled.
+ assertThat(DigestUtils.getCacheStats()).isNotNull(); // Ensure the cache is enabled.
// When using the cache, we cannot run our test using different hash functions because the
// hash function is not part of the cache key. This is intentional: the hash function is
@@ -190,7 +185,7 @@ public class DigestUtilsTest {
// function twice to further exercise the cache code.
assertRecoverFromMalformedDigest(HashFunction.MD5, HashFunction.MD5);
- assertNotNull(DigestUtils.getCacheStats()); // Ensure the cache remains enabled.
+ assertThat(DigestUtils.getCacheStats()).isNotNull(); // Ensure the cache remains enabled.
}
/** Helper class to assert the cache statistics. */
@@ -225,9 +220,9 @@ public class DigestUtilsTest {
}
void check() throws Exception {
- assertEquals(expectedEvictionCount, stats.evictionCount());
- assertEquals(expectedHitCount, stats.hitCount());
- assertEquals(expectedMissCount, stats.missCount());
+ assertThat(stats.evictionCount()).isEqualTo(expectedEvictionCount);
+ assertThat(stats.hitCount()).isEqualTo(expectedHitCount);
+ assertThat(stats.missCount()).isEqualTo(expectedMissCount);
}
}
@@ -261,16 +256,16 @@ public class DigestUtilsTest {
FileSystemUtils.writeContentAsLatin1(file3, "and something else");
byte[] digest1 = DigestUtils.getDigestOrFail(file1, file1.getFileSize());
- assertEquals(1, getFastDigestCounter.get());
- assertEquals(1, getDigestCounter.get());
+ assertThat(getFastDigestCounter.get()).isEqualTo(1);
+ assertThat(getDigestCounter.get()).isEqualTo(1);
new CacheStatsChecker().evictionCount(0).hitCount(0).missCount(1).check();
byte[] digest2 = DigestUtils.getDigestOrFail(file1, file1.getFileSize());
- assertEquals(2, getFastDigestCounter.get());
- assertEquals(1, getDigestCounter.get());
+ assertThat(getFastDigestCounter.get()).isEqualTo(2);
+ assertThat(getDigestCounter.get()).isEqualTo(1);
new CacheStatsChecker().evictionCount(0).hitCount(1).missCount(1).check();
- assertArrayEquals(digest1, digest2);
+ assertThat(digest2).isEqualTo(digest1);
// Evict the digest for the previous file.
DigestUtils.getDigestOrFail(file2, file2.getFileSize());
@@ -281,6 +276,6 @@ public class DigestUtilsTest {
byte[] digest3 = DigestUtils.getDigestOrFail(file1, file1.getFileSize());
new CacheStatsChecker().evictionCount(2).hitCount(1).missCount(4).check();
- assertArrayEquals(digest1, digest3);
+ assertThat(digest3).isEqualTo(digest1);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/actions/ExecutableSymlinkActionTest.java b/src/test/java/com/google/devtools/build/lib/actions/ExecutableSymlinkActionTest.java
index 61fc21815a..ee86d56a13 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/ExecutableSymlinkActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/ExecutableSymlinkActionTest.java
@@ -13,11 +13,9 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableMap;
@@ -68,7 +66,7 @@ public class ExecutableSymlinkActionTest {
Artifact output = new Artifact(outputFile, outputRoot);
ExecutableSymlinkAction action = new ExecutableSymlinkAction(NULL_ACTION_OWNER, input, output);
action.execute(createContext());
- assertEquals(inputFile, outputFile.resolveSymbolicLinks());
+ assertThat(outputFile.resolveSymbolicLinks()).isEqualTo(inputFile);
}
@Test
@@ -82,7 +80,7 @@ public class ExecutableSymlinkActionTest {
action.execute(createContext());
fail();
} catch (ActionExecutionException e) {
- assertThat(e.getMessage()).contains("'some-dir' is not a file");
+ assertThat(e).hasMessageThat().contains("'some-dir' is not a file");
}
}
@@ -100,7 +98,9 @@ public class ExecutableSymlinkActionTest {
} catch (ActionExecutionException e) {
String want = "'some-file' is not executable";
String got = e.getMessage();
- assertTrue(String.format("got %s, want %s", got, want), got.contains(want));
+ assertWithMessage(String.format("got %s, want %s", got, want))
+ .that(got.contains(want))
+ .isTrue();
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/actions/FailActionTest.java b/src/test/java/com/google/devtools/build/lib/actions/FailActionTest.java
index e21ed945e5..f3395198c4 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/FailActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/FailActionTest.java
@@ -13,23 +13,19 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;
-import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.testutil.Scratch;
-
+import java.util.Collection;
+import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Collection;
-import java.util.Collections;
-
@RunWith(JUnit4.class)
public class FailActionTest {
@@ -50,7 +46,7 @@ public class FailActionTest {
outputs = ImmutableList.of(anOutput);
failAction = new FailAction(NULL_ACTION_OWNER, outputs, errorMessage);
actionGraph.registerAction(failAction);
- assertSame(failAction, actionGraph.getGeneratingAction(anOutput));
+ assertThat(actionGraph.getGeneratingAction(anOutput)).isSameAs(failAction);
}
@Test
@@ -75,6 +71,6 @@ public class FailActionTest {
@Test
public void testPrimaryOutput() {
- assertSame(anOutput, failAction.getPrimaryOutput());
+ assertThat(failAction.getPrimaryOutput()).isSameAs(anOutput);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/actions/LocalHostResourceManagerLinuxTest.java b/src/test/java/com/google/devtools/build/lib/actions/LocalHostResourceManagerLinuxTest.java
index 3cd5ded358..1773b94606 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/LocalHostResourceManagerLinuxTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/LocalHostResourceManagerLinuxTest.java
@@ -13,11 +13,10 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.util.StringUtilities;
import com.google.devtools.build.lib.vfs.util.FsApparatus;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -88,10 +87,13 @@ public class LocalHostResourceManagerLinuxTest {
"HugePages_Rsvd: 0",
"Hugepagesize: 2048 kB");
String meminfoFile = scratch.file("test_meminfo_nonht", meminfoContent).getPathString();
- assertEquals(1, LocalHostResourceManagerLinux.getLogicalCpuCountHelper(cpuinfoContent));
- assertEquals(1, LocalHostResourceManagerLinux.getPhysicalCpuCountHelper(1, cpuinfoContent));
+ assertThat(LocalHostResourceManagerLinux.getLogicalCpuCountHelper(cpuinfoContent)).isEqualTo(1);
+ assertThat(LocalHostResourceManagerLinux.getPhysicalCpuCountHelper(1, cpuinfoContent))
+ .isEqualTo(1);
// +/- 0.1MB
- assertEquals(3091.732, LocalHostResourceManagerLinux.getMemoryInMbHelper(meminfoFile), 0.1);
+ assertThat(LocalHostResourceManagerLinux.getMemoryInMbHelper(meminfoFile))
+ .isWithin(0.1)
+ .of(3091.732);
}
@Test
@@ -181,10 +183,13 @@ public class LocalHostResourceManagerLinuxTest {
"HugePages_Rsvd: 0",
"Hugepagesize: 2048 kB");
String meminfoFile = scratch.file("test_meminfo_ht", meminfoContent).getPathString();
- assertEquals(2, LocalHostResourceManagerLinux.getLogicalCpuCountHelper(cpuinfoContent));
- assertEquals(1, LocalHostResourceManagerLinux.getPhysicalCpuCountHelper(2, cpuinfoContent));
+ assertThat(LocalHostResourceManagerLinux.getLogicalCpuCountHelper(cpuinfoContent)).isEqualTo(2);
+ assertThat(LocalHostResourceManagerLinux.getPhysicalCpuCountHelper(2, cpuinfoContent))
+ .isEqualTo(1);
// +/- 0.1MB
- assertEquals(3092.004, LocalHostResourceManagerLinux.getMemoryInMbHelper(meminfoFile), 0.1);
+ assertThat(LocalHostResourceManagerLinux.getMemoryInMbHelper(meminfoFile))
+ .isWithin(0.1)
+ .of(3092.004);
}
@Test
@@ -332,9 +337,12 @@ public class LocalHostResourceManagerLinuxTest {
"HugePages_Rsvd: 0",
"Hugepagesize: 2048 kB");
String meminfoFile = scratch.file("test_meminfo_amd", meminfoContent).getPathString();
- assertEquals(4, LocalHostResourceManagerLinux.getLogicalCpuCountHelper(cpuinfoContent));
- assertEquals(4, LocalHostResourceManagerLinux.getPhysicalCpuCountHelper(4, cpuinfoContent));
+ assertThat(LocalHostResourceManagerLinux.getLogicalCpuCountHelper(cpuinfoContent)).isEqualTo(4);
+ assertThat(LocalHostResourceManagerLinux.getPhysicalCpuCountHelper(4, cpuinfoContent))
+ .isEqualTo(4);
// +/- 0.1MB
- assertEquals(8223.956, LocalHostResourceManagerLinux.getMemoryInMbHelper(meminfoFile), 0.1);
+ assertThat(LocalHostResourceManagerLinux.getMemoryInMbHelper(meminfoFile))
+ .isWithin(0.1)
+ .of(8223.956);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/actions/ResourceManagerTest.java b/src/test/java/com/google/devtools/build/lib/actions/ResourceManagerTest.java
index a6eff2e633..fbe74fbae2 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/ResourceManagerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/ResourceManagerTest.java
@@ -13,11 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -73,12 +69,12 @@ public class ResourceManagerTest {
}
private void validate(int count) {
- assertEquals(count, counter.incrementAndGet());
+ assertThat(counter.incrementAndGet()).isEqualTo(count);
}
@Test
public void testOverBudgetRequests() throws Exception {
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// When nothing is consuming RAM,
// Then Resource Manager will successfully acquire an over-budget request for RAM:
@@ -86,37 +82,37 @@ public class ResourceManagerTest {
acquire(bigRam, 0, 0, 0);
// When RAM is consumed,
// Then Resource Manager will be "in use":
- assertTrue(rm.inUse());
+ assertThat(rm.inUse()).isTrue();
release(bigRam, 0, 0, 0);
// When that RAM is released,
// Then Resource Manager will not be "in use":
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Ditto, for CPU:
double bigCpu = 10.0;
acquire(0, bigCpu, 0, 0);
- assertTrue(rm.inUse());
+ assertThat(rm.inUse()).isTrue();
release(0, bigCpu, 0, 0);
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Ditto, for IO:
double bigIo = 10.0;
acquire(0, 0, bigIo, 0);
- assertTrue(rm.inUse());
+ assertThat(rm.inUse()).isTrue();
release(0, 0, bigIo, 0);
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Ditto, for tests:
int bigTests = 10;
acquire(0, 0, 0, bigTests);
- assertTrue(rm.inUse());
+ assertThat(rm.inUse()).isTrue();
release(0, 0, 0, bigTests);
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
}
@Test
public void testThatCpuCanBeOverallocated() throws Exception {
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Given CPU is partially acquired:
acquire(0, 0.5, 0, 0);
@@ -136,7 +132,7 @@ public class ResourceManagerTest {
@Test
public void testThatCpuAllocationIsNoncommutative() throws Exception {
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Given that CPU has a small initial allocation:
acquire(0, 0.099, 0, 0);
@@ -157,7 +153,7 @@ public class ResourceManagerTest {
// Cleanup
release(0, 0.099, 0, 0);
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Given that CPU has a large initial allocation:
acquire(0, 0.99, 0, 0);
@@ -178,7 +174,7 @@ public class ResourceManagerTest {
@Test
public void testThatRamCannotBeOverallocated() throws Exception {
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Given RAM is partially acquired:
acquire(500, 0, 0, 0);
@@ -198,7 +194,7 @@ public class ResourceManagerTest {
@Test
public void testThatIOCannotBeOverallocated() throws Exception {
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Given IO is partially acquired:
acquire(0, 0, 0.5, 0);
@@ -218,7 +214,7 @@ public class ResourceManagerTest {
@Test
public void testThatTestsCannotBeOverallocated() throws Exception {
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Given test count is partially acquired:
acquire(0, 0, 0, 1);
@@ -238,93 +234,99 @@ public class ResourceManagerTest {
@Test
public void testHasResources() throws Exception {
- assertFalse(rm.inUse());
- assertFalse(rm.threadHasResources());
+ assertThat(rm.inUse()).isFalse();
+ assertThat(rm.threadHasResources()).isFalse();
acquire(1.0, 0.1, 0.1, 1);
- assertTrue(rm.threadHasResources());
+ assertThat(rm.threadHasResources()).isTrue();
// We have resources in this thread - make sure other threads
// are not affected.
- TestThread thread1 = new TestThread () {
- @Override public void runTest() throws Exception {
- assertFalse(rm.threadHasResources());
- acquire(1.0, 0, 0, 0);
- assertTrue(rm.threadHasResources());
- release(1.0, 0, 0, 0);
- assertFalse(rm.threadHasResources());
- acquire(0, 0.1, 0, 0);
- assertTrue(rm.threadHasResources());
- release(0, 0.1, 0, 0);
- assertFalse(rm.threadHasResources());
- acquire(0, 0, 0.1, 0);
- assertTrue(rm.threadHasResources());
- release(0, 0, 0.1, 0);
- assertFalse(rm.threadHasResources());
- acquire(0, 0, 0, 1);
- assertTrue(rm.threadHasResources());
- release(0, 0, 0, 1);
- assertFalse(rm.threadHasResources());
- }
- };
+ TestThread thread1 =
+ new TestThread() {
+ @Override
+ public void runTest() throws Exception {
+ assertThat(rm.threadHasResources()).isFalse();
+ acquire(1.0, 0, 0, 0);
+ assertThat(rm.threadHasResources()).isTrue();
+ release(1.0, 0, 0, 0);
+ assertThat(rm.threadHasResources()).isFalse();
+ acquire(0, 0.1, 0, 0);
+ assertThat(rm.threadHasResources()).isTrue();
+ release(0, 0.1, 0, 0);
+ assertThat(rm.threadHasResources()).isFalse();
+ acquire(0, 0, 0.1, 0);
+ assertThat(rm.threadHasResources()).isTrue();
+ release(0, 0, 0.1, 0);
+ assertThat(rm.threadHasResources()).isFalse();
+ acquire(0, 0, 0, 1);
+ assertThat(rm.threadHasResources()).isTrue();
+ release(0, 0, 0, 1);
+ assertThat(rm.threadHasResources()).isFalse();
+ }
+ };
thread1.start();
thread1.joinAndAssertState(10000);
release(1.0, 0.1, 0.1, 1);
- assertFalse(rm.threadHasResources());
- assertFalse(rm.inUse());
+ assertThat(rm.threadHasResources()).isFalse();
+ assertThat(rm.inUse()).isFalse();
}
@Test
public void testConcurrentLargeRequests() throws Exception {
- assertFalse(rm.inUse());
- TestThread thread1 = new TestThread () {
- @Override public void runTest() throws Exception {
- acquire(2000, 2, 0, 0);
- sync.await();
- validate(1);
- sync.await();
- // Wait till other thread will be locked.
- while (rm.getWaitCount() == 0) {
- Thread.yield();
- }
- release(2000, 2, 0, 0);
- assertEquals(0, rm.getWaitCount());
- acquire(2000, 2, 0, 0); // Will be blocked by the thread2.
- validate(3);
- release(2000, 2, 0, 0);
- }
- };
- TestThread thread2 = new TestThread () {
- @Override public void runTest() throws Exception {
- sync2.await();
- assertFalse(rm.isAvailable(2000, 2, 0, 0));
- acquire(2000, 2, 0, 0); // Will be blocked by the thread1.
- validate(2);
- sync2.await();
- // Wait till other thread will be locked.
- while (rm.getWaitCount() == 0) {
- Thread.yield();
- }
- release(2000, 2, 0, 0);
- }
- };
+ assertThat(rm.inUse()).isFalse();
+ TestThread thread1 =
+ new TestThread() {
+ @Override
+ public void runTest() throws Exception {
+ acquire(2000, 2, 0, 0);
+ sync.await();
+ validate(1);
+ sync.await();
+ // Wait till other thread will be locked.
+ while (rm.getWaitCount() == 0) {
+ Thread.yield();
+ }
+ release(2000, 2, 0, 0);
+ assertThat(rm.getWaitCount()).isEqualTo(0);
+ acquire(2000, 2, 0, 0); // Will be blocked by the thread2.
+ validate(3);
+ release(2000, 2, 0, 0);
+ }
+ };
+ TestThread thread2 =
+ new TestThread() {
+ @Override
+ public void runTest() throws Exception {
+ sync2.await();
+ assertThat(rm.isAvailable(2000, 2, 0, 0)).isFalse();
+ acquire(2000, 2, 0, 0); // Will be blocked by the thread1.
+ validate(2);
+ sync2.await();
+ // Wait till other thread will be locked.
+ while (rm.getWaitCount() == 0) {
+ Thread.yield();
+ }
+ release(2000, 2, 0, 0);
+ }
+ };
thread1.start();
thread2.start();
sync.await(1, TimeUnit.SECONDS);
- assertTrue(rm.inUse());
- assertEquals(0, rm.getWaitCount());
+ assertThat(rm.inUse()).isTrue();
+ assertThat(rm.getWaitCount()).isEqualTo(0);
sync2.await(1, TimeUnit.SECONDS);
sync.await(1, TimeUnit.SECONDS);
sync2.await(1, TimeUnit.SECONDS);
thread1.joinAndAssertState(1000);
thread2.joinAndAssertState(1000);
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
}
@Test
public void testInterruptedAcquisitionClearsResources() throws Exception {
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
// Acquire a small amount of resources so that future requests can block (the initial request
// always succeeds even if it's for too much).
TestThread smallThread =
@@ -373,7 +375,7 @@ public class ResourceManagerTest {
final CyclicBarrier sync3 = new CyclicBarrier(2);
final CyclicBarrier sync4 = new CyclicBarrier(2);
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
TestThread thread1 = new TestThread () {
@Override public void runTest() throws Exception {
@@ -464,7 +466,7 @@ public class ResourceManagerTest {
thread3.join();
thread4.join();
- assertFalse(rm.inUse());
+ assertThat(rm.inUse()).isFalse();
}
private static class ResourceOwnerStub implements ActionExecutionMetadata {
diff --git a/src/test/java/com/google/devtools/build/lib/actions/ResourceSetTest.java b/src/test/java/com/google/devtools/build/lib/actions/ResourceSetTest.java
index 8a085c15a4..a5a2ca0bfd 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/ResourceSetTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/ResourceSetTest.java
@@ -13,13 +13,11 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.actions.ResourceSet.ResourceSetConverter;
import com.google.devtools.common.options.OptionsParsingException;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -41,10 +39,10 @@ public class ResourceSetTest {
@Test
public void testConverterParsesExpectedFormat() throws Exception {
ResourceSet resources = converter.convert("1,0.5,2");
- assertEquals(1.0, resources.getMemoryMb(), 0.01);
- assertEquals(0.5, resources.getCpuUsage(), 0.01);
- assertEquals(2.0, resources.getIoUsage(), 0.01);
- assertEquals(Integer.MAX_VALUE, resources.getLocalTestCount());
+ assertThat(resources.getMemoryMb()).isWithin(0.01).of(1.0);
+ assertThat(resources.getCpuUsage()).isWithin(0.01).of(0.5);
+ assertThat(resources.getIoUsage()).isWithin(0.01).of(2.0);
+ assertThat(resources.getLocalTestCount()).isEqualTo(Integer.MAX_VALUE);
}
@Test(expected = OptionsParsingException.class)
diff --git a/src/test/java/com/google/devtools/build/lib/actions/RootTest.java b/src/test/java/com/google/devtools/build/lib/actions/RootTest.java
index 92b0567699..36ede38c34 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/RootTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/RootTest.java
@@ -13,26 +13,19 @@
// limitations under the License.
package com.google.devtools.build.lib.actions;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.testing.EqualsTester;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
-
+import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.IOException;
-
-/**
- * Tests for {@link Root}.
- */
+/** Tests for {@link Root}. */
@RunWith(JUnit4.class)
public class RootTest {
private Scratch scratch = new Scratch();
@@ -41,10 +34,10 @@ public class RootTest {
public void testAsSourceRoot() throws IOException {
Path sourceDir = scratch.dir("/source");
Root root = Root.asSourceRoot(sourceDir);
- assertTrue(root.isSourceRoot());
- assertEquals(PathFragment.EMPTY_FRAGMENT, root.getExecPath());
- assertEquals(sourceDir, root.getPath());
- assertEquals("/source[source]", root.toString());
+ assertThat(root.isSourceRoot()).isTrue();
+ assertThat(root.getExecPath()).isEqualTo(PathFragment.EMPTY_FRAGMENT);
+ assertThat(root.getPath()).isEqualTo(sourceDir);
+ assertThat(root.toString()).isEqualTo("/source[source]");
}
@Test
@@ -61,10 +54,10 @@ public class RootTest {
Path execRoot = scratch.dir("/exec");
Path rootDir = scratch.dir("/exec/root");
Root root = Root.asDerivedRoot(execRoot, rootDir);
- assertFalse(root.isSourceRoot());
- assertEquals(PathFragment.create("root"), root.getExecPath());
- assertEquals(rootDir, root.getPath());
- assertEquals("/exec/root[derived]", root.toString());
+ assertThat(root.isSourceRoot()).isFalse();
+ assertThat(root.getExecPath()).isEqualTo(PathFragment.create("root"));
+ assertThat(root.getPath()).isEqualTo(rootDir);
+ assertThat(root.toString()).isEqualTo("/exec/root[derived]");
}
@Test
@@ -125,8 +118,8 @@ public class RootTest {
if (expected) {
new EqualsTester().addEqualityGroup(b, a).testEquals();
} else {
- assertFalse(a.equals(b));
- assertFalse(a.hashCode() == b.hashCode());
+ assertThat(a.equals(b)).isFalse();
+ assertThat(a.hashCode() == b.hashCode()).isFalse();
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/actions/cache/CompactPersistentActionCacheTest.java b/src/test/java/com/google/devtools/build/lib/actions/cache/CompactPersistentActionCacheTest.java
index b731f6f69d..c2bf185d29 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/cache/CompactPersistentActionCacheTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/cache/CompactPersistentActionCacheTest.java
@@ -13,31 +13,21 @@
// limitations under the License.
package com.google.devtools.build.lib.actions.cache;
-
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.util.Clock;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
-
+import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.IOException;
-
-/**
- * Test for the CompactPersistentActionCache class.
- */
+/** Test for the CompactPersistentActionCache class. */
@RunWith(JUnit4.class)
public class CompactPersistentActionCacheTest {
@@ -72,7 +62,7 @@ public class CompactPersistentActionCacheTest {
@Test
public void testGetInvalidKey() {
- assertNull(cache.get("key"));
+ assertThat(cache.get("key")).isNull();
}
@Test
@@ -80,9 +70,9 @@ public class CompactPersistentActionCacheTest {
String key = "key";
putKey(key);
ActionCache.Entry readentry = cache.get(key);
- assertNotNull(readentry);
- assertEquals(cache.get(key).toString(), readentry.toString());
- assertFalse(mapFile.exists());
+ assertThat(readentry).isNotNull();
+ assertThat(readentry.toString()).isEqualTo(cache.get(key).toString());
+ assertThat(mapFile.exists()).isFalse();
}
@Test
@@ -90,8 +80,8 @@ public class CompactPersistentActionCacheTest {
String key = "key";
putKey(key);
cache.remove(key);
- assertNull(cache.get(key));
- assertFalse(mapFile.exists());
+ assertThat(cache.get(key)).isNull();
+ assertThat(mapFile.exists()).isFalse();
}
@Test
@@ -108,14 +98,14 @@ public class CompactPersistentActionCacheTest {
String key = "key";
putKey(key, discoverInputs);
cache.save();
- assertTrue(mapFile.exists());
- assertFalse(journalFile.exists());
+ assertThat(mapFile.exists()).isTrue();
+ assertThat(journalFile.exists()).isFalse();
CompactPersistentActionCache newcache =
new CompactPersistentActionCache(dataRoot, clock);
ActionCache.Entry readentry = newcache.get(key);
- assertNotNull(readentry);
- assertEquals(cache.get(key).toString(), readentry.toString());
+ assertThat(readentry).isNotNull();
+ assertThat(readentry.toString()).isEqualTo(cache.get(key).toString());
}
@Test
@@ -150,8 +140,8 @@ public class CompactPersistentActionCacheTest {
}
assertKeyEquals(cache, newerCache, "abc");
assertKeyEquals(cache, newerCache, "123");
- assertNotNull(newerCache.get("xyz"));
- assertNull(newerCache.get("not_a_key"));
+ assertThat(newerCache.get("xyz")).isNotNull();
+ assertThat(newerCache.get("not_a_key")).isNull();
// Add another 10 entries. This should not be incremental.
for (int i = 300; i < 310; i++) {
@@ -194,20 +184,20 @@ public class CompactPersistentActionCacheTest {
private static void assertKeyEquals(ActionCache cache1, ActionCache cache2, String key) {
Object entry = cache1.get(key);
- assertNotNull(entry);
- assertEquals(entry.toString(), cache2.get(key).toString());
+ assertThat(entry).isNotNull();
+ assertThat(cache2.get(key).toString()).isEqualTo(entry.toString());
}
private void assertFullSave() throws IOException {
cache.save();
- assertTrue(mapFile.exists());
- assertFalse(journalFile.exists());
+ assertThat(mapFile.exists()).isTrue();
+ assertThat(journalFile.exists()).isFalse();
}
private void assertIncrementalSave(ActionCache ac) throws IOException {
ac.save();
- assertTrue(mapFile.exists());
- assertTrue(journalFile.exists());
+ assertThat(mapFile.exists()).isTrue();
+ assertThat(journalFile.exists()).isTrue();
}
private void putKey(String key) {
diff --git a/src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java b/src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java
index 2c9dfe2555..7b4c01457d 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.actions.cache;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.testutil.Scratch;
@@ -24,12 +21,6 @@ import com.google.devtools.build.lib.testutil.TestThread;
import com.google.devtools.build.lib.util.Clock;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
@@ -38,6 +29,10 @@ import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Test for the PersistentStringIndexer class.
@@ -79,12 +74,12 @@ public class PersistentStringIndexerTest {
}
private void assertSize(int expected) {
- assertEquals(expected, psi.size());
+ assertThat(psi.size()).isEqualTo(expected);
}
private void assertIndex(int expected, String s) {
int index = psi.getOrCreateIndex(s);
- assertEquals(expected, index);
+ assertThat(index).isEqualTo(expected);
mappings.put(expected, s);
}
@@ -150,109 +145,111 @@ public class PersistentStringIndexerTest {
@Test
public void testNormalOperation() throws Exception {
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
setupTestContent();
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
clock.advance(4);
assertIndex(9, "xyzqwerty"); // This should flush journal to disk.
- assertFalse(dataPath.exists());
- assertTrue(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isTrue();
psi.save(); // Successful save will remove journal file.
- assertTrue(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isFalse();
// Now restore data from file and verify it.
psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- assertFalse(journalPath.exists());
+ assertThat(journalPath.exists()).isFalse();
clock.advance(4);
assertSize(10);
assertContent();
- assertFalse(journalPath.exists());
+ assertThat(journalPath.exists()).isFalse();
}
@Test
public void testJournalRecoveryWithoutMainDataFile() throws Exception {
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
setupTestContent();
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
clock.advance(4);
assertIndex(9, "abc1234"); // This should flush journal to disk.
- assertFalse(dataPath.exists());
- assertTrue(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isTrue();
// Now restore data from file and verify it. All data should be restored from journal;
psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- assertTrue(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isFalse();
clock.advance(4);
assertSize(10);
assertContent();
- assertFalse(journalPath.exists());
+ assertThat(journalPath.exists()).isFalse();
}
@Test
public void testJournalRecovery() throws Exception {
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
setupTestContent();
psi.save();
- assertTrue(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isFalse();
long oldDataFileLen = dataPath.getFileSize();
clock.advance(4);
assertIndex(9, "another record"); // This should flush journal to disk.
assertSize(10);
- assertTrue(dataPath.exists());
- assertTrue(journalPath.exists());
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isTrue();
// Now restore data from file and verify it. All data should be restored from journal;
psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- assertTrue(dataPath.exists());
- assertFalse(journalPath.exists());
- assertTrue(dataPath.getFileSize() > oldDataFileLen); // data file should have been updated
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isFalse();
+ assertThat(dataPath.getFileSize())
+ .isGreaterThan(oldDataFileLen); // data file should have been updated
clock.advance(4);
assertSize(10);
assertContent();
- assertFalse(journalPath.exists());
+ assertThat(journalPath.exists()).isFalse();
}
@Test
public void testConcurrentWritesJournalRecovery() throws Exception {
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
setupTestContent();
psi.save();
- assertTrue(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isFalse();
long oldDataFileLen = dataPath.getFileSize();
int size = psi.size();
int numToWrite = 50000;
writeLotsOfEntriesConcurrently(numToWrite);
- assertFalse(journalPath.exists());
+ assertThat(journalPath.exists()).isFalse();
clock.advance(4);
assertIndex(size + numToWrite, "another record"); // This should flush journal to disk.
assertSize(size + numToWrite + 1);
- assertTrue(dataPath.exists());
- assertTrue(journalPath.exists());
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isTrue();
// Now restore data from file and verify it. All data should be restored from journal;
psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- assertTrue(dataPath.exists());
- assertFalse(journalPath.exists());
- assertTrue(dataPath.getFileSize() > oldDataFileLen); // data file should have been updated
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isFalse();
+ assertThat(dataPath.getFileSize())
+ .isGreaterThan(oldDataFileLen); // data file should have been updated
clock.advance(4);
assertSize(size + numToWrite + 1);
assertContent();
- assertFalse(journalPath.exists());
+ assertThat(journalPath.exists()).isFalse();
}
@Test
@@ -263,28 +260,28 @@ public class PersistentStringIndexerTest {
psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
fail();
} catch (IOException e) {
- assertThat(e.getMessage()).contains("too short: Only 13 bytes");
+ assertThat(e).hasMessageThat().contains("too short: Only 13 bytes");
}
journalPath.delete();
setupTestContent();
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
clock.advance(4);
assertIndex(9, "abc1234"); // This should flush journal to disk.
- assertFalse(dataPath.exists());
- assertTrue(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isTrue();
byte[] journalContent = FileSystemUtils.readContent(journalPath);
// Now restore data from file and verify it. All data should be restored from journal;
psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- assertTrue(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isFalse();
// Now put back truncated journal. We should get an error.
- assertTrue(dataPath.delete());
+ assertThat(dataPath.delete()).isTrue();
FileSystemUtils.writeContent(journalPath,
Arrays.copyOf(journalContent, journalContent.length - 1));
try {
@@ -304,7 +301,7 @@ public class PersistentStringIndexerTest {
fail();
} catch (IOException e) {
// Expected.
- assertThat(e.getMessage()).contains("corrupt key length");
+ assertThat(e).hasMessageThat().contains("corrupt key length");
}
// Now put back corrupted journal. We should get an error.
@@ -321,13 +318,13 @@ public class PersistentStringIndexerTest {
@Test
public void testDupeIndexCorruption() throws Exception {
setupTestContent();
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
assertIndex(9, "abc1234"); // This should flush journal to disk.
psi.save();
- assertTrue(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isTrue();
+ assertThat(journalPath.exists()).isFalse();
byte[] content = FileSystemUtils.readContent(dataPath);
@@ -344,7 +341,7 @@ public class PersistentStringIndexerTest {
// index that is guaranteed to already exist. If it is the index 1, we change it to 2, otherwise
// we change it to 1 - in both cases, the code currently guarantees that the duplicate comes
// earlier in the stream.
- assertTrue(dataPath.delete());
+ assertThat(dataPath.delete()).isTrue();
content[content.length - 1] = content[content.length - 1] == 1 ? (byte) 2 : (byte) 1;
FileSystemUtils.writeContent(journalPath, content);
@@ -353,24 +350,24 @@ public class PersistentStringIndexerTest {
fail();
} catch (IOException e) {
// Expected.
- assertThat(e.getMessage()).contains("Corrupted filename index has duplicate entry");
+ assertThat(e).hasMessageThat().contains("Corrupted filename index has duplicate entry");
}
}
@Test
public void testDeferredIOFailure() throws Exception {
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
setupTestContent();
- assertFalse(dataPath.exists());
- assertFalse(journalPath.exists());
+ assertThat(dataPath.exists()).isFalse();
+ assertThat(journalPath.exists()).isFalse();
// Ensure that journal cannot be saved.
FileSystemUtils.createDirectoryAndParents(journalPath);
clock.advance(4);
assertIndex(9, "abc1234"); // This should flush journal to disk (and fail at that).
- assertFalse(dataPath.exists());
+ assertThat(dataPath.exists()).isFalse();
// Subsequent updates should succeed even though journaling is disabled at this point.
clock.advance(4);
@@ -381,7 +378,7 @@ public class PersistentStringIndexerTest {
psi.save();
fail();
} catch(IOException e) {
- assertThat(e.getMessage()).contains(journalPath.getPathString() + " (Is a directory)");
+ assertThat(e).hasMessageThat().contains(journalPath.getPathString() + " (Is a directory)");
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/AnalysisCachingTest.java b/src/test/java/com/google/devtools/build/lib/analysis/AnalysisCachingTest.java
index 2a86b99514..714c539a1a 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/AnalysisCachingTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/AnalysisCachingTest.java
@@ -13,12 +13,9 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis;
+
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -51,8 +48,8 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
" srcs = ['A.java'])");
update("//java/a:A");
ConfiguredTarget javaTest = getConfiguredTarget("//java/a:A");
- assertNotNull(javaTest);
- assertNotNull(javaTest.getProvider(JavaSourceJarsProvider.class));
+ assertThat(javaTest).isNotNull();
+ assertThat(javaTest.getProvider(JavaSourceJarsProvider.class)).isNotNull();
}
@Test
@@ -76,7 +73,7 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
ConfiguredTarget old = getConfiguredTarget("//java/a:A");
update("//java/a:A");
ConfiguredTarget current = getConfiguredTarget("//java/a:A");
- assertSame(old, current);
+ assertThat(current).isSameAs(old);
}
@Test
@@ -90,7 +87,7 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
ConfiguredTarget old = getConfiguredTarget("//java/a:A");
update("//java/a:A");
ConfiguredTarget current = getConfiguredTarget("//java/a:A");
- assertSame(old, current);
+ assertThat(current).isSameAs(old);
}
@Test
@@ -109,7 +106,7 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
" srcs = ['C.java'])");
update("//java/a:A");
ConfiguredTarget current = getConfiguredTarget("//java/a:A");
- assertNotSame(old, current);
+ assertThat(current).isNotSameAs(old);
}
@Test
@@ -128,7 +125,7 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
" srcs = ['A.java'])");
update("//java/a:A");
ConfiguredTarget current = getConfiguredTarget("//java/a:A");
- assertNotSame(old, current);
+ assertThat(current).isNotSameAs(old);
}
// Regression test for:
@@ -164,7 +161,7 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
update("//conflict:x");
ConfiguredTarget conflict = getConfiguredTarget("//conflict:x");
Action oldAction = getGeneratingAction(getBinArtifact("_objs/x/conflict/foo.pic.o", conflict));
- assertEquals("//conflict:x", oldAction.getOwner().getLabel().toString());
+ assertThat(oldAction.getOwner().getLabel().toString()).isEqualTo("//conflict:x");
scratch.overwriteFile("conflict/BUILD",
"cc_library(name='newx', srcs=['foo.cc'])", // Rename target.
"cc_binary(name='_objs/x/conflict/foo.pic.o', srcs=['bar.cc'])");
@@ -172,8 +169,8 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
ConfiguredTarget objsConflict = getConfiguredTarget("//conflict:_objs/x/conflict/foo.pic.o");
Action newAction =
getGeneratingAction(getBinArtifact("_objs/x/conflict/foo.pic.o", objsConflict));
- assertEquals("//conflict:_objs/x/conflict/foo.pic.o",
- newAction.getOwner().getLabel().toString());
+ assertThat(newAction.getOwner().getLabel().toString())
+ .isEqualTo("//conflict:_objs/x/conflict/foo.pic.o");
}
/**
@@ -265,7 +262,7 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
matchCount++;
}
- assertEquals(5, matchCount);
+ assertThat(matchCount).isEqualTo(5);
}
/**
@@ -283,7 +280,7 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
"//conflict:x", "//conflict:_objs/x/conflict/foo.pic.o");
ConfiguredTarget a = getConfiguredTarget("//conflict:x");
ConfiguredTarget b = getConfiguredTarget("//conflict:_objs/x/conflict/foo.pic.o");
- assertTrue(hasTopLevelAnalysisError(a) ^ hasTopLevelAnalysisError(b));
+ assertThat(hasTopLevelAnalysisError(a) ^ hasTopLevelAnalysisError(b)).isTrue();
}
/**
@@ -315,12 +312,12 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
reporter.addHandler(failFastHandler);
update("//java/a:A");
ConfiguredTarget current = getConfiguredTarget("//java/a:A");
- assertNotSame(old, current);
+ assertThat(current).isNotSameAs(old);
}
private void assertNoTargetsVisited() {
Set<?> analyzedTargets = getSkyframeEvaluatedTargetKeys();
- assertEquals(analyzedTargets.toString(), 0, analyzedTargets.size());
+ assertWithMessage(analyzedTargets.toString()).that(analyzedTargets.size()).isEqualTo(0);
}
@Test
@@ -340,9 +337,9 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
"java_library(name = 'y', srcs = ['B.java'])");
update("//java/a:x");
Set<?> oldAnalyzedTargets = getSkyframeEvaluatedTargetKeys();
- assertTrue(oldAnalyzedTargets.size() >= 2); // could be greater due to implicit deps
- assertEquals(1, countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:x"));
- assertEquals(1, countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:y"));
+ assertThat(oldAnalyzedTargets.size()).isAtLeast(2); // could be greater due to implicit deps
+ assertThat(countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:x")).isEqualTo(1);
+ assertThat(countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:y")).isEqualTo(1);
update("//java/a:y");
assertNoTargetsVisited();
}
@@ -357,14 +354,14 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
"java_library(name = 'z', srcs = ['C.java'])");
update("//java/a:y");
Set<?> oldAnalyzedTargets = getSkyframeEvaluatedTargetKeys();
- assertTrue(oldAnalyzedTargets.size() >= 3); // could be greater due to implicit deps
- assertEquals(0, countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:x"));
- assertEquals(1, countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:y"));
+ assertThat(oldAnalyzedTargets.size()).isAtLeast(3); // could be greater due to implicit deps
+ assertThat(countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:x")).isEqualTo(0);
+ assertThat(countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:y")).isEqualTo(1);
update("//java/a:x");
Set<?> newAnalyzedTargets = getSkyframeEvaluatedTargetKeys();
- assertTrue(newAnalyzedTargets.size() >= 1); // could be greater due to implicit deps
- assertEquals(1, countObjectsPartiallyMatchingRegex(newAnalyzedTargets, "//java/a:x"));
- assertEquals(0, countObjectsPartiallyMatchingRegex(newAnalyzedTargets, "//java/a:y"));
+ assertThat(newAnalyzedTargets).isNotEmpty(); // could be greater due to implicit deps
+ assertThat(countObjectsPartiallyMatchingRegex(newAnalyzedTargets, "//java/a:x")).isEqualTo(1);
+ assertThat(countObjectsPartiallyMatchingRegex(newAnalyzedTargets, "//java/a:y")).isEqualTo(0);
}
@Test
@@ -411,7 +408,7 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
update("//java/a:a");
fail();
} catch (ViewCreationFailedException e) {
- assertThat(e.getMessage()).contains("Analysis of target '//java/a:a' failed");
+ assertThat(e).hasMessageThat().contains("Analysis of target '//java/a:a' failed");
assertContainsEvent("Unable to expand make variables: $(BUG)");
}
}
@@ -430,12 +427,12 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
public void testWorkspaceStatusCommandIsNotCachedForNullBuild() throws Exception {
update();
WorkspaceStatusAction actionA = getView().getLastWorkspaceBuildInfoActionForTesting();
- assertEquals("DummyBuildInfoAction", actionA.getMnemonic());
+ assertThat(actionA.getMnemonic()).isEqualTo("DummyBuildInfoAction");
workspaceStatusActionFactory.setKey("Second");
update();
WorkspaceStatusAction actionB = getView().getLastWorkspaceBuildInfoActionForTesting();
- assertEquals("DummyBuildInfoActionSecond", actionB.getMnemonic());
+ assertThat(actionB.getMnemonic()).isEqualTo("DummyBuildInfoActionSecond");
}
@Test
@@ -453,11 +450,11 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
update(aTarget);
ConfiguredTarget updatedCT = getConfiguredTarget(aTarget);
- assertNotSame(firstCT, updatedCT);
+ assertThat(updatedCT).isNotSameAs(firstCT);
update(aTarget);
ConfiguredTarget updated2CT = getConfiguredTarget(aTarget);
- assertSame(updatedCT, updated2CT);
+ assertThat(updated2CT).isSameAs(updatedCT);
}
@Test
@@ -486,8 +483,8 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
ConfiguredTarget newAConfTarget = getConfiguredTarget(aTarget);
ConfiguredTarget newBConfTarget = getConfiguredTarget(bTarget);
- assertSame(oldAConfTarget, newAConfTarget);
- assertNotSame(oldBConfTarget, newBConfTarget);
+ assertThat(newAConfTarget).isSameAs(oldAConfTarget);
+ assertThat(newBConfTarget).isNotSameAs(oldBConfTarget);
}
private int countObjectsPartiallyMatchingRegex(Iterable<? extends Object> elements,
@@ -512,11 +509,11 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
update("//java/a:x");
Set<?> oldAnalyzedTargets = getSkyframeEvaluatedTargetKeys();
- assertTrue(oldAnalyzedTargets.size() >= 2); // could be greater due to implicit deps
- assertEquals(1, countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:x"));
- assertEquals(0, countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:y"));
- assertEquals(1, countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:z"));
- assertEquals(1, countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:w"));
+ assertThat(oldAnalyzedTargets.size()).isAtLeast(2); // could be greater due to implicit deps
+ assertThat(countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:x")).isEqualTo(1);
+ assertThat(countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:y")).isEqualTo(0);
+ assertThat(countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:z")).isEqualTo(1);
+ assertThat(countObjectsPartiallyMatchingRegex(oldAnalyzedTargets, "//java/a:w")).isEqualTo(1);
// Unless the build is not fully cached, we get notified about newly evaluated targets, as well
// as cached top-level targets. For the two tests above to work correctly, we need to ensure
@@ -524,7 +521,8 @@ public class AnalysisCachingTest extends AnalysisCachingTestBase {
update("//java/a:x", "//java/a:y", "//java/a:z");
Set<?> newAnalyzedTargets = getSkyframeEvaluatedTargetKeys();
assertThat(newAnalyzedTargets).hasSize(2);
- assertEquals(1, countObjectsPartiallyMatchingRegex(newAnalyzedTargets, "//java/a:B.java"));
- assertEquals(1, countObjectsPartiallyMatchingRegex(newAnalyzedTargets, "//java/a:y"));
+ assertThat(countObjectsPartiallyMatchingRegex(newAnalyzedTargets, "//java/a:B.java"))
+ .isEqualTo(1);
+ assertThat(countObjectsPartiallyMatchingRegex(newAnalyzedTargets, "//java/a:y")).isEqualTo(1);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/AspectAwareAttributeMapperTest.java b/src/test/java/com/google/devtools/build/lib/analysis/AspectAwareAttributeMapperTest.java
index 5cbaf479b7..f2aa16e8e8 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/AspectAwareAttributeMapperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/AspectAwareAttributeMapperTest.java
@@ -84,7 +84,8 @@ public class AspectAwareAttributeMapperTest extends BuildViewTestCase {
mapper.get("fromaspect", BuildType.LABEL_LIST);
fail("Expected failure on wrong-typed attribute");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.isEqualTo("attribute fromaspect has type label, not expected type list(label)");
}
}
@@ -95,7 +96,8 @@ public class AspectAwareAttributeMapperTest extends BuildViewTestCase {
mapper.get("noexist", BuildType.LABEL);
fail("Expected failure on non-existent attribute");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.isEqualTo("no attribute 'noexist' in either //foo:myrule or its aspects");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/BlazeDirectoriesTest.java b/src/test/java/com/google/devtools/build/lib/analysis/BlazeDirectoriesTest.java
index 78cba05316..28a4a8c470 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/BlazeDirectoriesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/BlazeDirectoriesTest.java
@@ -13,12 +13,11 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -36,17 +35,17 @@ public class BlazeDirectoriesTest extends FoundationTestCase {
Path outputBase = fs.getPath("/my/output");
Path workspace = fs.getPath("/my/ws");
BlazeDirectories directories = new BlazeDirectories(installBase, outputBase, workspace, "foo");
- assertEquals(directories.getExecRoot(), outputBase.getChild("ws"));
+ assertThat(outputBase.getChild("ws")).isEqualTo(directories.getExecRoot());
workspace = null;
directories = new BlazeDirectories(installBase, outputBase, workspace, "foo");
- assertEquals(directories.getExecRoot(),
- outputBase.getChild(BlazeDirectories.DEFAULT_EXEC_ROOT));
+ assertThat(outputBase.getChild(BlazeDirectories.DEFAULT_EXEC_ROOT))
+ .isEqualTo(directories.getExecRoot());
workspace = fs.getPath("/");
directories = new BlazeDirectories(installBase, outputBase, workspace, "foo");
- assertEquals(directories.getExecRoot(),
- outputBase.getChild(BlazeDirectories.DEFAULT_EXEC_ROOT));
+ assertThat(outputBase.getChild(BlazeDirectories.DEFAULT_EXEC_ROOT))
+ .isEqualTo(directories.getExecRoot());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/BuildViewTest.java b/src/test/java/com/google/devtools/build/lib/analysis/BuildViewTest.java
index 21988605e5..6b36afc68f 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/BuildViewTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/BuildViewTest.java
@@ -18,12 +18,6 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertEventCount;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertEventCountAtLeast;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
@@ -32,7 +26,6 @@ import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
-import com.google.common.truth.Truth;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.Actions;
import com.google.devtools.build.lib.actions.Artifact;
@@ -96,11 +89,11 @@ public class BuildViewTest extends BuildViewTestBase {
" outs=['a.out'])");
update("//pkg:foo");
Rule ruleTarget = (Rule) getTarget("//pkg:foo");
- assertEquals("genrule", ruleTarget.getRuleClass());
+ assertThat(ruleTarget.getRuleClass()).isEqualTo("genrule");
ConfiguredTarget ruleCT = getConfiguredTarget("//pkg:foo");
- assertSame(ruleTarget, ruleCT.getTarget());
+ assertThat(ruleCT.getTarget()).isSameAs(ruleTarget);
}
@Test
@@ -143,8 +136,8 @@ public class BuildViewTest extends BuildViewTestBase {
update("//pkg:a.src");
InputFileConfiguredTarget inputCT = getInputFileConfiguredTarget("//pkg:a.src");
Artifact inputArtifact = inputCT.getArtifact();
- assertNull(getGeneratingAction(inputArtifact));
- assertEquals("pkg/a.src", inputArtifact.getExecPathString());
+ assertThat(getGeneratingAction(inputArtifact)).isNull();
+ assertThat(inputArtifact.getExecPathString()).isEqualTo("pkg/a.src");
}
@Test
@@ -154,16 +147,18 @@ public class BuildViewTest extends BuildViewTestBase {
OutputFileConfiguredTarget outputCT = (OutputFileConfiguredTarget)
getConfiguredTarget("//pkg:a.out");
Artifact outputArtifact = outputCT.getArtifact();
- assertEquals(
- outputCT.getConfiguration().getBinDirectory(
- outputCT.getTarget().getLabel().getPackageIdentifier().getRepository()),
- outputArtifact.getRoot());
- assertEquals(outputCT.getConfiguration().getBinFragment().getRelative("pkg/a.out"),
- outputArtifact.getExecPath());
- assertEquals(PathFragment.create("pkg/a.out"), outputArtifact.getRootRelativePath());
+ assertThat(outputArtifact.getRoot())
+ .isEqualTo(
+ outputCT
+ .getConfiguration()
+ .getBinDirectory(
+ outputCT.getTarget().getLabel().getPackageIdentifier().getRepository()));
+ assertThat(outputArtifact.getExecPath())
+ .isEqualTo(outputCT.getConfiguration().getBinFragment().getRelative("pkg/a.out"));
+ assertThat(outputArtifact.getRootRelativePath()).isEqualTo(PathFragment.create("pkg/a.out"));
Action action = getGeneratingAction(outputArtifact);
- assertSame(FailAction.class, action.getClass());
+ assertThat(action.getClass()).isSameAs(FailAction.class);
}
@Test
@@ -218,8 +213,8 @@ public class BuildViewTest extends BuildViewTestBase {
assertThat(result.hasError()).isTrue();
assertThat(recorder.events).hasSize(1);
AnalysisFailureEvent event = recorder.events.get(0);
- assertEquals("//foo:bar", event.getFailureReason().toString());
- assertEquals("//foo:foo", event.getFailedTarget().getLabel().toString());
+ assertThat(event.getFailureReason().toString()).isEqualTo("//foo:bar");
+ assertThat(event.getFailedTarget().getLabel().toString()).isEqualTo("//foo:foo");
}
@Test
@@ -274,9 +269,13 @@ public class BuildViewTest extends BuildViewTestBase {
"//third_party/first", "//third_party/third");
assertThat(result.hasError()).isTrue();
assertThat(recorder.events).hasSize(2);
- assertTrue(recorder.events.toString(), recorder.events.contains(
- Pair.of(Label.parseAbsolute("//third_party/first"),
- Label.parseAbsolute("//third_party/fourth"))));
+ assertWithMessage(recorder.events.toString())
+ .that(
+ recorder.events.contains(
+ Pair.of(
+ Label.parseAbsolute("//third_party/first"),
+ Label.parseAbsolute("//third_party/fourth"))))
+ .isTrue();
assertThat(recorder.events)
.contains(Pair.of(
Label.parseAbsolute("//third_party/third"),
@@ -298,9 +297,11 @@ public class BuildViewTest extends BuildViewTestBase {
AnalysisResult result = update(eventBus, defaultFlags().with(Flag.KEEP_GOING), "//gp");
assertThat(result.hasError()).isTrue();
assertThat(recorder.events).hasSize(2);
- assertTrue(recorder.events.toString(), recorder.events.contains(
- Pair.of(Label.parseAbsolute("//gp"),
- Label.parseAbsolute("//c1:not"))));
+ assertWithMessage(recorder.events.toString())
+ .that(
+ recorder.events.contains(
+ Pair.of(Label.parseAbsolute("//gp"), Label.parseAbsolute("//c1:not"))))
+ .isTrue();
assertThat(recorder.events)
.contains(Pair.of(Label.parseAbsolute("//gp"), Label.parseAbsolute("//c2:not")));
}
@@ -318,7 +319,7 @@ public class BuildViewTest extends BuildViewTestBase {
update("//tropical:guava");
// Check if the included package group also got analyzed
- assertNotNull(getConfiguredTarget("//tropical:mango", null));
+ assertThat(getConfiguredTarget("//tropical:mango", null)).isNotNull();
}
@Test
@@ -326,7 +327,7 @@ public class BuildViewTest extends BuildViewTestBase {
scratch.file("tropical/BUILD",
"exports_files(['file.txt'])");
update("//tropical:file.txt");
- assertNotNull(getConfiguredTarget("//tropical:file.txt", null));
+ assertThat(getConfiguredTarget("//tropical:file.txt", null)).isNotNull();
}
@Test
@@ -585,14 +586,15 @@ public class BuildViewTest extends BuildViewTestBase {
getConfiguredTarget("//pkg:a.out");
Artifact outputArtifact = outputCT.getArtifact();
Action action = getGeneratingAction(outputArtifact);
- assertNotNull(action);
+ assertThat(action).isNotNull();
scratch.overwriteFile("pkg/BUILD",
"genrule(name='a', ",
" cmd='false',",
" outs=['a.out'])");
update("//pkg:a.out");
- assertFalse("Actions should not be compatible",
- Actions.canBeShared(action, getGeneratingAction(outputArtifact)));
+ assertWithMessage("Actions should not be compatible")
+ .that(Actions.canBeShared(action, getGeneratingAction(outputArtifact)))
+ .isFalse();
}
/**
@@ -623,8 +625,7 @@ public class BuildViewTest extends BuildViewTestBase {
scratch.deleteFile("java/a/C.java");
update("//java/a:B");
update("//java/a:A");
- assertNotNull(getGeneratingAction(
- getBinArtifact("A_deploy.jar", ct)));
+ assertThat(getGeneratingAction(getBinArtifact("A_deploy.jar", ct))).isNotNull();
}
/**
@@ -646,10 +647,10 @@ public class BuildViewTest extends BuildViewTestBase {
"sh_library(name = 'bad-target')",
"invalidbuildsyntax");
update(defaultFlags().with(Flag.KEEP_GOING), "//parent:foo");
- assertEquals(1, getFrequencyOfErrorsWithLocation(
- badpkg1BuildFile.asFragment(), eventCollector));
- assertEquals(1, getFrequencyOfErrorsWithLocation(
- badpkg2BuildFile.asFragment(), eventCollector));
+ assertThat(getFrequencyOfErrorsWithLocation(badpkg1BuildFile.asFragment(), eventCollector))
+ .isEqualTo(1);
+ assertThat(getFrequencyOfErrorsWithLocation(badpkg2BuildFile.asFragment(), eventCollector))
+ .isEqualTo(1);
}
@Test
@@ -705,12 +706,12 @@ public class BuildViewTest extends BuildViewTestBase {
// However, a ConfiguredTarget was actually produced.
ConfiguredTarget target = Iterables.getOnlyElement(getAnalysisResult().getTargetsToBuild());
- assertEquals(aoutLabel, target.getLabel().toString());
+ assertThat(target.getLabel().toString()).isEqualTo(aoutLabel);
Artifact aout = Iterables.getOnlyElement(
target.getProvider(FileProvider.class).getFilesToBuild());
Action action = getGeneratingAction(aout);
- assertSame(FailAction.class, action.getClass());
+ assertThat(action.getClass()).isSameAs(FailAction.class);
}
/**
@@ -727,7 +728,7 @@ public class BuildViewTest extends BuildViewTestBase {
Artifact fooOut = Iterables.getOnlyElement(
getConfiguredTarget("//actions_not_registered:foo")
.getProvider(FileProvider.class).getFilesToBuild());
- assertNotNull(getActionGraph().getGeneratingAction(fooOut));
+ assertThat(getActionGraph().getGeneratingAction(fooOut)).isNotNull();
clearAnalysisResult();
scratch.overwriteFile("actions_not_registered/BUILD",
@@ -739,7 +740,7 @@ public class BuildViewTest extends BuildViewTestBase {
update("//actions_not_registered:foo");
fail("This build should fail because: 'linkshared' used in non-shared library");
} catch (ViewCreationFailedException e) {
- assertNull(getActionGraph().getGeneratingAction(fooOut));
+ assertThat(getActionGraph().getGeneratingAction(fooOut)).isNull();
}
}
@@ -772,12 +773,12 @@ public class BuildViewTest extends BuildViewTestBase {
// However, a ConfiguredTarget was actually produced.
ConfiguredTarget target = Iterables.getOnlyElement(getAnalysisResult().getTargetsToBuild());
- assertEquals(aoutLabel, target.getLabel().toString());
+ assertThat(target.getLabel().toString()).isEqualTo(aoutLabel);
Artifact aout = Iterables.getOnlyElement(
target.getProvider(FileProvider.class).getFilesToBuild());
Action action = getGeneratingAction(aout);
- assertSame(FailAction.class, action.getClass());
+ assertThat(action.getClass()).isSameAs(FailAction.class);
}
/**
@@ -809,10 +810,16 @@ public class BuildViewTest extends BuildViewTestBase {
AnalysisResult result = update(eventBus, defaultFlags().with(Flag.KEEP_GOING), "//gp");
assertThat(result.hasError()).isTrue();
assertThat(recorder.events).hasSize(2);
- assertTrue(recorder.events.toString(), recorder.events.contains(
- Pair.of(Label.parseAbsolute("//gp"), Label.parseAbsolute("//cycles1"))));
- assertTrue(recorder.events.toString(), recorder.events.contains(
- Pair.of(Label.parseAbsolute("//gp"), Label.parseAbsolute("//cycles2"))));
+ assertWithMessage(recorder.events.toString())
+ .that(
+ recorder.events.contains(
+ Pair.of(Label.parseAbsolute("//gp"), Label.parseAbsolute("//cycles1"))))
+ .isTrue();
+ assertWithMessage(recorder.events.toString())
+ .that(
+ recorder.events.contains(
+ Pair.of(Label.parseAbsolute("//gp"), Label.parseAbsolute("//cycles2"))))
+ .isTrue();
}
/**
@@ -895,7 +902,8 @@ public class BuildViewTest extends BuildViewTestBase {
update("//foo:query", "//foo:zquery");
fail();
} catch (ViewCreationFailedException e) {
- Truth.assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.contains("Analysis of target '//foo:query' failed; build aborted");
}
TrackingAwaiter.INSTANCE.assertNoErrors();
@@ -948,7 +956,8 @@ public class BuildViewTest extends BuildViewTestBase {
update("//foo:java", "//foo:cpp");
fail();
} catch (ViewCreationFailedException expected) {
- Truth.assertThat(expected.getMessage())
+ assertThat(expected)
+ .hasMessageThat()
.matches("Analysis of target '//foo:(java|cpp)' failed; build aborted.*");
}
assertContainsEvent("cycle in dependency graph");
@@ -965,7 +974,8 @@ public class BuildViewTest extends BuildViewTestBase {
update("//foo:test");
fail();
} catch (ViewCreationFailedException expected) {
- Truth.assertThat(expected.getMessage())
+ assertThat(expected)
+ .hasMessageThat()
.matches("Analysis of target '//foo:test' failed; build aborted.*");
}
}
@@ -985,7 +995,8 @@ public class BuildViewTest extends BuildViewTestBase {
fail();
} catch (ViewCreationFailedException expected) {
assertContainsEvent("in cc_library rule //cycle:foo: cycle in dependency graph:");
- assertThat(expected.getMessage())
+ assertThat(expected)
+ .hasMessageThat()
.contains("Analysis of target '//cycle:foo' failed; build aborted");
}
}
@@ -1069,7 +1080,7 @@ public class BuildViewTest extends BuildViewTestBase {
update(defaultFlags().with(Flag.KEEP_GOING));
fail();
} catch (InvalidConfigurationException e) {
- assertThat(e.getMessage()).contains("third_party/crosstool/v2");
+ assertThat(e).hasMessageThat().contains("third_party/crosstool/v2");
}
}
@@ -1118,7 +1129,7 @@ public class BuildViewTest extends BuildViewTestBase {
update(defaultFlags().with(Flag.KEEP_GOING));
fail();
} catch (InvalidConfigurationException e) {
- assertThat(e.getMessage()).contains("//xcode:does_not_exist");
+ assertThat(e).hasMessageThat().contains("//xcode:does_not_exist");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/CircularDependencyTest.java b/src/test/java/com/google/devtools/build/lib/analysis/CircularDependencyTest.java
index 19e775e0f2..270ccb19f5 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/CircularDependencyTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/CircularDependencyTest.java
@@ -14,10 +14,7 @@
package com.google.devtools.build.lib.analysis;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
@@ -86,10 +83,10 @@ public class CircularDependencyTest extends BuildViewTestCase {
}
}
- assertNotNull(foundEvent);
+ assertThat(foundEvent).isNotNull();
Location location = foundEvent.getLocation();
- assertEquals(3, location.getStartLineAndColumn().getLine());
- assertEquals("/workspace/cycle/BUILD", location.getPath().toString());
+ assertThat(location.getStartLineAndColumn().getLine()).isEqualTo(3);
+ assertThat(location.getPath().toString()).isEqualTo("/workspace/cycle/BUILD");
}
/**
@@ -106,7 +103,7 @@ public class CircularDependencyTest extends BuildViewTestCase {
} catch (NoSuchTargetException e) {
/* ok */
}
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
assertContainsEvent("rule 'jcyc' has file 'libjcyc.jar' as both an" + " input and an output");
}
@@ -123,7 +120,7 @@ public class CircularDependencyTest extends BuildViewTestCase {
" srcs = ['//googledata/geo:geo_info.txt'],",
" outs = ['geoinfo.txt'],",
" cmd = '$(SRCS) > $@')");
- assertFalse(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/CompilationHelperTest.java b/src/test/java/com/google/devtools/build/lib/analysis/CompilationHelperTest.java
index 9ee48ad8a1..8610523c94 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/CompilationHelperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/CompilationHelperTest.java
@@ -15,9 +15,6 @@
package com.google.devtools.build.lib.analysis;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.fail;
import com.google.common.collect.Iterables;
@@ -28,18 +25,14 @@ import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.util.AnalysisTestUtil;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.rules.cpp.CppHelper;
-
+import java.io.IOException;
+import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.IOException;
-import java.util.List;
-
-/**
- * Unit tests for the {@link CompilationHelper} class.
- */
+/** Unit tests for the {@link CompilationHelper} class. */
@RunWith(JUnit4.class)
public class CompilationHelperTest extends BuildViewTestCase {
private AnalysisTestUtil.CollectingAnalysisEnvironment analysisEnvironment;
@@ -79,7 +72,7 @@ public class CompilationHelperTest extends BuildViewTestCase {
assertThat(middleman1).hasSize(1);
List<Artifact> middleman2 = getAggregatingMiddleman(rule, false);
assertThat(middleman2).hasSize(1);
- assertEquals(middleman1.get(0), middleman2.get(0));
+ assertThat(middleman2.get(0)).isEqualTo(middleman1.get(0));
}
/**
@@ -97,7 +90,7 @@ public class CompilationHelperTest extends BuildViewTestCase {
assertThat(middleman).hasSize(1);
List<Artifact> middlemanWithSymlinks = getAggregatingMiddleman(rule, true);
assertThat(middlemanWithSymlinks).hasSize(1);
- assertNotSame(middleman.get(0), middlemanWithSymlinks.get(0));
+ assertThat(middlemanWithSymlinks.get(0)).isNotSameAs(middleman.get(0));
}
/**
@@ -131,9 +124,8 @@ public class CompilationHelperTest extends BuildViewTestCase {
List<Artifact> middleman2 = getAggregatingMiddleman(pyRuleB, true);
- assertEquals(
- Iterables.getOnlyElement(middleman1).getExecPathString(),
- Iterables.getOnlyElement(middleman2).getExecPathString());
+ assertThat(Iterables.getOnlyElement(middleman2).getExecPathString())
+ .isEqualTo(Iterables.getOnlyElement(middleman1).getExecPathString());
}
/**
@@ -164,10 +156,11 @@ public class CompilationHelperTest extends BuildViewTestCase {
ConfiguredTarget javaRuleB = getDirectPrerequisite(
getConfiguredTarget("//foo:d"), "//foo:libb.so");
List<Artifact> middleman2 = getAggregatingMiddleman(javaRuleB, false);
- assertFalse(
- Iterables.getOnlyElement(middleman1)
- .getExecPathString()
- .equals(Iterables.getOnlyElement(middleman2).getExecPathString()));
+ assertThat(
+ Iterables.getOnlyElement(middleman1)
+ .getExecPathString()
+ .equals(Iterables.getOnlyElement(middleman2).getExecPathString()))
+ .isFalse();
}
private void setupJavaPythonCcConfigurationFiles() throws IOException {
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/ConfigurationsForLateBoundTargetsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/ConfigurationsForLateBoundTargetsTest.java
index 9cf51a0895..f3e8a1d7c0 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/ConfigurationsForLateBoundTargetsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/ConfigurationsForLateBoundTargetsTest.java
@@ -17,7 +17,6 @@ package com.google.devtools.build.lib.analysis;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
-import static org.junit.Assert.assertNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
@@ -36,7 +35,6 @@ import com.google.devtools.build.lib.testutil.Suite;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.testutil.TestSpec;
import com.google.devtools.build.lib.testutil.UnknownRuleConfiguredTarget;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -126,7 +124,7 @@ public class ConfigurationsForLateBoundTargetsTest extends AnalysisTestCase {
"rule_with_test_fragment(",
" name = 'latebound_dep')");
update("//foo:foo");
- assertNotNull(getConfiguredTarget("//foo:foo", getTargetConfiguration()));
+ assertThat(getConfiguredTarget("//foo:foo", getTargetConfiguration())).isNotNull();
ConfiguredTarget dep = Iterables.getOnlyElement(
SkyframeExecutorTestUtils.getExistingConfiguredTargets(
skyframeExecutor, Label.parseAbsolute("//foo:latebound_dep")));
@@ -148,7 +146,7 @@ public class ConfigurationsForLateBoundTargetsTest extends AnalysisTestCase {
"rule_with_test_fragment(",
" name = 'latebound_dep')");
update("//foo:gen");
- assertNotNull(getConfiguredTarget("//foo:foo", getHostConfiguration()));
+ assertThat(getConfiguredTarget("//foo:foo", getHostConfiguration())).isNotNull();
ConfiguredTarget dep = Iterables.getOnlyElement(
SkyframeExecutorTestUtils.getExistingConfiguredTargets(
skyframeExecutor, Label.parseAbsolute("//foo:latebound_dep")));
@@ -166,7 +164,7 @@ public class ConfigurationsForLateBoundTargetsTest extends AnalysisTestCase {
"rule_with_test_fragment(",
" name = 'latebound_dep')");
update("//foo:foo");
- assertNotNull(getConfiguredTarget("//foo:foo"));
+ assertThat(getConfiguredTarget("//foo:foo")).isNotNull();
Iterable<ConfiguredTarget> deps = SkyframeExecutorTestUtils.getExistingConfiguredTargets(
skyframeExecutor, Label.parseAbsolute("//foo:latebound_dep"));
assertThat(deps).hasSize(2);
@@ -191,7 +189,7 @@ public class ConfigurationsForLateBoundTargetsTest extends AnalysisTestCase {
"rule_with_test_fragment(",
" name = 'latebound_dep')");
update("//foo:gen");
- assertNotNull(getConfiguredTarget("//foo:foo", getHostConfiguration()));
+ assertThat(getConfiguredTarget("//foo:foo", getHostConfiguration())).isNotNull();
ConfiguredTarget dep = Iterables.getOnlyElement(
SkyframeExecutorTestUtils.getExistingConfiguredTargets(
skyframeExecutor, Label.parseAbsolute("//foo:latebound_dep")));
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/ConfiguredAttributeMapperTest.java b/src/test/java/com/google/devtools/build/lib/analysis/ConfiguredAttributeMapperTest.java
index 8f97a49d77..bff9d57b0e 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/ConfiguredAttributeMapperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/ConfiguredAttributeMapperTest.java
@@ -14,9 +14,7 @@
package com.google.devtools.build.lib.analysis;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.config.CompilationMode;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.cmdline.Label;
@@ -24,14 +22,12 @@ import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.syntax.Type;
-
+import java.util.ArrayList;
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* Unit tests for {@link ConfiguredAttributeMapper}.
*
@@ -81,13 +77,13 @@ public class ConfiguredAttributeMapperTest extends BuildViewTestCase {
" }))");
useConfiguration("--define", "mode=a");
- assertEquals("a command", getMapper("//a:gen").get("cmd", Type.STRING));
+ assertThat(getMapper("//a:gen").get("cmd", Type.STRING)).isEqualTo("a command");
useConfiguration("--define", "mode=b");
- assertEquals("b command", getMapper("//a:gen").get("cmd", Type.STRING));
+ assertThat(getMapper("//a:gen").get("cmd", Type.STRING)).isEqualTo("b command");
useConfiguration("--define", "mode=c");
- assertEquals("default command", getMapper("//a:gen").get("cmd", Type.STRING));
+ assertThat(getMapper("//a:gen").get("cmd", Type.STRING)).isEqualTo("default command");
}
/**
@@ -130,20 +126,17 @@ public class ConfiguredAttributeMapperTest extends BuildViewTestCase {
useConfiguration("--define", "mode=a");
getMapper("//a:bin").visitLabels(testVisitor);
- assertThat(visitedLabels)
- .containsExactlyElementsIn(ImmutableList.of(binSrc, Label.parseAbsolute("//a:adep")));
+ assertThat(visitedLabels).containsExactly(binSrc, Label.parseAbsolute("//a:adep"));
visitedLabels.clear();
useConfiguration("--define", "mode=b");
getMapper("//a:bin").visitLabels(testVisitor);
- assertThat(visitedLabels)
- .containsExactlyElementsIn(ImmutableList.of(binSrc, Label.parseAbsolute("//a:bdep")));
+ assertThat(visitedLabels).containsExactly(binSrc, Label.parseAbsolute("//a:bdep"));
visitedLabels.clear();
useConfiguration("--define", "mode=c");
getMapper("//a:bin").visitLabels(testVisitor);
- assertThat(visitedLabels)
- .containsExactlyElementsIn(ImmutableList.of(binSrc, Label.parseAbsolute("//a:defaultdep")));
+ assertThat(visitedLabels).containsExactly(binSrc, Label.parseAbsolute("//a:defaultdep"));
}
/**
@@ -177,13 +170,17 @@ public class ConfiguredAttributeMapperTest extends BuildViewTestCase {
// Target configuration is in dbg mode, so we should match //conditions:b:
assertThat(getMapper("//a:gen").get("tools", BuildType.LABEL_LIST))
- .containsExactlyElementsIn(ImmutableList.of(Label.parseAbsolute("//a:bdep")));
+ .containsExactly(Label.parseAbsolute("//a:bdep"));
// Verify the "tools" dep uses a different configuration that's not also in "dbg":
- assertEquals(Attribute.ConfigurationTransition.HOST,
- getTarget("//a:gen").getAssociatedRule().getRuleClassObject()
- .getAttributeByName("tools").getConfigurationTransition());
- assertEquals(CompilationMode.OPT, getHostConfiguration().getCompilationMode());
+ assertThat(
+ getTarget("//a:gen")
+ .getAssociatedRule()
+ .getRuleClassObject()
+ .getAttributeByName("tools")
+ .getConfigurationTransition())
+ .isEqualTo(Attribute.ConfigurationTransition.HOST);
+ assertThat(getHostConfiguration().getCompilationMode()).isEqualTo(CompilationMode.OPT);
}
@Test
@@ -202,9 +199,7 @@ public class ConfiguredAttributeMapperTest extends BuildViewTestCase {
")");
useConfiguration("--define", "foo=a", "--define", "bar=d");
assertThat(getMapper("//hello:gen").get("srcs", BuildType.LABEL_LIST))
- .containsExactlyElementsIn(
- ImmutableList.of(
- Label.parseAbsolute("//hello:a.in"), Label.parseAbsolute("//hello:d.in")));
+ .containsExactly(Label.parseAbsolute("//hello:a.in"), Label.parseAbsolute("//hello:d.in"));
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/DependencyResolverTest.java b/src/test/java/com/google/devtools/build/lib/analysis/DependencyResolverTest.java
index a4d7cb4edf..d137a839df 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/DependencyResolverTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/DependencyResolverTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.analysis;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertNotNull;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
@@ -126,7 +126,7 @@ public class DependencyResolverTest extends AnalysisTestCase {
}
}
- assertNotNull("Attribute '" + attrName + "' not found", attr);
+ assertWithMessage("Attribute '" + attrName + "' not found").that(attr).isNotNull();
Dependency dependency = null;
for (Dependency candidate : dependentNodeMap.get(attr)) {
if (candidate.getLabel().toString().equals(dep)) {
@@ -135,7 +135,9 @@ public class DependencyResolverTest extends AnalysisTestCase {
}
}
- assertNotNull("Dependency '" + dep + "' on attribute '" + attrName + "' not found", dependency);
+ assertWithMessage("Dependency '" + dep + "' on attribute '" + attrName + "' not found")
+ .that(dependency)
+ .isNotNull();
assertThat(dependency.getAspects().getAllAspects()).containsExactly((Object[]) aspects);
return dependency;
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/DependencyTest.java b/src/test/java/com/google/devtools/build/lib/analysis/DependencyTest.java
index 03369f7e8c..4de388c23f 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/DependencyTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/DependencyTest.java
@@ -145,7 +145,7 @@ public class DependencyTest extends AnalysisTestCase {
assertThat(targetDep.hasStaticConfiguration()).isTrue();
assertThat(targetDep.getConfiguration()).isEqualTo(getTargetConfiguration());
assertThat(targetDep.getAspects().getAllAspects())
- .containsExactlyElementsIn(ImmutableSet.of(simpleAspect, attributeAspect));
+ .containsExactly(simpleAspect, attributeAspect);
assertThat(targetDep.getAspectConfiguration(simpleAspect)).isEqualTo(getTargetConfiguration());
assertThat(targetDep.getAspectConfiguration(attributeAspect))
.isEqualTo(getHostConfiguration());
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/DuplicateActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/DuplicateActionTest.java
index 655b86f674..257edfb9f0 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/DuplicateActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/DuplicateActionTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.analysis;
-import static org.junit.Assert.assertFalse;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.analysis.util.AnalysisTestCase;
import org.junit.Test;
@@ -37,7 +37,7 @@ public class DuplicateActionTest extends AnalysisTestCase {
"cc_binary(name = 'b', srcs = ['b.cc'], deps = [':c'], stamp = 1)",
"cc_library(name = 'c', linkstamp = 'stamp.cc')");
update("//a:a", "//a:b");
- assertFalse(hasErrors(getConfiguredTarget("//a:a")));
- assertFalse(hasErrors(getConfiguredTarget("//a:b")));
+ assertThat(hasErrors(getConfiguredTarget("//a:a"))).isFalse();
+ assertThat(hasErrors(getConfiguredTarget("//a:b"))).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LabelExpanderTest.java b/src/test/java/com/google/devtools/build/lib/analysis/LabelExpanderTest.java
index bda0f7a156..0ae750d72d 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LabelExpanderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LabelExpanderTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -25,16 +25,12 @@ import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.testutil.Suite;
import com.google.devtools.build.lib.testutil.TestSpec;
import com.google.devtools.build.lib.vfs.PathFragment;
-
+import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Map;
-
-/**
- * Tests for {@link LabelExpander}.
- */
+/** Tests for {@link LabelExpander}. */
@TestSpec(size = Suite.SMALL_TESTS)
@RunWith(JUnit4.class)
public class LabelExpanderTest extends BuildViewTestCase {
@@ -106,8 +102,8 @@ public class LabelExpanderTest extends BuildViewTestCase {
*/
private void assertExpansion(String expectedResult, String expressionToExpand,
Map<Label, Iterable<Artifact>> mapping) throws Exception {
- assertEquals(expectedResult,
- LabelExpander.expand(expressionToExpand, mapping, dummyTarget.getLabel()));
+ assertThat(LabelExpander.expand(expressionToExpand, mapping, dummyTarget.getLabel()))
+ .isEqualTo(expectedResult);
}
/**
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/LicensingTests.java b/src/test/java/com/google/devtools/build/lib/analysis/LicensingTests.java
index 679b6dd6bc..7553068c36 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/LicensingTests.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/LicensingTests.java
@@ -13,11 +13,8 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis;
-
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
@@ -137,7 +134,7 @@ public class LicensingTests extends BuildViewTestCase {
ConfiguredTarget target = getConfiguredTarget("//a:a");
License license = getTarget(target.getLabel()).getLicense();
- assertEquals(License.parseLicense(Arrays.asList("restricted", "reciprocal")), license);
+ assertThat(license).isEqualTo(License.parseLicense(Arrays.asList("restricted", "reciprocal")));
}
@Test
@@ -197,7 +194,7 @@ public class LicensingTests extends BuildViewTestCase {
kablamMap);
License cLicense = getTarget(cTarget.getLabel()).getLicense();
- assertEquals(License.parseLicense(Arrays.asList("restricted", "reciprocal")), cLicense);
+ assertThat(cLicense).isEqualTo(License.parseLicense(Arrays.asList("restricted", "reciprocal")));
}
@Test
@@ -213,11 +210,10 @@ public class LicensingTests extends BuildViewTestCase {
License aLicense = getTarget(aTarget.getLabel()).getLicense();
License bLicense = getTarget(bTarget.getLabel()).getLicense();
License cLicense = getTarget(cTarget.getLabel()).getLicense();
- assertFalse(aLicense.equals(bLicense));
- assertEquals(License.parseLicense(Arrays.asList("unencumbered")), aLicense);
- assertEquals(License.parseLicense(Arrays.asList("restricted", "reciprocal")),
- bLicense);
- assertEquals(License.parseLicense(Arrays.asList("unencumbered")), cLicense);
+ assertThat(aLicense.equals(bLicense)).isFalse();
+ assertThat(aLicense).isEqualTo(License.parseLicense(Arrays.asList("unencumbered")));
+ assertThat(bLicense).isEqualTo(License.parseLicense(Arrays.asList("restricted", "reciprocal")));
+ assertThat(cLicense).isEqualTo(License.parseLicense(Arrays.asList("unencumbered")));
}
@Test
@@ -485,9 +481,10 @@ public class LicensingTests extends BuildViewTestCase {
"reciprocal", "exception=//a:a"));
License l3 = License.parseLicense(Arrays.asList("by_exception_only",
"reciprocal", "exception=//a:a", "exception=//b:b"));
- assertEquals("[restricted] with exceptions [//a:a]", l1.toString());
- assertEquals("[restricted, reciprocal] with exceptions [//a:a]", l2.toString());
- assertEquals("[by_exception_only, reciprocal] with exceptions [//a:a, //b:b]", l3.toString());
+ assertThat(l1.toString()).isEqualTo("[restricted] with exceptions [//a:a]");
+ assertThat(l2.toString()).isEqualTo("[restricted, reciprocal] with exceptions [//a:a]");
+ assertThat(l3.toString())
+ .isEqualTo("[by_exception_only, reciprocal] with exceptions [//a:a, //b:b]");
}
/**
@@ -526,7 +523,9 @@ public class LicensingTests extends BuildViewTestCase {
V expectedValue = expected.get(key);
V actualValue = actual.get(key);
assertWithMessage("Key '%s'", key).that(actualValue).isNotNull();
- assertEquals("Values for key '" + key + "' should match", expectedValue, actualValue);
+ assertWithMessage("Values for key '" + key + "' should match")
+ .that(actualValue)
+ .isEqualTo(expectedValue);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/MakeVariableExpanderTest.java b/src/test/java/com/google/devtools/build/lib/analysis/MakeVariableExpanderTest.java
index d5eb5412ca..33ae8a990e 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/MakeVariableExpanderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/MakeVariableExpanderTest.java
@@ -14,17 +14,15 @@
package com.google.devtools.build.lib.analysis;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import java.util.HashMap;
+import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.HashMap;
-import java.util.Map;
-
/**
* Unit tests for the {@link MakeVariableExpander}, which expands variable references of the form
* <code>"$x"</code> and <code>"$(foo)"</code> into their corresponding values.
@@ -58,7 +56,7 @@ public class MakeVariableExpanderTest {
private void assertExpansionEquals(String expected, String cmd)
throws MakeVariableExpander.ExpansionException {
- assertEquals(expected, MakeVariableExpander.expand(cmd, context));
+ assertThat(MakeVariableExpander.expand(cmd, context)).isEqualTo(expected);
}
private void assertExpansionFails(String expectedErrorSuffix, String cmd) {
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/RunfilesTest.java b/src/test/java/com/google/devtools/build/lib/analysis/RunfilesTest.java
index 41f543642b..aff8e5c0ff 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/RunfilesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/RunfilesTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.analysis;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
@@ -25,11 +25,9 @@ import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -42,9 +40,10 @@ public class RunfilesTest extends FoundationTestCase {
private void checkWarning() {
assertContainsEvent("obscured by a -> /workspace/a");
- assertEquals("Runfiles.filterListForObscuringSymlinks should have warned once",
- 1, eventCollector.count());
- assertEquals(EventKind.WARNING, Iterables.getOnlyElement(eventCollector).getKind());
+ assertWithMessage("Runfiles.filterListForObscuringSymlinks should have warned once")
+ .that(eventCollector.count())
+ .isEqualTo(1);
+ assertThat(Iterables.getOnlyElement(eventCollector).getKind()).isEqualTo(EventKind.WARNING);
}
@Test
@@ -126,14 +125,18 @@ public class RunfilesTest extends FoundationTestCase {
private void checkConflictWarning() {
assertContainsEvent("overwrote runfile");
- assertEquals("ConflictChecker.put should have warned once", 1, eventCollector.count());
- assertEquals(EventKind.WARNING, Iterables.getOnlyElement(eventCollector).getKind());
+ assertWithMessage("ConflictChecker.put should have warned once")
+ .that(eventCollector.count())
+ .isEqualTo(1);
+ assertThat(Iterables.getOnlyElement(eventCollector).getKind()).isEqualTo(EventKind.WARNING);
}
private void checkConflictError() {
assertContainsEvent("overwrote runfile");
- assertEquals("ConflictChecker.put should have errored once", 1, eventCollector.count());
- assertEquals(EventKind.ERROR, Iterables.getOnlyElement(eventCollector).getKind());
+ assertWithMessage("ConflictChecker.put should have errored once")
+ .that(eventCollector.count())
+ .isEqualTo(1);
+ assertThat(Iterables.getOnlyElement(eventCollector).getKind()).isEqualTo(EventKind.ERROR);
}
@Test
@@ -240,7 +243,7 @@ public class RunfilesTest extends FoundationTestCase {
PathFragment pathA = PathFragment.create("a");
Artifact artifactB = new Artifact(PathFragment.create("b"), root);
Artifact artifactB2 = new Artifact(PathFragment.create("b"), root);
- assertEquals(artifactB, artifactB2);
+ assertThat(artifactB2).isEqualTo(artifactB);
Map<PathFragment, Artifact> map = new LinkedHashMap<>();
Runfiles.ConflictChecker checker =
@@ -295,7 +298,7 @@ public class RunfilesTest extends FoundationTestCase {
public void testBuilderMergeConflictPolicyDefault() {
Runfiles r1 = new Runfiles.Builder("TESTING").build();
Runfiles r2 = new Runfiles.Builder("TESTING").merge(r1).build();
- assertEquals(Runfiles.ConflictPolicy.IGNORE, r2.getConflictPolicy());
+ assertThat(r2.getConflictPolicy()).isEqualTo(Runfiles.ConflictPolicy.IGNORE);
}
@Test
@@ -303,7 +306,7 @@ public class RunfilesTest extends FoundationTestCase {
Runfiles r1 = new Runfiles.Builder("TESTING").build()
.setConflictPolicy(Runfiles.ConflictPolicy.WARN);
Runfiles r2 = new Runfiles.Builder("TESTING").merge(r1).build();
- assertEquals(Runfiles.ConflictPolicy.WARN, r2.getConflictPolicy());
+ assertThat(r2.getConflictPolicy()).isEqualTo(Runfiles.ConflictPolicy.WARN);
}
@Test
@@ -313,10 +316,10 @@ public class RunfilesTest extends FoundationTestCase {
Runfiles r2 = new Runfiles.Builder("TESTING").build()
.setConflictPolicy(Runfiles.ConflictPolicy.ERROR);
Runfiles r3 = new Runfiles.Builder("TESTING").merge(r1).merge(r2).build();
- assertEquals(Runfiles.ConflictPolicy.ERROR, r3.getConflictPolicy());
+ assertThat(r3.getConflictPolicy()).isEqualTo(Runfiles.ConflictPolicy.ERROR);
// Swap ordering
Runfiles r4 = new Runfiles.Builder("TESTING").merge(r2).merge(r1).build();
- assertEquals(Runfiles.ConflictPolicy.ERROR, r4.getConflictPolicy());
+ assertThat(r4.getConflictPolicy()).isEqualTo(Runfiles.ConflictPolicy.ERROR);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/TopLevelArtifactHelperTest.java b/src/test/java/com/google/devtools/build/lib/analysis/TopLevelArtifactHelperTest.java
index 6403ecbe43..5a9e9e23df 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/TopLevelArtifactHelperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/TopLevelArtifactHelperTest.java
@@ -14,12 +14,11 @@
package com.google.devtools.build.lib.analysis;
-import static com.google.common.collect.Iterables.size;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.analysis.OutputGroupProvider.HIDDEN_OUTPUT_GROUP_PREFIX;
import static com.google.devtools.build.lib.analysis.TopLevelArtifactHelper.getAllArtifactsToBuild;
import static com.google.devtools.build.lib.util.Preconditions.checkNotNull;
import static java.util.Arrays.asList;
-import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
@@ -73,20 +72,20 @@ public class TopLevelArtifactHelperTest {
setup(asList(Pair.of("foo", 3), Pair.of("bar", 2)));
ArtifactsToBuild allArtifacts = getAllArtifactsToBuild(groupProvider, null, ctx);
- assertEquals(5, size(allArtifacts.getAllArtifacts()));
- assertEquals(5, size(allArtifacts.getImportantArtifacts()));
+ assertThat(allArtifacts.getAllArtifacts()).hasSize(5);
+ assertThat(allArtifacts.getImportantArtifacts()).hasSize(5);
NestedSet<ArtifactsInOutputGroup> artifactsByGroup =
allArtifacts.getAllArtifactsByOutputGroup();
// Two groups
- assertEquals(2, size(artifactsByGroup));
+ assertThat(artifactsByGroup).hasSize(2);
for (ArtifactsInOutputGroup artifacts : artifactsByGroup) {
String outputGroup = artifacts.getOutputGroup();
if ("foo".equals(outputGroup)) {
- assertEquals(3, size(artifacts.getArtifacts()));
+ assertThat(artifacts.getArtifacts()).hasSize(3);
} else if ("bar".equals(outputGroup)) {
- assertEquals(2, size(artifacts.getArtifacts()));
+ assertThat(artifacts.getArtifacts()).hasSize(2);
}
}
}
@@ -96,14 +95,14 @@ public class TopLevelArtifactHelperTest {
setup(asList(Pair.of("foo", 1), Pair.of("bar", 0)));
ArtifactsToBuild allArtifacts = getAllArtifactsToBuild(groupProvider, null, ctx);
- assertEquals(1, size(allArtifacts.getAllArtifacts()));
- assertEquals(1, size(allArtifacts.getImportantArtifacts()));
+ assertThat(allArtifacts.getAllArtifacts()).hasSize(1);
+ assertThat(allArtifacts.getImportantArtifacts()).hasSize(1);
NestedSet<ArtifactsInOutputGroup> artifactsByGroup =
allArtifacts.getAllArtifactsByOutputGroup();
// The bar list should not appear here, as it contains no artifacts.
- assertEquals(1, size(artifactsByGroup));
- assertEquals("foo", artifactsByGroup.toList().get(0).getOutputGroup());
+ assertThat(artifactsByGroup).hasSize(1);
+ assertThat(artifactsByGroup.toList().get(0).getOutputGroup()).isEqualTo("foo");
}
@Test
@@ -111,8 +110,8 @@ public class TopLevelArtifactHelperTest {
setup(asList(Pair.of(HIDDEN_OUTPUT_GROUP_PREFIX + "notimportant", 1), Pair.of("important", 2)));
ArtifactsToBuild allArtifacts = getAllArtifactsToBuild(groupProvider, null, ctx);
- assertEquals(3, size(allArtifacts.getAllArtifacts()));
- assertEquals(2, size(allArtifacts.getImportantArtifacts()));
+ assertThat(allArtifacts.getAllArtifacts()).hasSize(3);
+ assertThat(allArtifacts.getImportantArtifacts()).hasSize(2);
}
private NestedSet<Artifact> newArtifacts(int num) {
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/UtilTest.java b/src/test/java/com/google/devtools/build/lib/analysis/UtilTest.java
index 9024942379..ac34e06781 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/UtilTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/UtilTest.java
@@ -13,11 +13,9 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -30,7 +28,7 @@ public class UtilTest {
@Test
public void testContainsHyphen() throws Exception {
- assertTrue(Util.containsHyphen(PathFragment.create("foo/bar/with-hyphen")));
- assertFalse(Util.containsHyphen(PathFragment.create("foo/bar/no/hyphen")));
+ assertThat(Util.containsHyphen(PathFragment.create("foo/bar/with-hyphen"))).isTrue();
+ assertThat(Util.containsHyphen(PathFragment.create("foo/bar/no/hyphen"))).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/FileWriteActionTestCase.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/FileWriteActionTestCase.java
index 1916b089c9..2eb06f24c3 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/FileWriteActionTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/FileWriteActionTestCase.java
@@ -15,10 +15,6 @@ package com.google.devtools.build.lib.analysis.actions;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@@ -65,20 +61,20 @@ public abstract class FileWriteActionTestCase extends BuildViewTestCase {
protected void checkNoInputsByDefault() {
assertThat(action.getInputs()).isEmpty();
- assertNull(action.getPrimaryInput());
+ assertThat(action.getPrimaryInput()).isNull();
}
protected void checkDestinationArtifactIsOutput() {
Collection<Artifact> outputs = action.getOutputs();
- assertEquals(Sets.newHashSet(outputArtifact), Sets.newHashSet(outputs));
- assertEquals(outputArtifact, action.getPrimaryOutput());
+ assertThat(Sets.newHashSet(outputs)).isEqualTo(Sets.newHashSet(outputArtifact));
+ assertThat(action.getPrimaryOutput()).isEqualTo(outputArtifact);
}
protected void checkCanWriteNonExecutableFile() throws Exception {
action.execute(context);
String content = new String(FileSystemUtils.readContentAsLatin1(output));
- assertEquals("Hello World", content);
- assertFalse(output.isExecutable());
+ assertThat(content).isEqualTo("Hello World");
+ assertThat(output.isExecutable()).isFalse();
}
protected void checkCanWriteExecutableFile() throws Exception {
@@ -87,8 +83,8 @@ public abstract class FileWriteActionTestCase extends BuildViewTestCase {
Action action = createAction(NULL_ACTION_OWNER, outputArtifact, "echo 'Hello World'", true);
action.execute(context);
String content = new String(FileSystemUtils.readContentAsLatin1(output));
- assertEquals("echo 'Hello World'", content);
- assertTrue(output.isExecutable());
+ assertThat(content).isEqualTo("echo 'Hello World'");
+ assertThat(output.isExecutable()).isTrue();
}
private enum KeyAttributes {
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/ParamFileWriteActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/ParamFileWriteActionTest.java
index dbf57aedb8..8711b47a4b 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/ParamFileWriteActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/ParamFileWriteActionTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.analysis.actions;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -83,7 +82,7 @@ public class ParamFileWriteActionTest extends BuildViewTestCase {
ActionExecutionContext context = actionExecutionContext();
action.execute(context);
String content = new String(FileSystemUtils.readContentAsLatin1(outputArtifact.getPath()));
- assertEquals("--flag1\n--flag2\n--flag3\nvalue1\nvalue2", content.trim());
+ assertThat(content.trim()).isEqualTo("--flag1\n--flag2\n--flag3\nvalue1\nvalue2");
}
@Test
@@ -94,11 +93,11 @@ public class ParamFileWriteActionTest extends BuildViewTestCase {
ActionExecutionContext context = actionExecutionContext();
action.execute(context);
String content = new String(FileSystemUtils.readContentAsLatin1(outputArtifact.getPath()));
- assertEquals(
- "--flag1\n"
- + "artifact/myTreeFileArtifact/artifacts/treeFileArtifact1:"
- + "artifact/myTreeFileArtifact/artifacts/treeFileArtifact2",
- content.trim());
+ assertThat(content.trim())
+ .isEqualTo(
+ "--flag1\n"
+ + "artifact/myTreeFileArtifact/artifacts/treeFileArtifact1:"
+ + "artifact/myTreeFileArtifact/artifacts/treeFileArtifact2");
}
private Artifact createTreeArtifact(String rootRelativePath) {
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
index 5b8ba357a0..a39cf858e4 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/SpawnActionTest.java
@@ -17,15 +17,12 @@ import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.util.Arrays.asList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.Action;
@@ -44,7 +41,6 @@ import com.google.devtools.build.lib.analysis.util.AnalysisTestUtil;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.testutil.MoreAsserts;
import com.google.devtools.build.lib.vfs.PathFragment;
-import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
@@ -101,7 +97,7 @@ public class SpawnActionTest extends BuildViewTestCase {
SpawnAction copyFromWelcomeToDestination =
createCopyFromWelcomeToDestination(ImmutableMap.<String, String>of());
Iterable<Artifact> inputs = copyFromWelcomeToDestination.getInputs();
- assertEquals(Sets.newHashSet(welcomeArtifact), Sets.newHashSet(inputs));
+ assertThat(inputs).containsExactly(welcomeArtifact);
}
@Test
@@ -109,7 +105,7 @@ public class SpawnActionTest extends BuildViewTestCase {
SpawnAction copyFromWelcomeToDestination =
createCopyFromWelcomeToDestination(ImmutableMap.<String, String>of());
Collection<Artifact> outputs = copyFromWelcomeToDestination.getOutputs();
- assertEquals(Sets.newHashSet(destinationArtifact), Sets.newHashSet(outputs));
+ assertThat(outputs).containsExactly(destinationArtifact);
}
@Test
@@ -124,13 +120,14 @@ public class SpawnActionTest extends BuildViewTestCase {
.build(ActionsTestUtil.NULL_ACTION_OWNER, collectingAnalysisEnvironment, targetConfig);
collectingAnalysisEnvironment.registerAction(actions);
SpawnAction action = (SpawnAction) actions[0];
- assertEquals(ActionsTestUtil.NULL_ACTION_OWNER.getLabel(),
- action.getOwner().getLabel());
- assertThat(action.getInputs()).containsExactlyElementsIn(asList(input));
- assertThat(action.getOutputs()).containsExactlyElementsIn(asList(output));
- assertEquals(AbstractAction.DEFAULT_RESOURCE_SET, action.getSpawn().getLocalResources());
- assertThat(action.getArguments()).containsExactlyElementsIn(asList("/bin/xxx"));
- assertEquals("Test", action.getProgressMessage());
+ assertThat(action.getOwner().getLabel())
+ .isEqualTo(ActionsTestUtil.NULL_ACTION_OWNER.getLabel());
+ assertThat(action.getInputs()).containsExactly(input);
+ assertThat(action.getOutputs()).containsExactly(output);
+ assertThat(action.getSpawn().getLocalResources())
+ .isEqualTo(AbstractAction.DEFAULT_RESOURCE_SET);
+ assertThat(action.getArguments()).containsExactly("/bin/xxx");
+ assertThat(action.getProgressMessage()).isEqualTo("Test");
}
@Test
@@ -142,7 +139,7 @@ public class SpawnActionTest extends BuildViewTestCase {
collectingAnalysisEnvironment.registerAction(actions);
SpawnAction action = (SpawnAction) actions[0];
assertThat(action.getArguments())
- .containsExactlyElementsIn(asList(welcomeArtifact.getExecPath().getPathString()));
+ .containsExactly(welcomeArtifact.getExecPath().getPathString());
}
@Test
@@ -154,8 +151,10 @@ public class SpawnActionTest extends BuildViewTestCase {
.build(ActionsTestUtil.NULL_ACTION_OWNER, collectingAnalysisEnvironment, targetConfig);
collectingAnalysisEnvironment.registerAction(actions);
SpawnAction action = (SpawnAction) actions[0];
- assertEquals(asList("/bin/java", "-Xverify:none", "-jvmarg", "-cp",
- "pkg/exe.jar", "MyMainClass"), action.getArguments());
+ assertThat(action.getArguments())
+ .containsExactly(
+ "/bin/java", "-Xverify:none", "-jvmarg", "-cp", "pkg/exe.jar", "MyMainClass")
+ .inOrder();
}
@Test
@@ -179,12 +178,18 @@ public class SpawnActionTest extends BuildViewTestCase {
// use STUB_ANALYSIS_ENVIRONMENT here because we also need a BuildConfiguration.
collectingAnalysisEnvironment.registerWith(getMutableActionGraph());
}
- assertEquals(asList("/bin/java", "-Xverify:none", "-jvmarg", "-cp",
- "pkg/exe.jar", "MyMainClass", "@" + paramFile.getExecPathString()),
- action.getArguments());
- assertThat(
- ImmutableList.copyOf(
- ((ParameterFileWriteAction) getGeneratingAction(paramFile)).getContents()))
+ assertThat(action.getArguments())
+ .containsExactly(
+ "/bin/java",
+ "-Xverify:none",
+ "-jvmarg",
+ "-cp",
+ "pkg/exe.jar",
+ "MyMainClass",
+ "@" + paramFile.getExecPathString())
+ .inOrder();
+
+ assertThat(((ParameterFileWriteAction) getGeneratingAction(paramFile)).getContents())
.containsExactly("-X");
MoreAsserts.assertContainsSublist(actionInputsToPaths(action.getSpawn().getInputFiles()),
"pkg/exe.jar");
@@ -212,12 +217,18 @@ public class SpawnActionTest extends BuildViewTestCase {
// use STUB_ANALYSIS_ENVIRONMENT here because we also need a BuildConfiguration.
collectingAnalysisEnvironment.registerWith(getMutableActionGraph());
}
- assertEquals(asList("/bin/java", "-Xverify:none", "-jvmarg", "-cp",
- "pkg/exe.jar", "MyMainClass", "--flagfile=" + paramFile.getExecPathString()),
- ImmutableList.copyOf(action.getArguments()));
- assertEquals(Arrays.asList("-X"),
- ImmutableList.copyOf(
- ((ParameterFileWriteAction) getGeneratingAction(paramFile)).getContents()));
+ assertThat(action.getArguments())
+ .containsExactly(
+ "/bin/java",
+ "-Xverify:none",
+ "-jvmarg",
+ "-cp",
+ "pkg/exe.jar",
+ "MyMainClass",
+ "--flagfile=" + paramFile.getExecPathString())
+ .inOrder();
+ assertThat(((ParameterFileWriteAction) getGeneratingAction(paramFile)).getContents())
+ .containsExactly("-X");
MoreAsserts.assertContainsSublist(actionInputsToPaths(action.getSpawn().getInputFiles()),
"pkg/exe.jar");
}
@@ -233,9 +244,17 @@ public class SpawnActionTest extends BuildViewTestCase {
.build(ActionsTestUtil.NULL_ACTION_OWNER, collectingAnalysisEnvironment, targetConfig);
collectingAnalysisEnvironment.registerAction(actions);
SpawnAction action = (SpawnAction) actions[0];
- assertEquals(asList("/bin/java", "-Xverify:none", "-jvmarg", "-cp",
- "pkg/exe.jar", "MyMainClass", "execArg1", "execArg2", "arg1"),
- action.getArguments());
+ assertThat(action.getArguments())
+ .containsExactly(
+ "/bin/java",
+ "-Xverify:none",
+ "-jvmarg",
+ "-cp",
+ "pkg/exe.jar",
+ "MyMainClass",
+ "execArg1",
+ "execArg2",
+ "arg1");
}
@Test
@@ -260,15 +279,31 @@ public class SpawnActionTest extends BuildViewTestCase {
// use STUB_ANALYSIS_ENVIRONMENT here because we also need a BuildConfiguration.
collectingAnalysisEnvironment.registerWith(getMutableActionGraph());
}
- assertEquals(asList("/bin/java", "-Xverify:none", "-jvmarg", "-cp",
- "pkg/exe.jar", "MyMainClass", "execArg1", "execArg2",
- "@" + paramFile.getExecPathString()), action.getSpawn().getArguments());
- assertEquals(asList("/bin/java", "-Xverify:none", "-jvmarg", "-cp",
- "pkg/exe.jar", "MyMainClass", "execArg1", "execArg2",
- "@" + paramFile.getExecPathString()), ImmutableList.copyOf(action.getArguments()));
- assertEquals(Arrays.asList("arg1", "arg2", "arg3"),
- ImmutableList.copyOf(
- ((ParameterFileWriteAction) getGeneratingAction(paramFile)).getContents()));
+ assertThat(action.getSpawn().getArguments())
+ .containsExactly(
+ "/bin/java",
+ "-Xverify:none",
+ "-jvmarg",
+ "-cp",
+ "pkg/exe.jar",
+ "MyMainClass",
+ "execArg1",
+ "execArg2",
+ "@" + paramFile.getExecPathString());
+
+ assertThat(action.getArguments())
+ .containsExactly(
+ "/bin/java",
+ "-Xverify:none",
+ "-jvmarg",
+ "-cp",
+ "pkg/exe.jar",
+ "MyMainClass",
+ "execArg1",
+ "execArg2",
+ "@" + paramFile.getExecPathString());
+ assertThat(((ParameterFileWriteAction) getGeneratingAction(paramFile)).getContents())
+ .containsExactly("arg1", "arg2", "arg3").inOrder();
}
@Test
@@ -304,10 +339,10 @@ public class SpawnActionTest extends BuildViewTestCase {
public void testExtraActionInfo() throws Exception {
SpawnAction action = createCopyFromWelcomeToDestination(ImmutableMap.<String, String>of());
ExtraActionInfo info = action.getExtraActionInfo().build();
- assertEquals("Dummy", info.getMnemonic());
+ assertThat(info.getMnemonic()).isEqualTo("Dummy");
SpawnInfo spawnInfo = info.getExtension(SpawnInfo.spawnInfo);
- assertNotNull(spawnInfo);
+ assertThat(spawnInfo).isNotNull();
assertThat(spawnInfo.getArgumentList())
.containsExactlyElementsIn(action.getArguments());
@@ -320,7 +355,7 @@ public class SpawnActionTest extends BuildViewTestCase {
assertThat(spawnInfo.getInputFileList()).containsExactlyElementsIn(inputPaths);
assertThat(spawnInfo.getOutputFileList()).containsExactlyElementsIn(outputPaths);
Map<String, String> environment = action.getEnvironment();
- assertEquals(environment.size(), spawnInfo.getVariableCount());
+ assertThat(spawnInfo.getVariableCount()).isEqualTo(environment.size());
for (EnvironmentVariable variable : spawnInfo.getVariableList()) {
assertThat(environment).containsEntry(variable.getName(), variable.getValue());
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkActionTest.java
index 5f58462fc6..ef88e3e8b9 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/SymlinkActionTest.java
@@ -13,12 +13,10 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis.actions;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Executor;
@@ -62,13 +60,13 @@ public class SymlinkActionTest extends BuildViewTestCase {
@Test
public void testInputArtifactIsInput() {
Iterable<Artifact> inputs = action.getInputs();
- assertEquals(Sets.newHashSet(inputArtifact), Sets.newHashSet(inputs));
+ assertThat(inputs).containsExactly(inputArtifact);
}
@Test
public void testDestinationArtifactIsOutput() {
Iterable<Artifact> outputs = action.getOutputs();
- assertEquals(Sets.newHashSet(outputArtifact), Sets.newHashSet(outputs));
+ assertThat(outputs).containsExactly(outputArtifact);
}
@Test
@@ -76,9 +74,9 @@ public class SymlinkActionTest extends BuildViewTestCase {
Executor executor = new TestExecutorBuilder(directories, null).build();
action.execute(new ActionExecutionContext(executor, null, null, null,
ImmutableMap.<String, String>of(), null));
- assertTrue(output.isSymbolicLink());
- assertEquals(input, output.resolveSymbolicLinks());
- assertEquals(inputArtifact, action.getPrimaryInput());
- assertEquals(outputArtifact, action.getPrimaryOutput());
+ assertThat(output.isSymbolicLink()).isTrue();
+ assertThat(output.resolveSymbolicLinks()).isEqualTo(input);
+ assertThat(action.getPrimaryInput()).isEqualTo(inputArtifact);
+ assertThat(action.getPrimaryOutput()).isEqualTo(outputArtifact);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/actions/TemplateExpansionActionTest.java b/src/test/java/com/google/devtools/build/lib/analysis/actions/TemplateExpansionActionTest.java
index 6a174a851e..84ba3db8b5 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/actions/TemplateExpansionActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/actions/TemplateExpansionActionTest.java
@@ -15,13 +15,10 @@ package com.google.devtools.build.lib.analysis.actions;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.Artifact;
@@ -98,7 +95,7 @@ public class TemplateExpansionActionTest extends FoundationTestCase {
@Test
public void testDestinationArtifactIsOutput() {
- assertEquals(ImmutableSet.of(outputArtifact), create().getOutputs());
+ assertThat(create().getOutputs()).containsExactly(outputArtifact);
}
@Test
@@ -107,7 +104,7 @@ public class TemplateExpansionActionTest extends FoundationTestCase {
create().execute(createContext(executor));
String content = new String(FileSystemUtils.readContentAsLatin1(output));
String expected = Joiner.on('\n').join("key=foo", "value=bar");
- assertEquals(expected, content);
+ assertThat(content).isEqualTo(expected);
}
@Test
@@ -120,7 +117,7 @@ public class TemplateExpansionActionTest extends FoundationTestCase {
TemplateExpansionAction b = new TemplateExpansionAction(NULL_ACTION_OWNER,
outputArtifact2, Template.forString(TEMPLATE),
ImmutableList.of(Substitution.of("%key%", "foo")), false);
- assertEquals(a.computeKey(), b.computeKey());
+ assertThat(b.computeKey()).isEqualTo(a.computeKey());
}
@Test
@@ -133,7 +130,7 @@ public class TemplateExpansionActionTest extends FoundationTestCase {
TemplateExpansionAction b = new TemplateExpansionAction(NULL_ACTION_OWNER,
outputArtifact2, Template.forString(TEMPLATE),
ImmutableList.of(Substitution.of("%key%", "foo2")), false);
- assertFalse(a.computeKey().equals(b.computeKey()));
+ assertThat(a.computeKey().equals(b.computeKey())).isFalse();
}
@Test
@@ -146,7 +143,7 @@ public class TemplateExpansionActionTest extends FoundationTestCase {
TemplateExpansionAction b = new TemplateExpansionAction(NULL_ACTION_OWNER,
outputArtifact2, Template.forString(TEMPLATE),
ImmutableList.of(Substitution.of("%key%", "foo")), true);
- assertFalse(a.computeKey().equals(b.computeKey()));
+ assertThat(a.computeKey().equals(b.computeKey())).isFalse();
}
@Test
@@ -159,7 +156,7 @@ public class TemplateExpansionActionTest extends FoundationTestCase {
TemplateExpansionAction b = new TemplateExpansionAction(NULL_ACTION_OWNER,
outputArtifact2, Template.forString(TEMPLATE + " "),
ImmutableList.of(Substitution.of("%key%", "foo")), false);
- assertFalse(a.computeKey().equals(b.computeKey()));
+ assertThat(a.computeKey().equals(b.computeKey())).isFalse();
}
private TemplateExpansionAction createWithArtifact() {
@@ -191,12 +188,12 @@ public class TemplateExpansionActionTest extends FoundationTestCase {
@Test
public void testArtifactTemplateHasInput() {
- assertEquals(ImmutableList.of(inputArtifact), createWithArtifact().getInputs());
+ assertThat(createWithArtifact().getInputs()).containsExactly(inputArtifact);
}
@Test
public void testArtifactTemplateHasOutput() {
- assertEquals(ImmutableSet.of(outputArtifact), createWithArtifact().getOutputs());
+ assertThat(createWithArtifact().getOutputs()).containsExactly(outputArtifact);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationTest.java b/src/test/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationTest.java
index 7678314870..b9fcc2f39b 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/config/BuildConfigurationTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.lib.analysis.config;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableSet;
@@ -55,16 +51,16 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
+ "/" + config.getMainRepositoryName()
+ "/blaze-out/gcc-4.4.0-glibc-2.3.6-grte-piii-fastbuild";
- assertEquals(outputDirPrefix,
- config.getOutputDirectory(RepositoryName.MAIN).getPath().toString());
- assertEquals(outputDirPrefix + "/bin",
- config.getBinDirectory(RepositoryName.MAIN).getPath().toString());
- assertEquals(outputDirPrefix + "/include",
- config.getIncludeDirectory(RepositoryName.MAIN).getPath().toString());
- assertEquals(outputDirPrefix + "/genfiles",
- config.getGenfilesDirectory(RepositoryName.MAIN).getPath().toString());
- assertEquals(outputDirPrefix + "/testlogs",
- config.getTestLogsDirectory(RepositoryName.MAIN).getPath().toString());
+ assertThat(config.getOutputDirectory(RepositoryName.MAIN).getPath().toString())
+ .isEqualTo(outputDirPrefix);
+ assertThat(config.getBinDirectory(RepositoryName.MAIN).getPath().toString())
+ .isEqualTo(outputDirPrefix + "/bin");
+ assertThat(config.getIncludeDirectory(RepositoryName.MAIN).getPath().toString())
+ .isEqualTo(outputDirPrefix + "/include");
+ assertThat(config.getGenfilesDirectory(RepositoryName.MAIN).getPath().toString())
+ .isEqualTo(outputDirPrefix + "/genfiles");
+ assertThat(config.getTestLogsDirectory(RepositoryName.MAIN).getPath().toString())
+ .isEqualTo(outputDirPrefix + "/testlogs");
}
@Test
@@ -74,9 +70,12 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
}
BuildConfiguration config = create("--platform_suffix=-test");
- assertEquals(outputBase + "/" + config.getMainRepositoryName()
- + "/blaze-out/gcc-4.4.0-glibc-2.3.6-grte-k8-fastbuild-test",
- config.getOutputDirectory(RepositoryName.MAIN).getPath().toString());
+ assertThat(config.getOutputDirectory(RepositoryName.MAIN).getPath().toString())
+ .isEqualTo(
+ outputBase
+ + "/"
+ + config.getMainRepositoryName()
+ + "/blaze-out/gcc-4.4.0-glibc-2.3.6-grte-k8-fastbuild-test");
}
@Test
@@ -101,7 +100,7 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
public void testHostCpu() throws Exception {
for (String cpu : new String[] { "piii", "k8" }) {
BuildConfiguration hostConfig = createHost("--host_cpu=" + cpu);
- assertEquals(cpu, hostConfig.getFragment(CppConfiguration.class).getTargetCpu());
+ assertThat(hostConfig.getFragment(CppConfiguration.class).getTargetCpu()).isEqualTo(cpu);
}
}
@@ -113,12 +112,12 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
BuildConfigurationCollection configs = createCollection("--cpu=piii");
BuildConfiguration config = Iterables.getOnlyElement(configs.getTargetConfigurations());
- assertEquals(Label.parseAbsoluteUnchecked("//third_party/crosstool/mock:cc-compiler-piii"),
- config.getFragment(CppConfiguration.class).getCcToolchainRuleLabel());
+ assertThat(config.getFragment(CppConfiguration.class).getCcToolchainRuleLabel())
+ .isEqualTo(Label.parseAbsoluteUnchecked("//third_party/crosstool/mock:cc-compiler-piii"));
BuildConfiguration hostConfig = configs.getHostConfiguration();
- assertEquals(Label.parseAbsoluteUnchecked("//third_party/crosstool/mock:cc-compiler-k8"),
- hostConfig.getFragment(CppConfiguration.class).getCcToolchainRuleLabel());
+ assertThat(hostConfig.getFragment(CppConfiguration.class).getCcToolchainRuleLabel())
+ .isEqualTo(Label.parseAbsoluteUnchecked("//third_party/crosstool/mock:cc-compiler-k8"));
}
@Test
@@ -133,8 +132,8 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
BuildConfiguration.Options b = Options.getDefaults(BuildConfiguration.Options.class);
// The String representations of the BuildConfiguration.Options must be equal even if these are
// different objects, if they were created with the same options (no options in this case).
- assertEquals(a.toString(), b.toString());
- assertEquals(a.cacheKey(), b.cacheKey());
+ assertThat(b.toString()).isEqualTo(a.toString());
+ assertThat(b.cacheKey()).isEqualTo(a.cacheKey());
}
@Test
@@ -145,8 +144,11 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
create("--cpu=bogus", "--experimental_disable_jvm");
fail();
} catch (InvalidConfigurationException e) {
- assertThat(e.getMessage()).matches(Pattern.compile(
- "No toolchain found for cpu 'bogus'. Valid cpus are: \\[\n( [\\w-]+,\n)+]"));
+ assertThat(e)
+ .hasMessageThat()
+ .matches(
+ Pattern.compile(
+ "No toolchain found for cpu 'bogus'. Valid cpus are: \\[\n( [\\w-]+,\n)+]"));
}
}
@@ -165,8 +167,8 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
BuildConfigurationCollection master = createCollection("--multi_cpu=k8", "--multi_cpu=piii");
assertThat(master.getTargetConfigurations()).hasSize(2);
// Note: the cpus are sorted alphabetically.
- assertEquals("k8", master.getTargetConfigurations().get(0).getCpu());
- assertEquals("piii", master.getTargetConfigurations().get(1).getCpu());
+ assertThat(master.getTargetConfigurations().get(0).getCpu()).isEqualTo("k8");
+ assertThat(master.getTargetConfigurations().get(1).getCpu()).isEqualTo("piii");
}
/**
@@ -187,8 +189,8 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
master = createCollection("--multi_cpu=piii", "--multi_cpu=k8");
}
assertThat(master.getTargetConfigurations()).hasSize(2);
- assertEquals("k8", master.getTargetConfigurations().get(0).getCpu());
- assertEquals("piii", master.getTargetConfigurations().get(1).getCpu());
+ assertThat(master.getTargetConfigurations().get(0).getCpu()).isEqualTo("k8");
+ assertThat(master.getTargetConfigurations().get(1).getCpu()).isEqualTo("piii");
}
}
@@ -272,29 +274,24 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
@Test
public void testGetTransitiveOptionDetails() throws Exception {
// Directly defined options:
- assertEquals(
- CompilationMode.DBG,
- create("-c", "dbg").getTransitiveOptionDetails().getOptionValue("compilation_mode"));
- assertEquals(
- CompilationMode.OPT,
- create("-c", "opt").getTransitiveOptionDetails().getOptionValue("compilation_mode"));
+ assertThat(create("-c", "dbg").getTransitiveOptionDetails().getOptionValue("compilation_mode"))
+ .isEqualTo(CompilationMode.DBG);
+ assertThat(create("-c", "opt").getTransitiveOptionDetails().getOptionValue("compilation_mode"))
+ .isEqualTo(CompilationMode.OPT);
// Options defined in a fragment:
- assertEquals(
- Boolean.TRUE,
- create("--force_pic").getTransitiveOptionDetails().getOptionValue("force_pic"));
- assertEquals(
- Boolean.FALSE,
- create("--noforce_pic").getTransitiveOptionDetails().getOptionValue("force_pic"));
+ assertThat(create("--force_pic").getTransitiveOptionDetails().getOptionValue("force_pic"))
+ .isEqualTo(Boolean.TRUE);
+ assertThat(create("--noforce_pic").getTransitiveOptionDetails().getOptionValue("force_pic"))
+ .isEqualTo(Boolean.FALSE);
// Late-bound default option:
BuildConfiguration config = create();
- assertEquals(
- config.getTransitiveOptionDetails().getOptionValue("compiler"),
- config.getFragment(CppConfiguration.class).getCompiler());
+ assertThat(config.getFragment(CppConfiguration.class).getCompiler())
+ .isEqualTo(config.getTransitiveOptionDetails().getOptionValue("compiler"));
// Legitimately null option:
- assertNull(create().getTransitiveOptionDetails().getOptionValue("test_filter"));
+ assertThat(create().getTransitiveOptionDetails().getOptionValue("test_filter")).isNull();
}
@Test
@@ -315,9 +312,9 @@ public class BuildConfigurationTest extends ConfigurationTestCase {
analysisMock.createRuleClassProvider());
BuildConfiguration hostConfig = createHost();
- assertTrue(config.equalsOrIsSupersetOf(trimmedConfig));
- assertFalse(config.equalsOrIsSupersetOf(hostConfig));
- assertFalse(trimmedConfig.equalsOrIsSupersetOf(config));
+ assertThat(config.equalsOrIsSupersetOf(trimmedConfig)).isTrue();
+ assertThat(config.equalsOrIsSupersetOf(hostConfig)).isFalse();
+ assertThat(trimmedConfig.equalsOrIsSupersetOf(config)).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/config/BuildOptionsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/config/BuildOptionsTest.java
index 4b4d7d0258..7dbca0bf42 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/config/BuildOptionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/config/BuildOptionsTest.java
@@ -13,13 +13,11 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis.config;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.rules.cpp.CppOptions;
import com.google.devtools.common.options.OptionsParser;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -38,8 +36,8 @@ public class BuildOptionsTest {
BuildOptions b = BuildOptions.of(TEST_OPTIONS, OptionsParser.newOptionsParser(TEST_OPTIONS));
// The cache keys of the OptionSets must be equal even if these are
// different objects, if they were created with the same options (no options in this case).
- assertEquals(a.toString(), b.toString());
- assertEquals(a.computeCacheKey(), b.computeCacheKey());
+ assertThat(b.toString()).isEqualTo(a.toString());
+ assertThat(b.computeCacheKey()).isEqualTo(a.computeCacheKey());
}
@Test
@@ -48,7 +46,7 @@ public class BuildOptionsTest {
String[] options = new String[] { "--run_under=//run_under" };
BuildOptions a = BuildOptions.of(TEST_OPTIONS, options);
BuildOptions b = BuildOptions.of(TEST_OPTIONS, options);
- assertEquals(a.toString(), b.toString());
+ assertThat(b.toString()).isEqualTo(a.toString());
}
@Test
@@ -56,15 +54,20 @@ public class BuildOptionsTest {
String[] options1 = new String[] { "--compilation_mode=opt" };
String[] options2 = new String[] { "--compilation_mode=dbg" };
// Distinct instances with the same values are equal:
- assertEquals(BuildOptions.of(TEST_OPTIONS, options1), BuildOptions.of(TEST_OPTIONS, options1));
+ assertThat(BuildOptions.of(TEST_OPTIONS, options1))
+ .isEqualTo(BuildOptions.of(TEST_OPTIONS, options1));
// Same fragments, different values aren't equal:
- assertFalse(BuildOptions.of(TEST_OPTIONS, options1).equals(
- BuildOptions.of(TEST_OPTIONS, options2)));
+ assertThat(
+ BuildOptions.of(TEST_OPTIONS, options1).equals(BuildOptions.of(TEST_OPTIONS, options2)))
+ .isFalse();
// Same values, different fragments aren't equal:
- assertFalse(BuildOptions.of(TEST_OPTIONS, options1).equals(
- BuildOptions.of(
- ImmutableList.<Class<? extends FragmentOptions>>of(
- BuildConfiguration.Options.class, CppOptions.class),
- options1)));
+ assertThat(
+ BuildOptions.of(TEST_OPTIONS, options1)
+ .equals(
+ BuildOptions.of(
+ ImmutableList.<Class<? extends FragmentOptions>>of(
+ BuildConfiguration.Options.class, CppOptions.class),
+ options1)))
+ .isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/config/PerLabelOptionsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/config/PerLabelOptionsTest.java
index 1441ebe485..c1e17652cf 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/config/PerLabelOptionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/config/PerLabelOptionsTest.java
@@ -14,24 +14,18 @@
package com.google.devtools.build.lib.analysis.config;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import com.google.common.testing.EqualsTester;
import com.google.devtools.build.lib.util.RegexFilter;
import com.google.devtools.common.options.OptionsParsingException;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
-/**
- * A test for {@link PerLabelOptions}.
- */
+/** A test for {@link PerLabelOptions}. */
@RunWith(JUnit4.class)
public class PerLabelOptionsTest {
private PerLabelOptions options = null;
@@ -43,15 +37,15 @@ public class PerLabelOptionsTest {
private void assertRegexParsing(String filter) throws OptionsParsingException {
RegexFilter regexFilter = new RegexFilter.RegexFilterConverter().convert(filter);
- assertEquals(regexFilter.toString(), options.getRegexFilter().toString());
+ assertThat(options.getRegexFilter().toString()).isEqualTo(regexFilter.toString());
}
private void assertOptions(String pattern, String opts, List<String> expectedOptions)
throws OptionsParsingException {
createOptions(pattern + "@" + opts);
assertRegexParsing(pattern);
- assertNotNull(options.getOptions());
- assertEquals(expectedOptions, options.getOptions());
+ assertThat(options.getOptions()).isNotNull();
+ assertThat(options.getOptions()).isEqualTo(expectedOptions);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/config/RunUnderConverterTest.java b/src/test/java/com/google/devtools/build/lib/analysis/config/RunUnderConverterTest.java
index 4ded8121b4..70e8d002b5 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/config/RunUnderConverterTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/config/RunUnderConverterTest.java
@@ -14,21 +14,16 @@
package com.google.devtools.build.lib.analysis.config;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
import com.google.devtools.common.options.OptionsParsingException;
-
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.List;
-
-/**
- * Tests {@link RunUnderConverter}.
- */
+/** Tests {@link RunUnderConverter}. */
@RunWith(JUnit4.class)
public class RunUnderConverterTest {
@@ -49,9 +44,10 @@ public class RunUnderConverterTest {
private void assertEqualsRunUnder(String input, String label, String command,
List<String> options) throws Exception {
RunUnder runUnder = new RunUnderConverter().convert(input);
- assertEquals(label, runUnder.getLabel() == null ? null : runUnder.getLabel().toString());
- assertEquals(command, runUnder.getCommand());
- assertEquals(options, runUnder.getOptions());
+ assertThat(runUnder.getLabel() == null ? null : runUnder.getLabel().toString())
+ .isEqualTo(label);
+ assertThat(runUnder.getCommand()).isEqualTo(command);
+ assertThat(runUnder.getOptions()).isEqualTo(options);
}
private void assertRunUnderFails(String input, String expectedError) {
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/config/StampTest.java b/src/test/java/com/google/devtools/build/lib/analysis/config/StampTest.java
index 1875088c53..c6e68c042e 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/config/StampTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/config/StampTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.analysis.config;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.packages.AttributeContainer;
@@ -22,7 +22,6 @@ import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleFactory;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.packages.TriState;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -43,7 +42,8 @@ public class StampTest extends BuildViewTestCase {
for (String name : ruleFactory.getRuleClassNames()) {
RuleClass ruleClass = ruleFactory.getRuleClass(name);
if (TargetUtils.isTestRuleName(name) && ruleClass.hasAttr("stamp", BuildType.TRISTATE)) {
- assertEquals(TriState.NO, ruleClass.getAttributeByName("stamp").getDefaultValue(null));
+ assertThat(ruleClass.getAttributeByName("stamp").getDefaultValue(null))
+ .isEqualTo(TriState.NO);
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/constraints/ConstraintsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/constraints/ConstraintsTest.java
index 95962e1461..fac4f006b6 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/constraints/ConstraintsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/constraints/ConstraintsTest.java
@@ -14,8 +14,6 @@
package com.google.devtools.build.lib.analysis.constraints;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.analysis.BaseRuleClasses;
@@ -33,17 +31,13 @@ import com.google.devtools.build.lib.packages.RuleClass.Builder;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.testutil.UnknownRuleConfiguredTarget;
import com.google.devtools.build.lib.util.FileTypeSet;
-
+import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Set;
-
-/**
- * Tests for the constraint enforcement system.
- */
+/** Tests for the constraint enforcement system. */
@RunWith(JUnit4.class)
public class ConstraintsTest extends AbstractConstraintsTest {
@@ -271,7 +265,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
new EnvironmentGroupMaker("buildenv/foo").setEnvironments("a", "b").setDefaults("a").make();
reporter.removeHandler(failFastHandler);
String ruleDef = getDependencyRule(constrainedTo());
- assertNull(scratchConfiguredTarget("hello", "dep", ruleDef));
+ assertThat(scratchConfiguredTarget("hello", "dep", ruleDef)).isNull();
assertContainsEvent("attribute cannot be empty");
}
@@ -298,7 +292,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
reporter.removeHandler(failFastHandler);
String ruleDef = getDependencyRule(
constrainedTo("//buildenv/foo:b"), compatibleWith("//buildenv/foo:b"));
- assertNull(scratchConfiguredTarget("hello", "dep", ruleDef));
+ assertThat(scratchConfiguredTarget("hello", "dep", ruleDef)).isNull();
assertContainsEvent("//buildenv/foo:b cannot appear both here and in restricted_to");
}
@@ -311,7 +305,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
reporter.removeHandler(failFastHandler);
String ruleDef = getDependencyRule(
constrainedTo("//buildenv/foo:a"), compatibleWith("//buildenv/foo:b"));
- assertNull(scratchConfiguredTarget("hello", "dep", ruleDef));
+ assertThat(scratchConfiguredTarget("hello", "dep", ruleDef)).isNull();
assertContainsEvent(
"//buildenv/foo:b and //buildenv/foo:a belong to the same environment group");
}
@@ -371,7 +365,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
writeRuleClassDefaultEnvironments();
reporter.removeHandler(failFastHandler);
String ruleDef = "bad_rule_class_default(name = 'a')";
- assertNull(scratchConfiguredTarget("hello", "a", ruleDef));
+ assertThat(scratchConfiguredTarget("hello", "a", ruleDef)).isNull();
assertContainsEvent("//buildenv/rule_class_compat:a and //buildenv/rule_class_compat:b "
+ "belong to the same environment group");
}
@@ -385,7 +379,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(),
getDependingRule());
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -398,7 +392,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(constrainedTo("//buildenv/foo:b")),
getDependingRule(constrainedTo("//buildenv/foo:b")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -412,7 +406,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(constrainedTo("//buildenv/foo:a", "//buildenv/foo:b")),
getDependingRule(constrainedTo("//buildenv/foo:b")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -427,7 +421,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(constrainedTo("//buildenv/foo:b")),
getDependingRule(constrainedTo("//buildenv/foo:a", "//buildenv/foo:b")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent(
"dependency //hello:dep doesn't support expected environment: //buildenv/foo:a");
}
@@ -443,7 +437,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(compatibleWith("//buildenv/foo:b", "//buildenv/foo:c")),
getDependingRule(compatibleWith("//buildenv/foo:b", "//buildenv/foo:c")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -458,7 +452,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(compatibleWith("//buildenv/foo:b", "//buildenv/foo:c")),
getDependingRule(compatibleWith("//buildenv/foo:c")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -474,7 +468,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(compatibleWith("//buildenv/foo:c")),
getDependingRule(compatibleWith("//buildenv/foo:b", "//buildenv/foo:c")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent(
"dependency //hello:dep doesn't support expected environment: //buildenv/foo:b");
}
@@ -490,7 +484,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(),
getDependingRule(compatibleWith("//buildenv/foo:b", "//buildenv/foo:c")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent("dependency //hello:dep doesn't support expected environments: "
+ "//buildenv/foo:b, //buildenv/foo:c");
}
@@ -508,7 +502,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(constrainedTo("//buildenv/foo:b", "//buildenv/foo:c"),
compatibleWith("//buildenv/bar:e")),
getDependingRule(constrainedTo("//buildenv/foo:c"), compatibleWith("//buildenv/bar:e")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -526,7 +520,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependingRule(constrainedTo("//buildenv/foo:b", "//buildenv/foo:c"),
compatibleWith("//buildenv/bar:e")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent(
"dependency //hello:dep doesn't support expected environment: //buildenv/foo:b");
}
@@ -542,7 +536,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(),
getDependingRule(constrainedTo("//buildenv/foo:b")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -558,7 +552,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(),
getDependingRule(constrainedTo("//buildenv/foo:c")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent(
"dependency //hello:dep doesn't support expected environment: //buildenv/foo:c");
}
@@ -575,7 +569,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(constrainedTo("//buildenv/foo:a", "//buildenv/foo:b")),
getDependingRule());
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -592,7 +586,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(constrainedTo("//buildenv/foo:b")),
getDependingRule());
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent(
"dependency //hello:dep doesn't support expected environment: //buildenv/foo:a");
}
@@ -610,7 +604,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
constrainedTo("//buildenv/foo:a", "//buildenv/foo:b"),
getAttrDef("deps", "good_dep", "bad_dep")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:depender"));
+ assertThat(getConfiguredTarget("//hello:depender")).isNull();
assertContainsEvent("//hello:bad_dep doesn't support expected environment: //buildenv/foo:a");
assertDoesNotContainEvent("//hello:good_dep");
}
@@ -623,7 +617,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(),
getDependingRule(compatibleWith("//buildenv/foo:b", "//buildenv/foo:c")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -640,7 +634,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" tools = [':main'])",
getDependencyRule(),
getDependingRule(compatibleWith("//buildenv/foo:a")));
- assertNotNull(getConfiguredTarget("//hello:gen"));
+ assertThat(getConfiguredTarget("//hello:gen")).isNotNull();
assertNoEvents();
}
@@ -655,7 +649,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
"package(default_compatible_with = ['//buildenv/foo:b'])",
getDependencyRule(),
getDependingRule(compatibleWith("//buildenv/foo:b")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -673,7 +667,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(compatibleWith("//buildenv/foo:a")),
getDependingRule(compatibleWith("//buildenv/foo:a", "//buildenv/foo:b")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent(
"dependency //hello:dep doesn't support expected environment: //buildenv/foo:b");
}
@@ -690,7 +684,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
"package(default_restricted_to = ['//buildenv/foo:b'])",
getDependencyRule(constrainedTo("//buildenv/foo:b")),
getDependingRule());
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -708,7 +702,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(constrainedTo("//buildenv/foo:a")),
getDependingRule(constrainedTo("//buildenv/foo:a", "//buildenv/foo:b")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent(
"dependency //hello:dep doesn't support expected environment: //buildenv/foo:b");
}
@@ -726,7 +720,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
"package(default_restricted_to = ['//buildenv/foo:b'])",
getDependencyRule(compatibleWith("//buildenv/foo:a")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:dep"));
+ assertThat(getConfiguredTarget("//hello:dep")).isNull();
assertContainsEvent("//buildenv/foo:a and //buildenv/foo:b belong to the same "
+ "environment group. They should be declared together either here or in restricted_to");
}
@@ -745,7 +739,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" cmd = '',",
" tools = [':host_tool'],",
" compatible_with = ['//buildenv/foo:a'])");
- assertNotNull(getConfiguredTarget("//hello:hello"));
+ assertThat(getConfiguredTarget("//hello:hello")).isNotNull();
assertNoEvents();
}
@@ -764,7 +758,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" cmd = '',",
" tools = [':host_tool'],",
" compatible_with = ['//buildenv/foo:a'])");
- assertNotNull(getConfiguredTarget("//hello:hello"));
+ assertThat(getConfiguredTarget("//hello:hello")).isNotNull();
assertNoEvents();
}
@@ -775,7 +769,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
"rule_with_implicit_and_latebound_deps(",
" name = 'hi',",
" compatible_with = ['//buildenv/foo:b'])");
- assertNotNull(getConfiguredTarget("//hello:hi"));
+ assertThat(getConfiguredTarget("//hello:hi")).isNotNull();
// Note that the event "cannot build rule_with_implicit_and_latebound_deps" *does* occur
// because of the implementation of UnknownRuleConfiguredTarget.
assertDoesNotContainEvent(":implicit doesn't support expected environment");
@@ -791,7 +785,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" name = 'hi',",
" compatible_with = ['//buildenv/foo:b'])");
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:hi"));
+ assertThat(getConfiguredTarget("//hello:hi")).isNull();
assertContainsEvent(
"dependency //helpers:implicit doesn't support expected environment: //buildenv/foo:b");
}
@@ -804,7 +798,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" name = 'hi',",
" some_attr = '//helpers:default',",
" compatible_with = ['//buildenv/foo:b'])");
- assertNotNull(getConfiguredTarget("//hello:hi"));
+ assertThat(getConfiguredTarget("//hello:hi")).isNotNull();
// This rule is implemented by UnknownRuleConfiguredTarget, which fails on analysis by design.
// Ensure that's the only event reported.
assertThat(Iterables.getOnlyElement(eventCollector).getMessage()).isEqualTo(
@@ -820,7 +814,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" data = ['//helpers:default'],",
" resources = ['//helpers:default'],",
" compatible_with = ['//buildenv/foo:b'])");
- assertNotNull(getConfiguredTarget("//hello:hi"));
+ assertThat(getConfiguredTarget("//hello:hi")).isNotNull();
assertNoEvents();
}
@@ -835,7 +829,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" data = ['whatever.txt'],",
" compatible_with = ['//buildenv/foo:a'])");
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:shlib"));
+ assertThat(getConfiguredTarget("//hello:shlib")).isNull();
assertContainsEvent(
"dependency //hello:gen doesn't support expected environment: //buildenv/foo:a");
}
@@ -851,7 +845,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" }),",
" compatible_with = ['//buildenv/foo:a'])");
useConfiguration("--define", "mode=a");
- assertNotNull(getConfiguredTarget("//hello:shlib"));
+ assertThat(getConfiguredTarget("//hello:shlib")).isNotNull();
assertNoEvents();
}
@@ -865,7 +859,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(constrainedTo("//buildenv/foo:a")),
getDependingRule(constrainedTo("//buildenv/foo:b")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -880,7 +874,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
getDependencyRule(constrainedTo("//buildenv/foo:b")),
getDependingRule(constrainedTo("//buildenv/foo:a")));
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNull();
assertContainsEvent(
"dependency //hello:dep doesn't support expected environment: //buildenv/foo:a");
}
@@ -896,7 +890,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(constrainedTo("//buildenv/foo:a")),
getDependingRule(constrainedTo("//buildenv/foo:c")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -910,7 +904,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(),
getDependingRule(constrainedTo("//buildenv/foo:b")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -925,7 +919,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(),
getDependingRule(constrainedTo("//buildenv/foo:c")));
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -939,7 +933,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
scratch.file("hello/BUILD",
getDependencyRule(constrainedTo("//buildenv/foo:a")),
getDependingRule());
- assertNotNull(getConfiguredTarget("//hello:main"));
+ assertThat(getConfiguredTarget("//hello:main")).isNotNull();
assertNoEvents();
}
@@ -956,7 +950,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
")");
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//ihave:nolimits"));
+ assertThat(getConfiguredTarget("//ihave:nolimits")).isNull();
assertContainsEvent("no such attribute 'restricted_to' in 'totally_free_rule'");
}
@@ -966,7 +960,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
.setEnvironments("a", "b")
.setDefaults("a")
.make();
- assertNotNull(getConfiguredTarget("//buildenv/foo:foo"));
+ assertThat(getConfiguredTarget("//buildenv/foo:foo")).isNotNull();
}
private void writeDepsForSelectTests() throws Exception {
@@ -995,7 +989,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" }),",
" compatible_with = ['//buildenv/foo:a', '//buildenv/foo:b'])");
useConfiguration("--define", "mode=a");
- assertNotNull(getConfiguredTarget("//hello:lib"));
+ assertThat(getConfiguredTarget("//hello:lib")).isNotNull();
}
@Test
@@ -1016,7 +1010,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" }),",
" compatible_with = ['//buildenv/foo:a', '//buildenv/foo:b', '//buildenv/foo:c'])");
useConfiguration("--define", "mode=a");
- assertNotNull(getConfiguredTarget("//hello:lib"));
+ assertThat(getConfiguredTarget("//hello:lib")).isNotNull();
}
@Test
@@ -1035,7 +1029,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" compatible_with = ['//buildenv/foo:a', '//buildenv/foo:b'])");
useConfiguration("--define", "mode=a");
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:lib"));
+ assertThat(getConfiguredTarget("//hello:lib")).isNull();
assertContainsEvent(
"dependency //deps:dep_a doesn't support expected environment: //buildenv/foo:b");
}
@@ -1053,7 +1047,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" }),",
" compatible_with = ['//buildenv/foo:a', '//buildenv/foo:b'])");
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:lib"));
+ assertThat(getConfiguredTarget("//hello:lib")).isNull();
assertContainsEvent(
"dependency //deps:dep_a doesn't support expected environment: //buildenv/foo:b");
}
@@ -1073,7 +1067,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" compatible_with = ['//buildenv/foo:a'])");
useConfiguration("--define", "mode=a");
// Valid because "--define mode=a" refines :lib to "compatible_with = ['//buildenv/foo:a']".
- assertNotNull(getConfiguredTarget("//hello:lib"));
+ assertThat(getConfiguredTarget("//hello:lib")).isNotNull();
}
@Test
@@ -1092,7 +1086,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
useConfiguration("--define", "mode=a");
reporter.removeHandler(failFastHandler);
// Invalid because "--define mode=a" refines :lib to "compatible_with = []" (empty).
- assertNull(getConfiguredTarget("//hello:lib"));
+ assertThat(getConfiguredTarget("//hello:lib")).isNull();
assertContainsEvent("//hello:lib: the current command-line flags disqualify all supported "
+ "environments because of incompatible select() paths:\n"
+ " environment: //buildenv/foo:b removed by: //hello:lib (/workspace/hello/BUILD:1:1)");
@@ -1118,7 +1112,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" compatible_with = ['//buildenv/foo:a'])");
useConfiguration("--define", "mode=a");
// Valid because "--define mode=a" refines :lib to "compatible_with = ['//buildenv/foo:a']".
- assertNotNull(getConfiguredTarget("//hello:depender"));
+ assertThat(getConfiguredTarget("//hello:depender")).isNotNull();
}
@Test
@@ -1142,7 +1136,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
useConfiguration("--define", "mode=a");
reporter.removeHandler(failFastHandler);
// Invalid because "--define mode=a" refines :lib to "compatible_with = ['//buildenv/foo:a']".
- assertNull(getConfiguredTarget("//hello:depender"));
+ assertThat(getConfiguredTarget("//hello:depender")).isNull();
assertContainsEvent("//hello:depender: the current command-line flags disqualify all supported "
+ "environments because of incompatible select() paths:\n"
+ " environment: //buildenv/foo:b removed by: //hello:lib (/workspace/hello/BUILD:1:1)");
@@ -1177,7 +1171,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
useConfiguration("--define", "mode=a");
reporter.removeHandler(failFastHandler);
// Invalid because "--define mode=a" refines :lib to "compatible_with = ['//buildenv/foo:a']".
- assertNull(getConfiguredTarget("//hello:depender"));
+ assertThat(getConfiguredTarget("//hello:depender")).isNull();
assertContainsEvent("//hello:depender: the current command-line flags disqualify all supported "
+ "environments because of incompatible select() paths:\n"
+ " environment: //buildenv/foo:b removed by: //hello:lib2 (/workspace/hello/BUILD:1:1)");
@@ -1199,7 +1193,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
reporter.removeHandler(failFastHandler);
// Invalid because :lib has an implicit default of ['//buildenv/foo:b'] and "--define mode=a"
// refines it to "compatible_with = []" (empty).
- assertNull(getConfiguredTarget("//hello:lib"));
+ assertThat(getConfiguredTarget("//hello:lib")).isNull();
assertContainsEvent("//hello:lib: the current command-line flags disqualify all supported "
+ "environments because of incompatible select() paths:\n"
+ " environment: //buildenv/foo:b removed by: //hello:lib (/workspace/hello/BUILD:1:1)");
@@ -1229,9 +1223,9 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" compatible_with = ['//buildenv/foo:a', '//buildenv/bar:c'])");
useConfiguration("--define", "mode=a");
reporter.removeHandler(failFastHandler);
- // Invalid because while the //buildenv/foo refinement successfully refines :lib to
- // ['//buildenv/foo:a'], the bar refinement refines it to [].
- assertNull(getConfiguredTarget("//hello:lib"));
+ // Invalid because while the //buildenv/foo refinement successfully refines :lib to
+ // ['//buildenv/foo:a'], the bar refinement refines it to [].
+ assertThat(getConfiguredTarget("//hello:lib")).isNull();
assertContainsEvent("//hello:lib: the current command-line flags disqualify all supported "
+ "environments because of incompatible select() paths:\n"
+ " environment: //buildenv/bar:c removed by: //hello:lib (/workspace/hello/BUILD:1:1)");
@@ -1264,7 +1258,7 @@ public class ConstraintsTest extends AbstractConstraintsTest {
" compatible_with = ['//buildenv/foo:a', '//buildenv/bar:c'])");
useConfiguration("--define", "mode=a");
reporter.removeHandler(failFastHandler);
- assertNull(getConfiguredTarget("//hello:lib"));
+ assertThat(getConfiguredTarget("//hello:lib")).isNull();
assertContainsEvent("//hello:lib: the current command-line flags disqualify all supported "
+ "environments because of incompatible select() paths:\n"
+ "\nenvironment group: //buildenv/foo:foo:\n"
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/select/AbstractAttributeMapperTest.java b/src/test/java/com/google/devtools/build/lib/analysis/select/AbstractAttributeMapperTest.java
index 942e1bba29..ac89f9f0eb 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/select/AbstractAttributeMapperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/select/AbstractAttributeMapperTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.lib.analysis.select;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.Lists;
@@ -32,17 +28,13 @@ import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.syntax.Type;
-
+import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.List;
-
-/**
- * Unit tests for {@link AbstractAttributeMapper}.
- */
+/** Unit tests for {@link AbstractAttributeMapper}. */
@RunWith(JUnit4.class)
public class AbstractAttributeMapperTest extends BuildViewTestCase {
@@ -68,8 +60,8 @@ public class AbstractAttributeMapperTest extends BuildViewTestCase {
@Test
public void testRuleProperties() throws Exception {
- assertEquals(rule.getName(), mapper.getName());
- assertEquals(rule.getLabel(), mapper.getLabel());
+ assertThat(mapper.getName()).isEqualTo(rule.getName());
+ assertThat(mapper.getLabel()).isEqualTo(rule.getLabel());
}
@Test
@@ -78,9 +70,9 @@ public class AbstractAttributeMapperTest extends BuildViewTestCase {
"cc_binary(name = 'myrule',",
" srcs = ['a', 'b', 'c'])");
Package pkg = rule.getPackage();
- assertEquals(pkg.getDefaultHdrsCheck(), mapper.getPackageDefaultHdrsCheck());
- assertEquals(pkg.getDefaultTestOnly(), mapper.getPackageDefaultTestOnly());
- assertEquals(pkg.getDefaultDeprecation(), mapper.getPackageDefaultDeprecation());
+ assertThat(mapper.getPackageDefaultHdrsCheck()).isEqualTo(pkg.getDefaultHdrsCheck());
+ assertThat(mapper.getPackageDefaultTestOnly()).isEqualTo(pkg.getDefaultTestOnly());
+ assertThat(mapper.getPackageDefaultDeprecation()).isEqualTo(pkg.getDefaultDeprecation());
}
@Test
@@ -107,21 +99,21 @@ public class AbstractAttributeMapperTest extends BuildViewTestCase {
@Test
public void testGetAttributeType() throws Exception {
- assertEquals(BuildType.LABEL_LIST, mapper.getAttributeType("srcs"));
- assertNull(mapper.getAttributeType("nonsense"));
+ assertThat(mapper.getAttributeType("srcs")).isEqualTo(BuildType.LABEL_LIST);
+ assertThat(mapper.getAttributeType("nonsense")).isNull();
}
@Test
public void testGetAttributeDefinition() {
- assertEquals("srcs", mapper.getAttributeDefinition("srcs").getName());
- assertNull(mapper.getAttributeDefinition("nonsense"));
+ assertThat(mapper.getAttributeDefinition("srcs").getName()).isEqualTo("srcs");
+ assertThat(mapper.getAttributeDefinition("nonsense")).isNull();
}
@Test
public void testIsAttributeExplicitlySpecified() throws Exception {
- assertTrue(mapper.isAttributeValueExplicitlySpecified("srcs"));
- assertFalse(mapper.isAttributeValueExplicitlySpecified("deps"));
- assertFalse(mapper.isAttributeValueExplicitlySpecified("nonsense"));
+ assertThat(mapper.isAttributeValueExplicitlySpecified("srcs")).isTrue();
+ assertThat(mapper.isAttributeValueExplicitlySpecified("deps")).isFalse();
+ assertThat(mapper.isAttributeValueExplicitlySpecified("nonsense")).isFalse();
}
protected static class VisitationRecorder implements AttributeMap.AcceptsLabelAttribute {
@@ -153,6 +145,6 @@ public class AbstractAttributeMapperTest extends BuildViewTestCase {
assertThat(mapper.getComputedDefault("$stl_default", BuildType.LABEL))
.isInstanceOf(Attribute.ComputedDefault.class);
// Should return null since this *isn't* a computed default:
- assertNull(mapper.getComputedDefault("srcs", BuildType.LABEL_LIST));
+ assertThat(mapper.getComputedDefault("srcs", BuildType.LABEL_LIST)).isNull();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/select/AggregatingAttributeMapperTest.java b/src/test/java/com/google/devtools/build/lib/analysis/select/AggregatingAttributeMapperTest.java
index 5c5f3ea8d3..266b0d96eb 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/select/AggregatingAttributeMapperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/select/AggregatingAttributeMapperTest.java
@@ -16,7 +16,6 @@ package com.google.devtools.build.lib.analysis.select;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.syntax.Type.STRING;
-import static org.junit.Assert.assertNull;
import com.google.common.base.Joiner;
import com.google.common.base.Verify;
@@ -39,7 +38,6 @@ import com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.testutil.UnknownRuleConfiguredTarget;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -72,7 +70,7 @@ public class AggregatingAttributeMapperTest extends AbstractAttributeMapperTest
"sh_binary(name = 'myrule',",
" srcs = ['a.sh'])");
assertThat(AggregatingAttributeMapper.of(rule).visitAttribute("srcs", BuildType.LABEL_LIST))
- .containsExactlyElementsIn(ImmutableList.of(ImmutableList.of(Label.create("@//a", "a.sh"))));
+ .containsExactly(ImmutableList.of(Label.create("@//a", "a.sh")));
}
/**
@@ -89,11 +87,10 @@ public class AggregatingAttributeMapperTest extends AbstractAttributeMapperTest
" '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': ['default.sh'],",
" }))");
assertThat(AggregatingAttributeMapper.of(rule).visitAttribute("srcs", BuildType.LABEL_LIST))
- .containsExactlyElementsIn(
- ImmutableList.of(
- ImmutableList.of(Label.create("@//a", "a.sh")),
- ImmutableList.of(Label.create("@//a", "b.sh")),
- ImmutableList.of(Label.create("@//a", "default.sh"))));
+ .containsExactly(
+ ImmutableList.of(Label.create("@//a", "a.sh")),
+ ImmutableList.of(Label.create("@//a", "b.sh")),
+ ImmutableList.of(Label.create("@//a", "default.sh")));
}
@Test
@@ -108,12 +105,11 @@ public class AggregatingAttributeMapperTest extends AbstractAttributeMapperTest
" '//conditions:b2': ['b2.sh']})",
" )");
assertThat(AggregatingAttributeMapper.of(rule).visitAttribute("srcs", BuildType.LABEL_LIST))
- .containsExactlyElementsIn(
- ImmutableList.of(
- ImmutableList.of(Label.create("@//a", "a1.sh"), Label.create("@//a", "a2.sh")),
- ImmutableList.of(Label.create("@//a", "a1.sh"), Label.create("@//a", "b2.sh")),
- ImmutableList.of(Label.create("@//a", "b1.sh"), Label.create("@//a", "a2.sh")),
- ImmutableList.of(Label.create("@//a", "b1.sh"), Label.create("@//a", "b2.sh"))));
+ .containsExactly(
+ ImmutableList.of(Label.create("@//a", "a1.sh"), Label.create("@//a", "a2.sh")),
+ ImmutableList.of(Label.create("@//a", "a1.sh"), Label.create("@//a", "b2.sh")),
+ ImmutableList.of(Label.create("@//a", "b1.sh"), Label.create("@//a", "a2.sh")),
+ ImmutableList.of(Label.create("@//a", "b1.sh"), Label.create("@//a", "b2.sh")));
}
/**
@@ -169,8 +165,7 @@ public class AggregatingAttributeMapperTest extends AbstractAttributeMapperTest
VisitationRecorder recorder = new VisitationRecorder("malloc");
AggregatingAttributeMapper.of(rule).visitLabels(recorder);
assertThat(recorder.labelsVisited)
- .containsExactlyElementsIn(
- ImmutableList.of("//conditions:a", getDefaultMallocLabel(rule).toString()));
+ .containsExactly("//conditions:a", getDefaultMallocLabel(rule).toString());
}
@@ -231,9 +226,8 @@ public class AggregatingAttributeMapperTest extends AbstractAttributeMapperTest
" srcs = ['main.java'])");
AggregatingAttributeMapper mapper = AggregatingAttributeMapper.of(rule);
Attribute launcherAttribute = mapper.getAttributeDefinition("launcher");
- assertNull(mapper.get(launcherAttribute.getName(), launcherAttribute.getType()));
- assertThat(mapper.checkForDuplicateLabels(launcherAttribute))
- .containsExactlyElementsIn(ImmutableList.of());
+ assertThat(mapper.get(launcherAttribute.getName(), launcherAttribute.getType())).isNull();
+ assertThat(mapper.checkForDuplicateLabels(launcherAttribute)).isEmpty();
}
/**
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/select/NonconfigurableAttributeMapperTest.java b/src/test/java/com/google/devtools/build/lib/analysis/select/NonconfigurableAttributeMapperTest.java
index 79a1eb1d34..97ce65f1b6 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/select/NonconfigurableAttributeMapperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/select/NonconfigurableAttributeMapperTest.java
@@ -14,13 +14,11 @@
package com.google.devtools.build.lib.analysis.select;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.packages.NonconfigurableAttributeMapper;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.syntax.Type;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -46,8 +44,8 @@ public class NonconfigurableAttributeMapperTest extends AbstractAttributeMapperT
@Test
public void testGetNonconfigurableAttribute() throws Exception {
- assertEquals("this rule is deprecated!",
- NonconfigurableAttributeMapper.of(rule).get("deprecation", Type.STRING));
+ assertThat(NonconfigurableAttributeMapper.of(rule).get("deprecation", Type.STRING))
+ .isEqualTo("this rule is deprecated!");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/select/RawAttributeMapperTest.java b/src/test/java/com/google/devtools/build/lib/analysis/select/RawAttributeMapperTest.java
index 04fda2fe81..f1bf25497d 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/select/RawAttributeMapperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/select/RawAttributeMapperTest.java
@@ -14,13 +14,8 @@
package com.google.devtools.build.lib.analysis.select;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.AttributeMap;
@@ -61,7 +56,7 @@ public class RawAttributeMapperTest extends AbstractAttributeMapperTest {
public void testGetAttribute() throws Exception {
RawAttributeMapper rawMapper = RawAttributeMapper.of(setupGenRule());
List<Label> value = rawMapper.get("data", BuildType.LABEL_LIST);
- assertNotNull(value);
+ assertThat(value).isNotNull();
assertThat(value).containsExactly(
Label.create("@//x", "data_a"), Label.create("@//x", "data_b"));
@@ -71,7 +66,9 @@ public class RawAttributeMapperTest extends AbstractAttributeMapperTest {
rawMapper.get("srcs", BuildType.LABEL_LIST);
fail("Expected srcs lookup to fail since the returned type is a SelectorList and not a list");
} catch (IllegalArgumentException e) {
- assertThat(e.getCause().getMessage())
+ assertThat(e)
+ .hasCauseThat()
+ .hasMessageThat()
.contains("SelectorList cannot be cast to java.util.List");
}
}
@@ -80,15 +77,16 @@ public class RawAttributeMapperTest extends AbstractAttributeMapperTest {
@Test
public void testGetAttributeType() throws Exception {
RawAttributeMapper rawMapper = RawAttributeMapper.of(setupGenRule());
- assertEquals(BuildType.LABEL_LIST, rawMapper.getAttributeType("data")); // not configurable
- assertEquals(BuildType.LABEL_LIST, rawMapper.getAttributeType("srcs")); // configurable
+ assertThat(rawMapper.getAttributeType("data"))
+ .isEqualTo(BuildType.LABEL_LIST); // not configurable
+ assertThat(rawMapper.getAttributeType("srcs")).isEqualTo(BuildType.LABEL_LIST); // configurable
}
@Test
public void testConfigurabilityCheck() throws Exception {
RawAttributeMapper rawMapper = RawAttributeMapper.of(setupGenRule());
- assertFalse(rawMapper.isConfigurable("data"));
- assertTrue(rawMapper.isConfigurable("srcs"));
+ assertThat(rawMapper.isConfigurable("data")).isFalse();
+ assertThat(rawMapper.isConfigurable("srcs")).isTrue();
}
/**
@@ -106,7 +104,9 @@ public class RawAttributeMapperTest extends AbstractAttributeMapperTest {
});
fail("Expected label visitation to fail since one attribute is configurable");
} catch (IllegalArgumentException e) {
- assertThat(e.getCause().getMessage())
+ assertThat(e)
+ .hasCauseThat()
+ .hasMessageThat()
.contains("SelectorList cannot be cast to java.util.List");
}
}
@@ -115,11 +115,10 @@ public class RawAttributeMapperTest extends AbstractAttributeMapperTest {
public void testGetConfigurabilityKeys() throws Exception {
RawAttributeMapper rawMapper = RawAttributeMapper.of(setupGenRule());
assertThat(rawMapper.getConfigurabilityKeys("srcs", BuildType.LABEL_LIST))
- .containsExactlyElementsIn(
- ImmutableSet.of(
- Label.parseAbsolute("//conditions:a"),
- Label.parseAbsolute("//conditions:b"),
- Label.parseAbsolute("//conditions:default")));
+ .containsExactly(
+ Label.parseAbsolute("//conditions:a"),
+ Label.parseAbsolute("//conditions:b"),
+ Label.parseAbsolute("//conditions:default"));
assertThat(rawMapper.getConfigurabilityKeys("data", BuildType.LABEL_LIST)).isEmpty();
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestBase.java b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestBase.java
index 184ba7d6fc..38f1deba6c 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestBase.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestBase.java
@@ -15,7 +15,6 @@
package com.google.devtools.build.lib.analysis.util;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
@@ -41,7 +40,6 @@ import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.DeterministicHelper;
import com.google.devtools.build.skyframe.InMemoryMemoizingEvaluator;
import com.google.devtools.build.skyframe.NotifyingHelper.Listener;
-
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@@ -120,7 +118,8 @@ public abstract class BuildViewTestBase extends AnalysisTestCase {
eventCollector.clear();
}
update(defaultFlags().with(Flag.KEEP_GOING), "//parent:foo");
- assertEquals(1, getFrequencyOfErrorsWithLocation(badpkgBuildFile.asFragment(), eventCollector));
+ assertThat(getFrequencyOfErrorsWithLocation(badpkgBuildFile.asFragment(), eventCollector))
+ .isEqualTo(1);
// TODO(nharmata): This test currently only works because each BuildViewTest#update call
// dirties all FileNodes that are in error. There is actually a skyframe bug with cycle
// reporting on incremental builds (see b/14622820).
@@ -155,7 +154,7 @@ public abstract class BuildViewTestBase extends AnalysisTestCase {
AnalysisResult result = getAnalysisResult();
assertThat(result.getTargetsToBuild()).hasSize(1);
ConfiguredTarget targetA = Iterables.get(result.getTargetsToBuild(), 0);
- assertEquals(goodCpu, targetA.getConfiguration().getCpu());
+ assertThat(targetA.getConfiguration().getCpu()).isEqualTo(goodCpu);
// Unfortunately, we get the same error twice - we can't distinguish the configurations.
assertContainsEvent("if genrules produce executables, they are allowed only one output");
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java
index c17a916056..601882c5b0 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java
@@ -14,12 +14,8 @@
package com.google.devtools.build.lib.analysis.util;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.getFirstArtifactEndingWith;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
@@ -552,7 +548,7 @@ public abstract class BuildViewTestCase extends FoundationTestCase {
protected void assertConfigurationsEqual(BuildConfiguration config1, BuildConfiguration config2) {
// BuildOptions and crosstool files determine a configuration's content. Within the context
// of these tests only the former actually change.
- assertEquals(config1.cloneOptions(), config2.cloneOptions());
+ assertThat(config2.cloneOptions()).isEqualTo(config1.cloneOptions());
}
/**
@@ -848,8 +844,10 @@ public abstract class BuildViewTestCase extends FoundationTestCase {
reporter.removeHandler(failFastHandler); // expect errors
ConfiguredTarget target = scratchConfiguredTarget(packageName, ruleName, lines);
if (target != null) {
- assertTrue("Rule '" + "//" + packageName + ":" + ruleName + "' did not contain an error",
- view.hasErrors(target));
+ assertWithMessage(
+ "Rule '" + "//" + packageName + ":" + ruleName + "' did not contain an error")
+ .that(view.hasErrors(target))
+ .isTrue();
}
return assertContainsEvent(expectedErrorMessage);
}
@@ -892,9 +890,9 @@ public abstract class BuildViewTestCase extends FoundationTestCase {
eventCollector.clear();
ConfiguredTarget target = scratchConfiguredTarget(packageName, ruleName,
lines);
- assertFalse(
- "Rule '" + "//" + packageName + ":" + ruleName + "' did contain an error",
- view.hasErrors(target));
+ assertWithMessage("Rule '" + "//" + packageName + ":" + ruleName + "' did contain an error")
+ .that(view.hasErrors(target))
+ .isFalse();
return assertContainsEvent(expectedWarningMessage);
}
@@ -921,21 +919,23 @@ public abstract class BuildViewTestCase extends FoundationTestCase {
Target outTarget = getTarget(expectedOut);
if (!(outTarget instanceof OutputFile)) {
fail("Target " + outTarget + " is not an output");
- assertSame(ruleTarget, ((OutputFile) outTarget).getGeneratingRule());
+ assertThat(((OutputFile) outTarget).getGeneratingRule()).isSameAs(ruleTarget);
// This ensures that the output artifact is wired up in the action graph
getConfiguredTarget(expectedOut);
}
}
Collection<OutputFile> outs = ruleTarget.getOutputFiles();
- assertEquals("Mismatched outputs: " + outs, expectedOuts.length, outs.size());
+ assertWithMessage("Mismatched outputs: " + outs)
+ .that(outs.size())
+ .isEqualTo(expectedOuts.length);
}
/**
* Asserts that there exists a configured target file for the given label.
*/
protected void assertConfiguredTargetExists(String label) throws Exception {
- assertNotNull(getFileConfiguredTarget(label));
+ assertThat(getFileConfiguredTarget(label)).isNotNull();
}
/**
@@ -944,10 +944,9 @@ public abstract class BuildViewTestCase extends FoundationTestCase {
*/
protected void assertSameGeneratingAction(String labelA, String labelB)
throws Exception {
- assertSame(
- "Action for " + labelA + " did not match " + labelB,
- getGeneratingActionForLabel(labelA),
- getGeneratingActionForLabel(labelB));
+ assertWithMessage("Action for " + labelA + " did not match " + labelB)
+ .that(getGeneratingActionForLabel(labelB))
+ .isSameAs(getGeneratingActionForLabel(labelA));
}
protected Artifact getSourceArtifact(PathFragment rootRelativePath, Root root) {
@@ -1248,14 +1247,14 @@ public abstract class BuildViewTestCase extends FoundationTestCase {
String... expectedMessages) throws Exception{
ConfiguredTarget target = getConfiguredTarget(targetName);
if (expectedError) {
- assertTrue(view.hasErrors(target));
+ assertThat(view.hasErrors(target)).isTrue();
for (String expectedMessage : expectedMessages) {
String message = "in srcs attribute of " + ruleType + " rule " + targetName + ": "
+ expectedMessage;
assertContainsEvent(message);
}
} else {
- assertFalse(view.hasErrors(target));
+ assertThat(view.hasErrors(target)).isFalse();
for (String expectedMessage : expectedMessages) {
String message = "in srcs attribute of " + ruleType + " rule " + target.getLabel() + ": "
+ expectedMessage;
@@ -1824,7 +1823,7 @@ public abstract class BuildViewTestCase extends FoundationTestCase {
ConfiguredTarget target = getConfiguredTarget(targetLabel);
List<Action> actions = getExtraActionActions(target);
- assertNotNull(actions);
+ assertThat(actions).isNotNull();
assertThat(actions).hasSize(2);
ExtraAction extraAction = null;
@@ -1836,15 +1835,16 @@ public abstract class BuildViewTestCase extends FoundationTestCase {
}
}
- assertNotNull(actions.toString(), extraAction);
+ assertWithMessage(actions.toString()).that(extraAction).isNotNull();
Action pseudoAction = extraAction.getShadowedAction();
assertThat(pseudoAction).isInstanceOf(PseudoAction.class);
- assertEquals(
- String.format("%s%s.extra_action_dummy", targetConfig.getGenfilesFragment(),
- convertLabelToPath(targetLabel)),
- pseudoAction.getPrimaryOutput().getExecPathString());
+ assertThat(pseudoAction.getPrimaryOutput().getExecPathString())
+ .isEqualTo(
+ String.format(
+ "%s%s.extra_action_dummy",
+ targetConfig.getGenfilesFragment(), convertLabelToPath(targetLabel)));
return (PseudoAction<?>) pseudoAction;
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java
index c1de6b19ab..67616fa683 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java
@@ -21,7 +21,6 @@ import com.google.devtools.build.lib.rules.repository.RepositoryFunction.Reposit
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -59,7 +58,7 @@ public class DecompressorValueTest {
DecompressorDescriptor.builder().setArchivePath(zipPath).build();
fail(".baz isn't a valid suffix");
} catch (RepositoryFunctionException expected) {
- assertThat(expected.getMessage()).contains("Expected a file with a .zip, .jar,");
+ assertThat(expected).hasMessageThat().contains("Expected a file with a .zip, .jar,");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java
index d2ca3ac072..51cef7f03b 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java
@@ -15,14 +15,10 @@
package com.google.devtools.build.lib.bazel.repository;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.base.Optional;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -35,18 +31,18 @@ public class StripPrefixedPathTest {
@Test
public void testStrip() {
StripPrefixedPath result = StripPrefixedPath.maybeDeprefix("foo/bar", Optional.of("foo"));
- assertEquals(result.getPathFragment(), PathFragment.create("bar"));
- assertTrue(result.foundPrefix());
- assertFalse(result.skip());
+ assertThat(PathFragment.create("bar")).isEqualTo(result.getPathFragment());
+ assertThat(result.foundPrefix()).isTrue();
+ assertThat(result.skip()).isFalse();
result = StripPrefixedPath.maybeDeprefix("foo", Optional.of("foo"));
- assertTrue(result.skip());
+ assertThat(result.skip()).isTrue();
result = StripPrefixedPath.maybeDeprefix("bar/baz", Optional.of("foo"));
- assertFalse(result.foundPrefix());
+ assertThat(result.foundPrefix()).isFalse();
result = StripPrefixedPath.maybeDeprefix("foof/bar", Optional.of("foo"));
- assertFalse(result.foundPrefix());
+ assertThat(result.foundPrefix()).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/cache/RepositoryCacheTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/cache/RepositoryCacheTest.java
index 8a5b987397..dfcca3d6c9 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/cache/RepositoryCacheTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/cache/RepositoryCacheTest.java
@@ -14,8 +14,9 @@
package com.google.devtools.build.lib.bazel.repository.cache;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+
import com.google.common.base.Strings;
import com.google.devtools.build.lib.bazel.repository.cache.RepositoryCache.KeyType;
import com.google.devtools.build.lib.testutil.Scratch;
@@ -66,7 +67,7 @@ public class RepositoryCacheTest {
@Test
public void testNonExistentCacheValue() {
String fakeSha256 = Strings.repeat("a", 64);
- assertFalse(repositoryCache.exists(fakeSha256, KeyType.SHA256));
+ assertThat(repositoryCache.exists(fakeSha256, KeyType.SHA256)).isFalse();
}
/**
@@ -79,9 +80,8 @@ public class RepositoryCacheTest {
Path cacheEntry = KeyType.SHA256.getCachePath(contentAddressableCachePath).getChild(downloadedFileSha256);
Path cacheValue = cacheEntry.getChild(RepositoryCache.DEFAULT_CACHE_FILENAME);
- assertEquals(
- FileSystemUtils.readContent(cacheValue, Charset.defaultCharset()),
- FileSystemUtils.readContent(downloadedFile, Charset.defaultCharset()));
+ assertThat(FileSystemUtils.readContent(downloadedFile, Charset.defaultCharset()))
+ .isEqualTo(FileSystemUtils.readContent(cacheValue, Charset.defaultCharset()));
}
/**
@@ -96,9 +96,8 @@ public class RepositoryCacheTest {
Path cacheEntry = KeyType.SHA256.getCachePath(contentAddressableCachePath).getChild(downloadedFileSha256);
Path cacheValue = cacheEntry.getChild(RepositoryCache.DEFAULT_CACHE_FILENAME);
- assertEquals(
- FileSystemUtils.readContent(cacheValue, Charset.defaultCharset()),
- FileSystemUtils.readContent(downloadedFile, Charset.defaultCharset()));
+ assertThat(FileSystemUtils.readContent(downloadedFile, Charset.defaultCharset()))
+ .isEqualTo(FileSystemUtils.readContent(cacheValue, Charset.defaultCharset()));
}
/**
@@ -114,9 +113,8 @@ public class RepositoryCacheTest {
Path actualTargetPath = repositoryCache.get(downloadedFileSha256, targetPath, KeyType.SHA256);
// Check that the contents are the same.
- assertEquals(
- FileSystemUtils.readContent(actualTargetPath, Charset.defaultCharset()),
- FileSystemUtils.readContent(downloadedFile, Charset.defaultCharset()));
+ assertThat(FileSystemUtils.readContent(downloadedFile, Charset.defaultCharset()))
+ .isEqualTo(FileSystemUtils.readContent(actualTargetPath, Charset.defaultCharset()));
// Check that the returned value is stored under outputBaseExternal.
assertEquals(targetPath, actualTargetPath);
@@ -162,7 +160,7 @@ public class RepositoryCacheTest {
@Test
public void testGetChecksum() throws IOException {
String actualChecksum = RepositoryCache.getChecksum(KeyType.SHA256, downloadedFile);
- assertEquals(downloadedFileSha256, actualChecksum);
+ assertThat(actualChecksum).isEqualTo(downloadedFileSha256);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryContextTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryContextTest.java
index 4a7c7262c2..020217cb9d 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryContextTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryContextTest.java
@@ -145,21 +145,27 @@ public class SkylarkRepositoryContextTest {
context.createFile(context.path("/absolute"), "", true);
fail("Expected error on creating path outside of the repository directory");
} catch (RepositoryFunctionException ex) {
- assertThat(ex.getCause().getMessage())
+ assertThat(ex)
+ .hasCauseThat()
+ .hasMessageThat()
.isEqualTo("Cannot write outside of the repository directory for path /absolute");
}
try {
context.createFile(context.path("../somepath"), "", true);
fail("Expected error on creating path outside of the repository directory");
} catch (RepositoryFunctionException ex) {
- assertThat(ex.getCause().getMessage())
+ assertThat(ex)
+ .hasCauseThat()
+ .hasMessageThat()
.isEqualTo("Cannot write outside of the repository directory for path /somepath");
}
try {
context.createFile(context.path("foo/../../somepath"), "", true);
fail("Expected error on creating path outside of the repository directory");
} catch (RepositoryFunctionException ex) {
- assertThat(ex.getCause().getMessage())
+ assertThat(ex)
+ .hasCauseThat()
+ .hasMessageThat()
.isEqualTo("Cannot write outside of the repository directory for path /somepath");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryIntegrationTest.java
index 1ffa3bd9b7..004987d7b8 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryIntegrationTest.java
@@ -300,10 +300,13 @@ public class SkylarkRepositoryIntegrationTest extends BuildViewTestCase {
getTarget("@//:git_repo");
fail();
} catch (AssertionError expected) {
- assertThat(expected.getMessage()).contains("Failed to load Skylark extension "
- + "'@git_repo//xyz:foo.bzl'.\n"
- + "It usually happens when the repository is not defined prior to being used.\n"
- + "Maybe repository 'git_repo' was defined later in your WORKSPACE file?");
+ assertThat(expected)
+ .hasMessageThat()
+ .contains(
+ "Failed to load Skylark extension "
+ + "'@git_repo//xyz:foo.bzl'.\n"
+ + "It usually happens when the repository is not defined prior to being used.\n"
+ + "Maybe repository 'git_repo' was defined later in your WORKSPACE file?");
}
}
@@ -329,7 +332,7 @@ public class SkylarkRepositoryIntegrationTest extends BuildViewTestCase {
fail();
} catch (NoSuchPackageException e) {
// This is expected
- assertThat(e.getMessage()).contains("Could not load //external package");
+ assertThat(e).hasMessageThat().contains("Could not load //external package");
}
assertContainsEvent("missing value for mandatory attribute 'path' in 'local_repository' rule");
}
@@ -371,8 +374,9 @@ public class SkylarkRepositoryIntegrationTest extends BuildViewTestCase {
getConfiguredTarget("@foo//:bar");
fail();
} catch (AssertionError e) {
- assertThat(e.getMessage()).contains("There is already a built-in attribute 'name' "
- + "which cannot be overridden");
+ assertThat(e)
+ .hasMessageThat()
+ .contains("There is already a built-in attribute 'name' " + "which cannot be overridden");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
index f077c5517b..3518fbc216 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
@@ -196,7 +196,8 @@ public class AndroidNdkRepositoryTest extends BuildViewTestCase {
getTarget("@androidndk//:files");
fail("android_ndk_repository should have failed due to missing NDK platforms dir.");
} catch (BuildFileNotFoundException e) {
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.contains(
"Expected directory at /ndk/platforms but it is not a directory or it does not "
+ "exist.");
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleCommandSubstitutionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleCommandSubstitutionTest.java
index 2d57b3a10a..c4c9a66978 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleCommandSubstitutionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleCommandSubstitutionTest.java
@@ -15,7 +15,7 @@
package com.google.devtools.build.lib.bazel.rules.genrule;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.base.Joiner;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
@@ -59,10 +59,9 @@ public class GenRuleCommandSubstitutionTest extends BuildViewTestCase {
command = m.group("command");
}
- assertEquals(
- "Expected command to be \"" + expected + "\", but found \"" + command + "\"",
- expected,
- command);
+ assertWithMessage("Expected command to be \"" + expected + "\", but found \"" + command + "\"")
+ .that(command)
+ .isEqualTo(expected);
}
private void assertExpansionFails(String expectedErrorSuffix, String genrule) throws Exception {
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleConfiguredTargetTest.java b/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleConfiguredTargetTest.java
index 7d323807d4..154743bc52 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleConfiguredTargetTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleConfiguredTargetTest.java
@@ -18,17 +18,12 @@ import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.TestConstants.GENRULE_SETUP;
import static com.google.devtools.build.lib.testutil.TestConstants.GENRULE_SETUP_PATH;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
-import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
@@ -106,7 +101,7 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
createFiles();
ConfiguredTarget z = getConfiguredTarget("//hello:z");
Artifact y = getOnlyElement(getFilesToBuild(z));
- assertEquals(PathFragment.create("hello/x/y"), y.getRootRelativePath());
+ assertThat(y.getRootRelativePath()).isEqualTo(PathFragment.create("hello/x/y"));
}
@Test
@@ -115,8 +110,8 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
ConfiguredTarget z = getConfiguredTarget("//hello:w");
List<Artifact> files = getFilesToBuild(z).toList();
assertThat(files).hasSize(2);
- assertEquals(PathFragment.create("hello/a/b"), files.get(0).getRootRelativePath());
- assertEquals(PathFragment.create("hello/c/d"), files.get(1).getRootRelativePath());
+ assertThat(files.get(0).getRootRelativePath()).isEqualTo(PathFragment.create("hello/a/b"));
+ assertThat(files.get(1).getRootRelativePath()).isEqualTo(PathFragment.create("hello/c/d"));
}
@Test
@@ -161,16 +156,14 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
Artifact ignoreMeArtifact = getFileConfiguredTarget("//genrule1:ignore_me.txt").getArtifact();
Artifact genruleSetupArtifact = getFileConfiguredTarget(GENRULE_SETUP).getArtifact();
- assertNotNull(shellAction);
- assertEquals(
- Sets.newHashSet(ignoreMeArtifact, genruleSetupArtifact),
- Sets.newHashSet(shellAction.getInputs()));
- assertEquals(Sets.newHashSet(messageArtifact), Sets.newHashSet(shellAction.getOutputs()));
+ assertThat(shellAction).isNotNull();
+ assertThat(shellAction.getInputs()).containsExactly(ignoreMeArtifact, genruleSetupArtifact);
+ assertThat(shellAction.getOutputs()).containsExactly(messageArtifact);
String expected = "echo \"Hello, world.\" >" + messageArtifact.getExecPathString();
- assertEquals(
- targetConfig.getShellExecutable().getPathString(), shellAction.getArguments().get(0));
- assertEquals("-c", shellAction.getArguments().get(1));
+ assertThat(shellAction.getArguments().get(0))
+ .isEqualTo(targetConfig.getShellExecutable().getPathString());
+ assertThat(shellAction.getArguments().get(1)).isEqualTo("-c");
assertCommandEquals(expected, shellAction.getArguments().get(2));
}
@@ -199,12 +192,11 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
SpawnAction shellAction = (SpawnAction) getGeneratingAction(farewellArtifact);
// inputs = { "goodbye.txt", "//genrule1:message.txt" }
- assertEquals(
- Sets.newHashSet(goodbyeArtifact, messageArtifact, genruleSetupArtifact),
- Sets.newHashSet(shellAction.getInputs()));
+ assertThat(shellAction.getInputs())
+ .containsExactly(goodbyeArtifact, messageArtifact, genruleSetupArtifact);
// outputs = { "farewell.txt" }
- assertEquals(Sets.newHashSet(farewellArtifact), Sets.newHashSet(shellAction.getOutputs()));
+ assertThat(shellAction.getOutputs()).containsExactly(farewellArtifact);
String expected =
"echo "
@@ -236,10 +228,10 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
FileConfiguredTarget bazOutTarget = getFileConfiguredTarget("//foo:baz_out.txt");
Action bazAction = getGeneratingAction(bazOutTarget.getArtifact());
Artifact barOut = bazAction.getInputs().iterator().next();
- assertTrue(barOut.getExecPath().endsWith(PathFragment.create("foo/bar_out.txt")));
+ assertThat(barOut.getExecPath().endsWith(PathFragment.create("foo/bar_out.txt"))).isTrue();
Action barAction = getGeneratingAction(barOut);
Artifact barIn = barAction.getInputs().iterator().next();
- assertTrue(barIn.getExecPath().endsWith(PathFragment.create("foo/bar_in.txt")));
+ assertThat(barIn.getExecPath().endsWith(PathFragment.create("foo/bar_in.txt"))).isTrue();
}
/** Ensure that variable $(@D) gets expanded correctly in the genrule cmd. */
@@ -279,11 +271,11 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
getConfiguredTarget("//foo:bar");
Artifact barOut = bazAction.getInputs().iterator().next();
- assertTrue(barOut.getExecPath().endsWith(PathFragment.create("foo/bar/bar_out.txt")));
+ assertThat(barOut.getExecPath().endsWith(PathFragment.create("foo/bar/bar_out.txt"))).isTrue();
SpawnAction barAction = (SpawnAction) getGeneratingAction(barOut);
String barExpected = "touch " + barOut.getExecPath().getParentDirectory().getPathString();
assertCommandEquals(barExpected, barAction.getArguments().get(2));
- assertFalse(bazExpected.equals(barExpected));
+ assertThat(bazExpected.equals(barExpected)).isFalse();
}
/** Ensure that variable $(CC) gets expanded correctly in the genrule cmd. */
@@ -383,12 +375,10 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
" outs = ['goodbye.txt'],",
" message = 'Generating message',",
" cmd = 'echo \"Goodbye, world.\" >goodbye.txt')");
- assertEquals(
- "Executing genrule //genrule3:hello_world",
- getSpawnAction("//genrule3:hello_world").getProgressMessage());
- assertEquals(
- "Generating message //genrule3:goodbye_world",
- getSpawnAction("//genrule3:goodbye_world").getProgressMessage());
+ assertThat(getSpawnAction("//genrule3:hello_world").getProgressMessage())
+ .isEqualTo("Executing genrule //genrule3:hello_world");
+ assertThat(getSpawnAction("//genrule3:goodbye_world").getProgressMessage())
+ .isEqualTo("Generating message //genrule3:goodbye_world");
}
/** Ensure that labels from binary targets expand to the executable */
@@ -420,11 +410,10 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
" cmd=':',",
" output_to_bindir=0)");
- assertEquals(
- getBinArtifact("bin.out", "//x:bin"), getFileConfiguredTarget("//x:bin.out").getArtifact());
- assertEquals(
- getGenfilesArtifact("genfiles.out", "//x:genfiles"),
- getFileConfiguredTarget("//x:genfiles.out").getArtifact());
+ assertThat(getFileConfiguredTarget("//x:bin.out").getArtifact())
+ .isEqualTo(getBinArtifact("bin.out", "//x:bin"));
+ assertThat(getFileConfiguredTarget("//x:genfiles.out").getArtifact())
+ .isEqualTo(getGenfilesArtifact("genfiles.out", "//x:genfiles"));
}
@Test
@@ -440,18 +429,14 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
" cmd=':',",
" output_to_bindir=0)");
- assertEquals(
- getBinArtifact("bin_a.out", "//x:bin"),
- getFileConfiguredTarget("//x:bin_a.out").getArtifact());
- assertEquals(
- getBinArtifact("bin_b.out", "//x:bin"),
- getFileConfiguredTarget("//x:bin_b.out").getArtifact());
- assertEquals(
- getGenfilesArtifact("genfiles_a.out", "//x:genfiles"),
- getFileConfiguredTarget("//x:genfiles_a.out").getArtifact());
- assertEquals(
- getGenfilesArtifact("genfiles_b.out", "//x:genfiles"),
- getFileConfiguredTarget("//x:genfiles_b.out").getArtifact());
+ assertThat(getFileConfiguredTarget("//x:bin_a.out").getArtifact())
+ .isEqualTo(getBinArtifact("bin_a.out", "//x:bin"));
+ assertThat(getFileConfiguredTarget("//x:bin_b.out").getArtifact())
+ .isEqualTo(getBinArtifact("bin_b.out", "//x:bin"));
+ assertThat(getFileConfiguredTarget("//x:genfiles_a.out").getArtifact())
+ .isEqualTo(getGenfilesArtifact("genfiles_a.out", "//x:genfiles"));
+ assertThat(getFileConfiguredTarget("//x:genfiles_b.out").getArtifact())
+ .isEqualTo(getGenfilesArtifact("genfiles_b.out", "//x:genfiles"));
}
@Test
@@ -540,7 +525,7 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
" outs = ['turtle'],",
" executable = 1,",
" cmd = 'touch $(OUTS)')");
- assertEquals("turtle", getExecutable(turtle).getExecPath().getBaseName());
+ assertThat(getExecutable(turtle).getExecPath().getBaseName()).isEqualTo("turtle");
}
@Test
@@ -553,7 +538,7 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
" srcs = ['Turtle.java'],",
" outs = ['debugdata.txt'],",
" cmd = 'touch $(OUTS)')");
- assertNull(getExecutable(turtle));
+ assertThat(getExecutable(turtle)).isNull();
}
@Test
@@ -566,7 +551,7 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
" srcs = ['Turtle.java'],",
" outs = ['turtle', 'debugdata.txt'],",
" cmd = 'touch $(OUTS)')");
- assertNull(getExecutable(turtle));
+ assertThat(getExecutable(turtle)).isNull();
}
@Test
@@ -624,7 +609,7 @@ public class GenRuleConfiguredTargetTest extends BuildViewTestCase {
private void assertStamped(ConfiguredTarget target) throws Exception {
Artifact out = Iterables.getFirst(getFilesToBuild(target), null);
List<String> inputs = ActionsTestUtil.baseArtifactNames(getGeneratingAction(out).getInputs());
- assertThat(inputs).containsAllIn(ImmutableList.of("build-info.txt", "build-changelist.txt"));
+ assertThat(inputs).containsAllOf("build-info.txt", "build-changelist.txt");
}
private void assertNotStamped(ConfiguredTarget target) throws Exception {
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemanticsTest.java b/src/test/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemanticsTest.java
index 6758e80089..080bdd9992 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemanticsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/rules/java/BazelJavaSemanticsTest.java
@@ -14,10 +14,9 @@
package com.google.devtools.build.lib.bazel.rules.java;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -30,21 +29,18 @@ public class BazelJavaSemanticsTest {
@Test
public void testFindingResources() {
BazelJavaSemantics semantics = BazelJavaSemantics.INSTANCE;
- assertEquals(
- PathFragment.EMPTY_FRAGMENT,
- semantics.getDefaultJavaResourcePath(PathFragment.create("x/y/src/main/resources")));
- assertEquals(
- PathFragment.create("foo"),
- semantics.getDefaultJavaResourcePath(PathFragment.create("x/y/src/main/resources/foo")));
- assertEquals(
- PathFragment.create("foo"),
- semantics.getDefaultJavaResourcePath(
- PathFragment.create("java/x/y/src/main/resources/foo")));
- assertEquals(
- PathFragment.create("foo/java/bar"),
- semantics.getDefaultJavaResourcePath(PathFragment.create("java/foo/java/bar")));
- assertEquals(
- PathFragment.create("foo/java/bar"),
- semantics.getDefaultJavaResourcePath(PathFragment.create("javatests/foo/java/bar")));
+ assertThat(semantics.getDefaultJavaResourcePath(PathFragment.create("x/y/src/main/resources")))
+ .isEqualTo(PathFragment.EMPTY_FRAGMENT);
+ assertThat(
+ semantics.getDefaultJavaResourcePath(PathFragment.create("x/y/src/main/resources/foo")))
+ .isEqualTo(PathFragment.create("foo"));
+ assertThat(
+ semantics.getDefaultJavaResourcePath(
+ PathFragment.create("java/x/y/src/main/resources/foo")))
+ .isEqualTo(PathFragment.create("foo"));
+ assertThat(semantics.getDefaultJavaResourcePath(PathFragment.create("java/foo/java/bar")))
+ .isEqualTo(PathFragment.create("foo/java/bar"));
+ assertThat(semantics.getDefaultJavaResourcePath(PathFragment.create("javatests/foo/java/bar")))
+ .isEqualTo(PathFragment.create("foo/java/bar"));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/buildtool/SymlinkForestTest.java b/src/test/java/com/google/devtools/build/lib/buildtool/SymlinkForestTest.java
index cd2b3b96fc..853873386b 100644
--- a/src/test/java/com/google/devtools/build/lib/buildtool/SymlinkForestTest.java
+++ b/src/test/java/com/google/devtools/build/lib/buildtool/SymlinkForestTest.java
@@ -14,11 +14,8 @@
package com.google.devtools.build.lib.buildtool;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.vfs.FileSystemUtils.createDirectoryAndParents;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@@ -114,22 +111,24 @@ public class SymlinkForestTest {
@Test
public void testLongestPathPrefix() {
PathFragment a = PathFragment.create("A");
- assertEquals(a, longestPathPrefix("A/b", "A", "B")); // simple parent
- assertEquals(a, longestPathPrefix("A", "A", "B")); // self
- assertEquals(a.getRelative("B"), longestPathPrefix("A/B/c", "A", "A/B")); // want longest
- assertNull(longestPathPrefix("C/b", "A", "B")); // not found in other parents
- assertNull(longestPathPrefix("A", "A/B", "B")); // not found in child
- assertEquals(a.getRelative("B/C"), longestPathPrefix("A/B/C/d/e/f.h", "A/B/C", "B/C/d"));
- assertEquals(PathFragment.EMPTY_FRAGMENT, longestPathPrefix("A/f.h", "", "B/C/d"));
+ assertThat(longestPathPrefix("A/b", "A", "B")).isEqualTo(a); // simple parent
+ assertThat(longestPathPrefix("A", "A", "B")).isEqualTo(a); // self
+ assertThat(longestPathPrefix("A/B/c", "A", "A/B"))
+ .isEqualTo(a.getRelative("B")); // want longest
+ assertThat(longestPathPrefix("C/b", "A", "B")).isNull(); // not found in other parents
+ assertThat(longestPathPrefix("A", "A/B", "B")).isNull(); // not found in child
+ assertThat(longestPathPrefix("A/B/C/d/e/f.h", "A/B/C", "B/C/d"))
+ .isEqualTo(a.getRelative("B/C"));
+ assertThat(longestPathPrefix("A/f.h", "", "B/C/d")).isEqualTo(PathFragment.EMPTY_FRAGMENT);
}
@Test
public void testDeleteTreesBelowNotPrefixed() throws IOException {
createTestDirectoryTree();
SymlinkForest.deleteTreesBelowNotPrefixed(topDir, new String[]{"file-"});
- assertTrue(file1.exists());
- assertTrue(file2.exists());
- assertFalse(aDir.exists());
+ assertThat(file1.exists()).isTrue();
+ assertThat(file2.exists()).isTrue();
+ assertThat(aDir.exists()).isFalse();
}
private PackageIdentifier createPkg(Path rootA, Path rootB, String pkg) throws IOException {
@@ -159,12 +158,12 @@ public class SymlinkForestTest {
}
private void assertLinksTo(Path fromRoot, Path toRoot) throws IOException {
- assertTrue("stat: " + fromRoot.stat(), fromRoot.isSymbolicLink());
- assertEquals(toRoot.asFragment(), fromRoot.readSymbolicLink());
+ assertWithMessage("stat: " + fromRoot.stat()).that(fromRoot.isSymbolicLink()).isTrue();
+ assertThat(fromRoot.readSymbolicLink()).isEqualTo(toRoot.asFragment());
}
private void assertIsDir(Path root, String relpart) {
- assertTrue(root.getRelative(relpart).isDirectory(Symlinks.NOFOLLOW));
+ assertThat(root.getRelative(relpart).isDirectory(Symlinks.NOFOLLOW)).isTrue();
}
@Test
@@ -243,7 +242,7 @@ public class SymlinkForestTest {
new SymlinkForest(packageRootMap, linkRoot, TestConstants.PRODUCT_NAME, "wsname")
.plantSymlinkForest();
- assertFalse(linkRoot.getRelative(Label.EXTERNAL_PATH_PREFIX + "/y/file").exists());
+ assertThat(linkRoot.getRelative(Label.EXTERNAL_PATH_PREFIX + "/y/file").exists()).isFalse();
assertLinksTo(
linkRoot.getRelative(Label.EXTERNAL_PATH_PREFIX + "/y/w"), rootY.getRelative("w"));
assertLinksTo(
diff --git a/src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java b/src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java
index 74e1248723..7e34cc64e8 100644
--- a/src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java
+++ b/src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java
@@ -14,11 +14,9 @@
package com.google.devtools.build.lib.cmdline;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import com.google.common.testing.EqualsTester;
import com.google.devtools.build.lib.testutil.TestUtils;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.regex.Pattern;
@@ -40,24 +38,24 @@ public class LabelTest {
public void testAbsolute() throws Exception {
{
Label l = Label.parseAbsolute("//foo/bar:baz");
- assertEquals("foo/bar", l.getPackageName());
- assertEquals("baz", l.getName());
+ assertThat(l.getPackageName()).isEqualTo("foo/bar");
+ assertThat(l.getName()).isEqualTo("baz");
}
{
Label l = Label.parseAbsolute("//foo/bar");
- assertEquals("foo/bar", l.getPackageName());
- assertEquals("bar", l.getName());
+ assertThat(l.getPackageName()).isEqualTo("foo/bar");
+ assertThat(l.getName()).isEqualTo("bar");
}
{
Label l = Label.parseAbsolute("//:bar");
- assertEquals("", l.getPackageName());
- assertEquals("bar", l.getName());
+ assertThat(l.getPackageName()).isEmpty();
+ assertThat(l.getName()).isEqualTo("bar");
}
{
Label l = Label.parseAbsolute("@foo");
- assertEquals("@foo", l.getPackageIdentifier().getRepository().getName());
- assertEquals("", l.getPackageName());
- assertEquals("foo", l.getName());
+ assertThat(l.getPackageIdentifier().getRepository().getName()).isEqualTo("@foo");
+ assertThat(l.getPackageName()).isEmpty();
+ assertThat(l.getName()).isEqualTo("foo");
}
}
@@ -67,14 +65,15 @@ public class LabelTest {
@Test
public void testLabelResolution() throws Exception {
- assertEquals("//absolute:label", parseCommandLine("//absolute:label", ""));
- assertEquals("//absolute:label", parseCommandLine("//absolute:label", "absolute"));
- assertEquals("//absolute:label", parseCommandLine(":label", "absolute"));
- assertEquals("//absolute:label", parseCommandLine("label", "absolute"));
- assertEquals("//absolute:label", parseCommandLine("absolute:label", ""));
- assertEquals("//absolute/path:label", parseCommandLine("path:label", "absolute"));
- assertEquals("//absolute/path:label/path", parseCommandLine("path:label/path", "absolute"));
- assertEquals("//absolute:label/path", parseCommandLine("label/path", "absolute"));
+ assertThat(parseCommandLine("//absolute:label", "")).isEqualTo("//absolute:label");
+ assertThat(parseCommandLine("//absolute:label", "absolute")).isEqualTo("//absolute:label");
+ assertThat(parseCommandLine(":label", "absolute")).isEqualTo("//absolute:label");
+ assertThat(parseCommandLine("label", "absolute")).isEqualTo("//absolute:label");
+ assertThat(parseCommandLine("absolute:label", "")).isEqualTo("//absolute:label");
+ assertThat(parseCommandLine("path:label", "absolute")).isEqualTo("//absolute/path:label");
+ assertThat(parseCommandLine("path:label/path", "absolute"))
+ .isEqualTo("//absolute/path:label/path");
+ assertThat(parseCommandLine("label/path", "absolute")).isEqualTo("//absolute:label/path");
}
@Test
@@ -101,16 +100,16 @@ public class LabelTest {
public void testGetRelativeWithAbsoluteLabel() throws Exception {
Label base = Label.parseAbsolute("//foo/bar:baz");
Label l = base.getRelative("//p1/p2:target");
- assertEquals("p1/p2", l.getPackageName());
- assertEquals("target", l.getName());
+ assertThat(l.getPackageName()).isEqualTo("p1/p2");
+ assertThat(l.getName()).isEqualTo("target");
}
@Test
public void testGetRelativeWithRelativeLabel() throws Exception {
Label base = Label.parseAbsolute("//foo/bar:baz");
Label l = base.getRelative(":quux");
- assertEquals("foo/bar", l.getPackageName());
- assertEquals("quux", l.getName());
+ assertThat(l.getPackageName()).isEqualTo("foo/bar");
+ assertThat(l.getName()).isEqualTo("quux");
}
@Test
@@ -149,9 +148,10 @@ public class LabelTest {
Label relative = base.getRelative("@remote//x:y");
- assertEquals(RepositoryName.create("@remote"), relative.getPackageIdentifier().getRepository());
- assertEquals(PathFragment.create("x"), relative.getPackageFragment());
- assertEquals("y", relative.getName());
+ assertThat(relative.getPackageIdentifier().getRepository())
+ .isEqualTo(RepositoryName.create("@remote"));
+ assertThat(relative.getPackageFragment()).isEqualTo(PathFragment.create("x"));
+ assertThat(relative.getName()).isEqualTo("y");
}
@Test
@@ -161,9 +161,10 @@ public class LabelTest {
Label relative = base.getRelative("//x:y");
- assertEquals(packageId.getRepository(), relative.getPackageIdentifier().getRepository());
- assertEquals(PathFragment.create("x"), relative.getPackageFragment());
- assertEquals("y", relative.getName());
+ assertThat(relative.getPackageIdentifier().getRepository())
+ .isEqualTo(packageId.getRepository());
+ assertThat(relative.getPackageFragment()).isEqualTo(PathFragment.create("x"));
+ assertThat(relative.getName()).isEqualTo("y");
}
@Test
@@ -173,9 +174,10 @@ public class LabelTest {
Label relative = base.getRelative(":y");
- assertEquals(packageId.getRepository(), relative.getPackageIdentifier().getRepository());
- assertEquals(PathFragment.create("foo"), relative.getPackageFragment());
- assertEquals("y", relative.getName());
+ assertThat(relative.getPackageIdentifier().getRepository())
+ .isEqualTo(packageId.getRepository());
+ assertThat(relative.getPackageFragment()).isEqualTo(PathFragment.create("foo"));
+ assertThat(relative.getName()).isEqualTo("y");
}
@Test
@@ -186,9 +188,9 @@ public class LabelTest {
Label relative = base.getRelative("//conditions:default");
PackageIdentifier expected = PackageIdentifier.createInMainRepo("conditions");
- assertEquals(expected.getRepository(), relative.getPackageIdentifier().getRepository());
- assertEquals(expected.getPackageFragment(), relative.getPackageFragment());
- assertEquals("default", relative.getName());
+ assertThat(relative.getPackageIdentifier().getRepository()).isEqualTo(expected.getRepository());
+ assertThat(relative.getPackageFragment()).isEqualTo(expected.getPackageFragment());
+ assertThat(relative.getName()).isEqualTo("default");
}
@Test
@@ -198,9 +200,10 @@ public class LabelTest {
Label relative = base.getRelative("@//x:y");
- assertEquals(RepositoryName.create("@"), relative.getPackageIdentifier().getRepository());
- assertEquals(PathFragment.create("x"), relative.getPackageFragment());
- assertEquals("y", relative.getName());
+ assertThat(relative.getPackageIdentifier().getRepository())
+ .isEqualTo(RepositoryName.create("@"));
+ assertThat(relative.getPackageFragment()).isEqualTo(PathFragment.create("x"));
+ assertThat(relative.getName()).isEqualTo("y");
}
@Test
@@ -210,18 +213,18 @@ public class LabelTest {
Label mainBase = Label.parseAbsolute("@//foo/bar:baz");
Label externalTarget = Label.parseAbsolute("//external:target");
Label l = defaultBase.resolveRepositoryRelative(externalTarget);
- assertTrue(l.getPackageIdentifier().getRepository().isMain());
- assertEquals("external", l.getPackageName());
- assertEquals("target", l.getName());
- assertEquals(l, repoBase.resolveRepositoryRelative(externalTarget));
- assertEquals(l, mainBase.resolveRepositoryRelative(externalTarget));
+ assertThat(l.getPackageIdentifier().getRepository().isMain()).isTrue();
+ assertThat(l.getPackageName()).isEqualTo("external");
+ assertThat(l.getName()).isEqualTo("target");
+ assertThat(repoBase.resolveRepositoryRelative(externalTarget)).isEqualTo(l);
+ assertThat(mainBase.resolveRepositoryRelative(externalTarget)).isEqualTo(l);
}
@Test
public void testFactory() throws Exception {
Label l = Label.create("foo/bar", "quux");
- assertEquals("foo/bar", l.getPackageName());
- assertEquals("quux", l.getName());
+ assertThat(l.getPackageName()).isEqualTo("foo/bar");
+ assertThat(l.getName()).isEqualTo("quux");
}
@Test
@@ -231,15 +234,10 @@ public class LabelTest {
Label l2 = Label.parseAbsolute("//foo/bar:baz");
Label l3 = Label.parseAbsolute("//foo/bar:quux");
- assertEquals(l1, l1);
- assertEquals(l1, l2);
- assertEquals(l2, l1);
- assertEquals(l1, l2);
-
- assertFalse(l3.equals(l1));
- assertFalse(l1.equals(l3));
-
- assertEquals(l1.hashCode(), l2.hashCode());
+ new EqualsTester()
+ .addEqualityGroup(l1, l2)
+ .addEqualityGroup(l3)
+ .testEquals();
}
@Test
@@ -247,15 +245,15 @@ public class LabelTest {
{
String s = "@//foo/bar:baz";
Label l = Label.parseAbsolute(s);
- assertEquals("//foo/bar:baz", l.toString());
+ assertThat(l.toString()).isEqualTo("//foo/bar:baz");
}
{
Label l = Label.parseAbsolute("//foo/bar");
- assertEquals("//foo/bar:bar", l.toString());
+ assertThat(l.toString()).isEqualTo("//foo/bar:bar");
}
{
Label l = Label.parseAbsolute("@foo");
- assertEquals("@foo//:foo", l.toString());
+ assertThat(l.toString()).isEqualTo("@foo//:foo");
}
}
@@ -293,7 +291,7 @@ public class LabelTest {
Label.parseAbsolute(label);
fail("Label '" + label + "' did not contain a syntax error");
} catch (LabelSyntaxException e) {
- assertThat(e.getMessage()).containsMatch(Pattern.quote(expectedError));
+ assertThat(e).hasMessageThat().containsMatch(Pattern.quote(expectedError));
}
}
@@ -342,9 +340,7 @@ public class LabelTest {
@Test
public void testTrailingDotSegment() throws Exception {
- assertEquals(Label
- .parseAbsolute("//foo:dir/."), Label
- .parseAbsolute("//foo:dir"));
+ assertThat(Label.parseAbsolute("//foo:dir")).isEqualTo(Label.parseAbsolute("//foo:dir/."));
}
@Test
@@ -427,22 +423,22 @@ public class LabelTest {
private void checkSerialization(String labelString, int expectedSize) throws Exception {
Label a = Label.parseAbsolute(labelString);
byte[] sa = TestUtils.serializeObject(a);
- assertEquals(expectedSize, sa.length);
+ assertThat(sa).hasLength(expectedSize);
Label a2 = (Label) TestUtils.deserializeObject(sa);
- assertEquals(a, a2);
+ assertThat(a2).isEqualTo(a);
}
@Test
public void testRepoLabel() throws Exception {
Label label = Label.parseAbsolute("@foo//bar/baz:bat/boo");
- assertEquals("@foo//bar/baz:bat/boo", label.toString());
+ assertThat(label.toString()).isEqualTo("@foo//bar/baz:bat/boo");
}
@Test
public void testNoRepo() throws Exception {
Label label = Label.parseAbsolute("//bar/baz:bat/boo");
- assertEquals("//bar/baz:bat/boo", label.toString());
+ assertThat(label.toString()).isEqualTo("//bar/baz:bat/boo");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/cmdline/LabelValidatorTest.java b/src/test/java/com/google/devtools/build/lib/cmdline/LabelValidatorTest.java
index 17e6ba5a12..2156ddf84d 100644
--- a/src/test/java/com/google/devtools/build/lib/cmdline/LabelValidatorTest.java
+++ b/src/test/java/com/google/devtools/build/lib/cmdline/LabelValidatorTest.java
@@ -14,10 +14,8 @@
package com.google.devtools.build.lib.cmdline;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.devtools.build.lib.cmdline.LabelValidator.PackageAndTarget;
import org.junit.Test;
@@ -41,115 +39,119 @@ public class LabelValidatorTest {
@Test
public void testValidatePackageName() throws Exception {
// OK:
- assertNull(LabelValidator.validatePackageName("foo"));
- assertNull(LabelValidator.validatePackageName("Foo"));
- assertNull(LabelValidator.validatePackageName("FOO"));
- assertNull(LabelValidator.validatePackageName("foO"));
- assertNull(LabelValidator.validatePackageName("foo-bar"));
- assertNull(LabelValidator.validatePackageName("Foo-Bar"));
- assertNull(LabelValidator.validatePackageName("FOO-BAR"));
- assertNull(LabelValidator.validatePackageName("bar.baz"));
- assertNull(LabelValidator.validatePackageName("a/..b"));
- assertNull(LabelValidator.validatePackageName("a/.b"));
- assertNull(LabelValidator.validatePackageName("a/b."));
- assertNull(LabelValidator.validatePackageName("a/b.."));
- assertNull(LabelValidator.validatePackageName("a$( )/b.."));
+ assertThat(LabelValidator.validatePackageName("foo")).isNull();
+ assertThat(LabelValidator.validatePackageName("Foo")).isNull();
+ assertThat(LabelValidator.validatePackageName("FOO")).isNull();
+ assertThat(LabelValidator.validatePackageName("foO")).isNull();
+ assertThat(LabelValidator.validatePackageName("foo-bar")).isNull();
+ assertThat(LabelValidator.validatePackageName("Foo-Bar")).isNull();
+ assertThat(LabelValidator.validatePackageName("FOO-BAR")).isNull();
+ assertThat(LabelValidator.validatePackageName("bar.baz")).isNull();
+ assertThat(LabelValidator.validatePackageName("a/..b")).isNull();
+ assertThat(LabelValidator.validatePackageName("a/.b")).isNull();
+ assertThat(LabelValidator.validatePackageName("a/b.")).isNull();
+ assertThat(LabelValidator.validatePackageName("a/b..")).isNull();
+ assertThat(LabelValidator.validatePackageName("a$( )/b..")).isNull();
// Bad:
- assertEquals(
- "package names may not start with '/'", LabelValidator.validatePackageName("/foo"));
- assertEquals("package names may not end with '/'", LabelValidator.validatePackageName("foo/"));
- assertEquals(LabelValidator.PACKAGE_NAME_ERROR, LabelValidator.validatePackageName("foo:bar"));
- assertEquals(
- LabelValidator.PACKAGE_NAME_ERROR, LabelValidator.validatePackageName("baz@12345"));
-
- assertEquals(
- LabelValidator.PACKAGE_NAME_DOT_ERROR, LabelValidator.validatePackageName("bar/../baz"));
- assertEquals(
- LabelValidator.PACKAGE_NAME_DOT_ERROR, LabelValidator.validatePackageName("bar/.."));
- assertEquals(
- LabelValidator.PACKAGE_NAME_DOT_ERROR, LabelValidator.validatePackageName("../bar"));
- assertEquals(
- LabelValidator.PACKAGE_NAME_DOT_ERROR, LabelValidator.validatePackageName("bar/..."));
-
- assertEquals(
- LabelValidator.PACKAGE_NAME_DOT_ERROR, LabelValidator.validatePackageName("bar/./baz"));
- assertEquals(
- LabelValidator.PACKAGE_NAME_DOT_ERROR, LabelValidator.validatePackageName("bar/."));
- assertEquals(
- LabelValidator.PACKAGE_NAME_DOT_ERROR, LabelValidator.validatePackageName("./bar"));
+ assertThat(LabelValidator.validatePackageName("/foo"))
+ .isEqualTo("package names may not start with '/'");
+ assertThat(LabelValidator.validatePackageName("foo/"))
+ .isEqualTo("package names may not end with '/'");
+ assertThat(LabelValidator.validatePackageName("foo:bar"))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_ERROR);
+ assertThat(LabelValidator.validatePackageName("baz@12345"))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_ERROR);
+
+ assertThat(LabelValidator.validatePackageName("bar/../baz"))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_DOT_ERROR);
+ assertThat(LabelValidator.validatePackageName("bar/.."))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_DOT_ERROR);
+ assertThat(LabelValidator.validatePackageName("../bar"))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_DOT_ERROR);
+ assertThat(LabelValidator.validatePackageName("bar/..."))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_DOT_ERROR);
+
+ assertThat(LabelValidator.validatePackageName("bar/./baz"))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_DOT_ERROR);
+ assertThat(LabelValidator.validatePackageName("bar/."))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_DOT_ERROR);
+ assertThat(LabelValidator.validatePackageName("./bar"))
+ .isEqualTo(LabelValidator.PACKAGE_NAME_DOT_ERROR);
}
@Test
public void testValidateTargetName() throws Exception {
- assertNull(LabelValidator.validateTargetName("foo"));
- assertNull(LabelValidator.validateTargetName("foo+bar"));
- assertNull(LabelValidator.validateTargetName("foo_bar"));
- assertNull(LabelValidator.validateTargetName("foo=bar"));
- assertNull(LabelValidator.validateTargetName("foo-bar"));
- assertNull(LabelValidator.validateTargetName("foo.bar"));
- assertNull(LabelValidator.validateTargetName("foo@bar"));
- assertNull(LabelValidator.validateTargetName("foo~bar"));
- assertNull(LabelValidator.validateTargetName("foo#bar"));
-
- assertEquals("target names may not end with '/'",
- LabelValidator.validateTargetName("foo/"));
- assertEquals("target names may not contain ':'",
- LabelValidator.validateTargetName("bar:baz"));
- assertEquals("target names may not contain ':'",
- LabelValidator.validateTargetName("bar:"));
- assertEquals("target names may not contain '&'",
- LabelValidator.validateTargetName("bar&"));
+ assertThat(LabelValidator.validateTargetName("foo")).isNull();
+ assertThat(LabelValidator.validateTargetName("foo+bar")).isNull();
+ assertThat(LabelValidator.validateTargetName("foo_bar")).isNull();
+ assertThat(LabelValidator.validateTargetName("foo=bar")).isNull();
+ assertThat(LabelValidator.validateTargetName("foo-bar")).isNull();
+ assertThat(LabelValidator.validateTargetName("foo.bar")).isNull();
+ assertThat(LabelValidator.validateTargetName("foo@bar")).isNull();
+ assertThat(LabelValidator.validateTargetName("foo~bar")).isNull();
+ assertThat(LabelValidator.validateTargetName("foo#bar")).isNull();
+
+ assertThat(LabelValidator.validateTargetName("foo/"))
+ .isEqualTo("target names may not end with '/'");
+ assertThat(LabelValidator.validateTargetName("bar:baz"))
+ .isEqualTo("target names may not contain ':'");
+ assertThat(LabelValidator.validateTargetName("bar:"))
+ .isEqualTo("target names may not contain ':'");
+ assertThat(LabelValidator.validateTargetName("bar&"))
+ .isEqualTo("target names may not contain '&'");
}
@Test
public void testValidateAbsoluteLabel() throws Exception {
PackageAndTarget emptyPackage = new PackageAndTarget("", "bar");
- assertEquals(emptyPackage, LabelValidator.validateAbsoluteLabel("//:bar"));
- assertEquals(emptyPackage, LabelValidator.validateAbsoluteLabel("@repo//:bar"));
- assertEquals(new PackageAndTarget("foo", "bar"),
- LabelValidator.validateAbsoluteLabel("@repo//foo:bar"));
- assertEquals(new PackageAndTarget("foo", "bar"),
- LabelValidator.validateAbsoluteLabel("@//foo:bar"));
+ assertThat(LabelValidator.validateAbsoluteLabel("//:bar")).isEqualTo(emptyPackage);
+ assertThat(LabelValidator.validateAbsoluteLabel("@repo//:bar")).isEqualTo(emptyPackage);
+ assertThat(LabelValidator.validateAbsoluteLabel("@repo//foo:bar"))
+ .isEqualTo(new PackageAndTarget("foo", "bar"));
+ assertThat(LabelValidator.validateAbsoluteLabel("@//foo:bar"))
+ .isEqualTo(new PackageAndTarget("foo", "bar"));
emptyPackage = new PackageAndTarget("", "b$() ar");
- assertEquals(emptyPackage, LabelValidator.validateAbsoluteLabel("//:b$() ar"));
- assertEquals(emptyPackage, LabelValidator.validateAbsoluteLabel("@repo//:b$() ar"));
- assertEquals(new PackageAndTarget("f$( )oo", "b$() ar"),
- LabelValidator.validateAbsoluteLabel("@repo//f$( )oo:b$() ar"));
- assertEquals(new PackageAndTarget("f$( )oo", "b$() ar"),
- LabelValidator.validateAbsoluteLabel("@//f$( )oo:b$() ar"));
+ assertThat(LabelValidator.validateAbsoluteLabel("//:b$() ar")).isEqualTo(emptyPackage);
+ assertThat(LabelValidator.validateAbsoluteLabel("@repo//:b$() ar")).isEqualTo(emptyPackage);
+ assertThat(LabelValidator.validateAbsoluteLabel("@repo//f$( )oo:b$() ar"))
+ .isEqualTo(new PackageAndTarget("f$( )oo", "b$() ar"));
+ assertThat(LabelValidator.validateAbsoluteLabel("@//f$( )oo:b$() ar"))
+ .isEqualTo(new PackageAndTarget("f$( )oo", "b$() ar"));
}
@Test
public void testPackageAndTargetHashCode_distinctButEqualObjects() {
PackageAndTarget fooTarget1 = newFooTarget();
PackageAndTarget fooTarget2 = newFooTarget();
- assertNotSame(fooTarget1, fooTarget2);
- assertEquals("Should have same hash code", fooTarget2.hashCode(), fooTarget1.hashCode());
+ assertThat(fooTarget2).isNotSameAs(fooTarget1);
+ assertWithMessage("Should have same hash code")
+ .that(fooTarget1.hashCode())
+ .isEqualTo(fooTarget2.hashCode());
}
@Test
public void testPackageAndTargetEquals_distinctButEqualObjects() {
PackageAndTarget fooTarget1 = newFooTarget();
PackageAndTarget fooTarget2 = newFooTarget();
- assertNotSame(fooTarget1, fooTarget2);
- assertEquals("Should be equal", fooTarget2, fooTarget1);
+ assertThat(fooTarget2).isNotSameAs(fooTarget1);
+ assertWithMessage("Should be equal").that(fooTarget1).isEqualTo(fooTarget2);
}
@Test
public void testPackageAndTargetEquals_unequalObjects() {
- assertFalse("should be unequal", newFooTarget().equals(newBarTarget()));
+ assertWithMessage("should be unequal").that(newFooTarget().equals(newBarTarget())).isFalse();
}
@Test
public void testPackageAndTargetToString() {
- assertEquals("//foo:foo", newFooTarget().toString());
- assertEquals("//bar:bar", newBarTarget().toString());
+ assertThat(newFooTarget().toString()).isEqualTo("//foo:foo");
+ assertThat(newBarTarget().toString()).isEqualTo("//bar:bar");
}
@Test
public void testSlashlessLabel_infersTargetNameFromRepoName() throws Exception {
- assertEquals("//:foo", LabelValidator.parseAbsoluteLabel("@foo").toString());
+ assertThat(LabelValidator.parseAbsoluteLabel("@foo").toString()).isEqualTo("//:foo");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/cmdline/PackageIdentifierTest.java b/src/test/java/com/google/devtools/build/lib/cmdline/PackageIdentifierTest.java
index f01a48c1a1..9e8f3b6cc2 100644
--- a/src/test/java/com/google/devtools/build/lib/cmdline/PackageIdentifierTest.java
+++ b/src/test/java/com/google/devtools/build/lib/cmdline/PackageIdentifierTest.java
@@ -15,16 +15,12 @@
package com.google.devtools.build.lib.cmdline;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -43,11 +39,11 @@ public class PackageIdentifierTest {
PathFragment.create("external/foo"));
PackageIdentifier absoluteA = PackageIdentifier.parse("//a");
- assertThat(absoluteA.getRepository().strippedName()).isEqualTo("");
+ assertThat(absoluteA.getRepository().strippedName()).isEmpty();
assertThat(absoluteA.getPackageFragment().getPathString()).isEqualTo("a");
PackageIdentifier plainA = PackageIdentifier.parse("a");
- assertThat(plainA.getRepository().strippedName()).isEqualTo("");
+ assertThat(plainA.getRepository().strippedName()).isEmpty();
assertThat(plainA.getPackageFragment().getPathString()).isEqualTo("a");
PackageIdentifier mainA = PackageIdentifier.parse("@//a");
@@ -59,9 +55,9 @@ public class PackageIdentifierTest {
@Test
public void testToString() throws Exception {
PackageIdentifier local = PackageIdentifier.create("", PathFragment.create("bar/baz"));
- assertEquals("bar/baz", local.toString());
+ assertThat(local.toString()).isEqualTo("bar/baz");
PackageIdentifier external = PackageIdentifier.create("@foo", PathFragment.create("bar/baz"));
- assertEquals("@foo//bar/baz", external.toString());
+ assertThat(external.toString()).isEqualTo("@foo//bar/baz");
}
@Test
@@ -70,7 +66,7 @@ public class PackageIdentifierTest {
PackageIdentifier foo2 = PackageIdentifier.create("@foo", PathFragment.create("bar/baz"));
PackageIdentifier foo3 = PackageIdentifier.create("@foo", PathFragment.create("bar/bz"));
PackageIdentifier bar = PackageIdentifier.create("@bar", PathFragment.create("bar/baz"));
- assertEquals(0, foo1.compareTo(foo2));
+ assertThat(foo1.compareTo(foo2)).isEqualTo(0);
assertThat(foo1.compareTo(foo3)).isLessThan(0);
assertThat(foo1.compareTo(bar)).isGreaterThan(0);
}
@@ -89,7 +85,7 @@ public class PackageIdentifierTest {
out.writeObject(inId);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data.toByteArray()));
PackageIdentifier outId = (PackageIdentifier) in.readObject();
- assertEquals(inId, outId);
+ assertThat(outId).isEqualTo(inId);
}
@Test
@@ -97,7 +93,7 @@ public class PackageIdentifierTest {
// Make sure package fragments are canonicalized.
PackageIdentifier p1 = PackageIdentifier.create("@whatever", PathFragment.create("foo/bar"));
PackageIdentifier p2 = PackageIdentifier.create("@whatever", PathFragment.create("foo/bar"));
- assertSame(p2.getPackageFragment(), p1.getPackageFragment());
+ assertThat(p1.getPackageFragment()).isSameAs(p2.getPackageFragment());
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/cmdline/RepositoryNameTest.java b/src/test/java/com/google/devtools/build/lib/cmdline/RepositoryNameTest.java
index 6970b5e23b..f5f3895264 100644
--- a/src/test/java/com/google/devtools/build/lib/cmdline/RepositoryNameTest.java
+++ b/src/test/java/com/google/devtools/build/lib/cmdline/RepositoryNameTest.java
@@ -15,7 +15,6 @@
package com.google.devtools.build.lib.cmdline;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.vfs.PathFragment;
@@ -34,20 +33,20 @@ public class RepositoryNameTest {
RepositoryName.create(name);
fail();
} catch (LabelSyntaxException expected) {
- assertThat(expected.getMessage()).contains(expectedMessage);
+ assertThat(expected).hasMessageThat().contains(expectedMessage);
}
}
@Test
public void testValidateRepositoryName() throws Exception {
- assertEquals("@foo", RepositoryName.create("@foo").toString());
+ assertThat(RepositoryName.create("@foo").toString()).isEqualTo("@foo");
assertThat(RepositoryName.create("").toString()).isEmpty();
- assertEquals("@foo_bar", RepositoryName.create("@foo_bar").toString());
- assertEquals("@foo-bar", RepositoryName.create("@foo-bar").toString());
- assertEquals("@foo.bar", RepositoryName.create("@foo.bar").toString());
- assertEquals("@..foo", RepositoryName.create("@..foo").toString());
- assertEquals("@foo..", RepositoryName.create("@foo..").toString());
- assertEquals("@.foo", RepositoryName.create("@.foo").toString());
+ assertThat(RepositoryName.create("@foo_bar").toString()).isEqualTo("@foo_bar");
+ assertThat(RepositoryName.create("@foo-bar").toString()).isEqualTo("@foo-bar");
+ assertThat(RepositoryName.create("@foo.bar").toString()).isEqualTo("@foo.bar");
+ assertThat(RepositoryName.create("@..foo").toString()).isEqualTo("@..foo");
+ assertThat(RepositoryName.create("@foo..").toString()).isEqualTo("@foo..");
+ assertThat(RepositoryName.create("@.foo").toString()).isEqualTo("@.foo");
assertNotValid("x", "workspace names must start with '@'");
assertNotValid("@.", "workspace names are not allowed to be '@.'");
diff --git a/src/test/java/com/google/devtools/build/lib/cmdline/TargetPatternTest.java b/src/test/java/com/google/devtools/build/lib/cmdline/TargetPatternTest.java
index cc22cfb508..1804abb04f 100644
--- a/src/test/java/com/google/devtools/build/lib/cmdline/TargetPatternTest.java
+++ b/src/test/java/com/google/devtools/build/lib/cmdline/TargetPatternTest.java
@@ -14,15 +14,10 @@
package com.google.devtools.build.lib.cmdline;
-
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.cmdline.TargetPattern.Type;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -66,28 +61,28 @@ public class TargetPatternTest {
@Test
public void testNormalize() {
// Good cases.
- assertEquals("empty", TargetPattern.normalize("empty"));
- assertEquals("a/b", TargetPattern.normalize("a/b"));
- assertEquals("a/b/c", TargetPattern.normalize("a/b/c"));
- assertEquals("a/b/c.d", TargetPattern.normalize("a/b/c.d"));
- assertEquals("a/b/c..", TargetPattern.normalize("a/b/c.."));
- assertEquals("a/b/c...", TargetPattern.normalize("a/b/c..."));
-
- assertEquals("a/b", TargetPattern.normalize("a/b/")); // Remove trailing empty segments
- assertEquals("a/c", TargetPattern.normalize("a//c")); // Remove empty inner segments
- assertEquals("a/d", TargetPattern.normalize("a/./d")); // Remove inner dot segments
- assertEquals("a", TargetPattern.normalize("a/.")); // Remove trailing dot segments
+ assertThat(TargetPattern.normalize("empty")).isEqualTo("empty");
+ assertThat(TargetPattern.normalize("a/b")).isEqualTo("a/b");
+ assertThat(TargetPattern.normalize("a/b/c")).isEqualTo("a/b/c");
+ assertThat(TargetPattern.normalize("a/b/c.d")).isEqualTo("a/b/c.d");
+ assertThat(TargetPattern.normalize("a/b/c..")).isEqualTo("a/b/c..");
+ assertThat(TargetPattern.normalize("a/b/c...")).isEqualTo("a/b/c...");
+
+ assertThat(TargetPattern.normalize("a/b/")).isEqualTo("a/b"); // Remove trailing empty segments
+ assertThat(TargetPattern.normalize("a//c")).isEqualTo("a/c"); // Remove empty inner segments
+ assertThat(TargetPattern.normalize("a/./d")).isEqualTo("a/d"); // Remove inner dot segments
+ assertThat(TargetPattern.normalize("a/.")).isEqualTo("a"); // Remove trailing dot segments
// Remove .. segment and its predecessor
- assertEquals("a/e", TargetPattern.normalize("a/b/../e"));
+ assertThat(TargetPattern.normalize("a/b/../e")).isEqualTo("a/e");
// Remove trailing .. segment and its predecessor
- assertEquals("a/g", TargetPattern.normalize("a/g/b/.."));
+ assertThat(TargetPattern.normalize("a/g/b/..")).isEqualTo("a/g");
// Remove double .. segments and two predecessors
- assertEquals("a/h", TargetPattern.normalize("a/b/c/../../h"));
+ assertThat(TargetPattern.normalize("a/b/c/../../h")).isEqualTo("a/h");
// Don't remove leading .. segments
- assertEquals("../a", TargetPattern.normalize("../a"));
- assertEquals("../../a", TargetPattern.normalize("../../a"));
- assertEquals("../../../a", TargetPattern.normalize("../../../a"));
- assertEquals("../../b", TargetPattern.normalize("a/../../../b"));
+ assertThat(TargetPattern.normalize("../a")).isEqualTo("../a");
+ assertThat(TargetPattern.normalize("../../a")).isEqualTo("../../a");
+ assertThat(TargetPattern.normalize("../../../a")).isEqualTo("../../../a");
+ assertThat(TargetPattern.normalize("a/../../../b")).isEqualTo("../../b");
}
@Test
@@ -97,9 +92,9 @@ public class TargetPatternTest {
// And a nested inner pattern '//foo/bar/...',
TargetPattern innerPattern = parseAsExpectedType("//foo/bar/...", Type.TARGETS_BELOW_DIRECTORY);
// Then the outer pattern contains the inner pattern,,
- assertTrue(outerPattern.containsDirectoryOfTBDForTBD(innerPattern));
+ assertThat(outerPattern.containsDirectoryOfTBDForTBD(innerPattern)).isTrue();
// And the inner pattern does not contain the outer pattern.
- assertFalse(innerPattern.containsDirectoryOfTBDForTBD(outerPattern));
+ assertThat(innerPattern.containsDirectoryOfTBDForTBD(outerPattern)).isFalse();
}
@Test
@@ -109,8 +104,8 @@ public class TargetPatternTest {
// And a pattern '//bar/...',
TargetPattern patternBar = parseAsExpectedType("//bar/...", Type.TARGETS_BELOW_DIRECTORY);
// Then neither pattern contains the other.
- assertFalse(patternFoo.containsDirectoryOfTBDForTBD(patternBar));
- assertFalse(patternBar.containsDirectoryOfTBDForTBD(patternFoo));
+ assertThat(patternFoo.containsDirectoryOfTBDForTBD(patternBar)).isFalse();
+ assertThat(patternBar.containsDirectoryOfTBDForTBD(patternFoo)).isFalse();
}
@Test
@@ -125,15 +120,15 @@ public class TargetPatternTest {
TargetPattern targetsInPackagePattern = parseAsExpectedType("foo:all", Type.TARGETS_IN_PACKAGE);
// Then the non-TargetsBelowDirectory patterns do not contain tbdFoo.
- assertFalse(pathAsTargetPattern.containsDirectoryOfTBDForTBD(tbdFoo));
+ assertThat(pathAsTargetPattern.containsDirectoryOfTBDForTBD(tbdFoo)).isFalse();
// And are not considered to be a contained directory of the TargetsBelowDirectory pattern.
- assertFalse(tbdFoo.containsDirectoryOfTBDForTBD(pathAsTargetPattern));
+ assertThat(tbdFoo.containsDirectoryOfTBDForTBD(pathAsTargetPattern)).isFalse();
- assertFalse(singleTargetPattern.containsDirectoryOfTBDForTBD(tbdFoo));
- assertFalse(tbdFoo.containsDirectoryOfTBDForTBD(singleTargetPattern));
+ assertThat(singleTargetPattern.containsDirectoryOfTBDForTBD(tbdFoo)).isFalse();
+ assertThat(tbdFoo.containsDirectoryOfTBDForTBD(singleTargetPattern)).isFalse();
- assertFalse(targetsInPackagePattern.containsDirectoryOfTBDForTBD(tbdFoo));
- assertFalse(tbdFoo.containsDirectoryOfTBDForTBD(targetsInPackagePattern));
+ assertThat(targetsInPackagePattern.containsDirectoryOfTBDForTBD(tbdFoo)).isFalse();
+ assertThat(tbdFoo.containsDirectoryOfTBDForTBD(targetsInPackagePattern)).isFalse();
}
@Test
@@ -151,10 +146,10 @@ public class TargetPatternTest {
parseAsExpectedType("food:all", Type.TARGETS_IN_PACKAGE);
// Then the non-TargetsBelowDirectory patterns are not contained by tbdFoo.
- assertFalse(tbdFoo.containsDirectoryOfTBDForTBD(targetsBelowDirectoryPattern));
- assertFalse(tbdFoo.containsDirectoryOfTBDForTBD(pathAsTargetPattern));
- assertFalse(tbdFoo.containsDirectoryOfTBDForTBD(singleTargetPattern));
- assertFalse(tbdFoo.containsDirectoryOfTBDForTBD(targetsInPackagePattern));
+ assertThat(tbdFoo.containsDirectoryOfTBDForTBD(targetsBelowDirectoryPattern)).isFalse();
+ assertThat(tbdFoo.containsDirectoryOfTBDForTBD(pathAsTargetPattern)).isFalse();
+ assertThat(tbdFoo.containsDirectoryOfTBDForTBD(singleTargetPattern)).isFalse();
+ assertThat(tbdFoo.containsDirectoryOfTBDForTBD(targetsInPackagePattern)).isFalse();
}
@Test
@@ -170,17 +165,17 @@ public class TargetPatternTest {
TargetPattern targetsInPackagePattern = parseAsExpectedType("foo:all", Type.TARGETS_IN_PACKAGE);
// Then the patterns are contained by tbdDepot, and do not contain tbdDepot.
- assertTrue(tbdDepot.containsDirectoryOfTBDForTBD(tbdFoo));
- assertFalse(tbdFoo.containsDirectoryOfTBDForTBD(tbdDepot));
+ assertThat(tbdDepot.containsDirectoryOfTBDForTBD(tbdFoo)).isTrue();
+ assertThat(tbdFoo.containsDirectoryOfTBDForTBD(tbdDepot)).isFalse();
- assertFalse(tbdDepot.containsDirectoryOfTBDForTBD(pathAsTargetPattern));
- assertFalse(pathAsTargetPattern.containsDirectoryOfTBDForTBD(tbdDepot));
+ assertThat(tbdDepot.containsDirectoryOfTBDForTBD(pathAsTargetPattern)).isFalse();
+ assertThat(pathAsTargetPattern.containsDirectoryOfTBDForTBD(tbdDepot)).isFalse();
- assertFalse(tbdDepot.containsDirectoryOfTBDForTBD(singleTargetPattern));
- assertFalse(singleTargetPattern.containsDirectoryOfTBDForTBD(tbdDepot));
+ assertThat(tbdDepot.containsDirectoryOfTBDForTBD(singleTargetPattern)).isFalse();
+ assertThat(singleTargetPattern.containsDirectoryOfTBDForTBD(tbdDepot)).isFalse();
- assertFalse(tbdDepot.containsDirectoryOfTBDForTBD(targetsInPackagePattern));
- assertFalse(targetsInPackagePattern.containsDirectoryOfTBDForTBD(tbdDepot));
+ assertThat(tbdDepot.containsDirectoryOfTBDForTBD(targetsInPackagePattern)).isFalse();
+ assertThat(targetsInPackagePattern.containsDirectoryOfTBDForTBD(tbdDepot)).isFalse();
}
private static TargetPattern parse(String pattern) throws TargetParsingException {
diff --git a/src/test/java/com/google/devtools/build/lib/collect/CollectionUtilsTest.java b/src/test/java/com/google/devtools/build/lib/collect/CollectionUtilsTest.java
index 769730f9c7..9f8b3770a1 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/CollectionUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/CollectionUtilsTest.java
@@ -14,11 +14,6 @@
package com.google.devtools.build.lib.collect;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -28,15 +23,13 @@ import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests for {@link CollectionUtils}.
@@ -56,37 +49,37 @@ public class CollectionUtilsTest {
}
private static void assertDups(List<Integer> collection, Set<Integer> dups) {
- assertEquals(dups, CollectionUtils.duplicatedElementsOf(collection));
+ assertThat(CollectionUtils.duplicatedElementsOf(collection)).isEqualTo(dups);
}
@Test
public void testIsImmutable() throws Exception {
- assertTrue(CollectionUtils.isImmutable(ImmutableList.of(1, 2, 3)));
- assertTrue(CollectionUtils.isImmutable(ImmutableSet.of(1, 2, 3)));
+ assertThat(CollectionUtils.isImmutable(ImmutableList.of(1, 2, 3))).isTrue();
+ assertThat(CollectionUtils.isImmutable(ImmutableSet.of(1, 2, 3))).isTrue();
NestedSet<Integer> ns = NestedSetBuilder.<Integer>compileOrder()
.add(1).add(2).add(3).build();
- assertTrue(CollectionUtils.isImmutable(ns));
+ assertThat(CollectionUtils.isImmutable(ns)).isTrue();
NestedSet<Integer> ns2 = NestedSetBuilder.<Integer>linkOrder().add(1).add(2).add(3).build();
- assertTrue(CollectionUtils.isImmutable(ns2));
+ assertThat(CollectionUtils.isImmutable(ns2)).isTrue();
IterablesChain<Integer> chain = IterablesChain.<Integer>builder().addElement(1).build();
- assertTrue(CollectionUtils.isImmutable(chain));
+ assertThat(CollectionUtils.isImmutable(chain)).isTrue();
- assertFalse(CollectionUtils.isImmutable(Lists.newArrayList()));
- assertFalse(CollectionUtils.isImmutable(Lists.newLinkedList()));
- assertFalse(CollectionUtils.isImmutable(Sets.newHashSet()));
- assertFalse(CollectionUtils.isImmutable(Sets.newLinkedHashSet()));
+ assertThat(CollectionUtils.isImmutable(Lists.newArrayList())).isFalse();
+ assertThat(CollectionUtils.isImmutable(Lists.newLinkedList())).isFalse();
+ assertThat(CollectionUtils.isImmutable(Sets.newHashSet())).isFalse();
+ assertThat(CollectionUtils.isImmutable(Sets.newLinkedHashSet())).isFalse();
// The result of Iterables.concat() actually is immutable, but we have no way of checking if
// a given Iterable comes from concat().
- assertFalse(CollectionUtils.isImmutable(Iterables.concat(ns, ns2)));
+ assertThat(CollectionUtils.isImmutable(Iterables.concat(ns, ns2))).isFalse();
// We can override the check by using the ImmutableIterable wrapper.
- assertTrue(CollectionUtils.isImmutable(
- ImmutableIterable.from(Iterables.concat(ns, ns2))));
+ assertThat(CollectionUtils.isImmutable(ImmutableIterable.from(Iterables.concat(ns, ns2))))
+ .isTrue();
}
@Test
@@ -105,12 +98,12 @@ public class CollectionUtilsTest {
@Test
public void testMakeImmutable() throws Exception {
Iterable<Integer> immutableList = ImmutableList.of(1, 2, 3);
- assertSame(immutableList, CollectionUtils.makeImmutable(immutableList));
+ assertThat(CollectionUtils.makeImmutable(immutableList)).isSameAs(immutableList);
Iterable<Integer> mutableList = Lists.newArrayList(1, 2, 3);
Iterable<Integer> converted = CollectionUtils.makeImmutable(mutableList);
- assertNotSame(mutableList, converted);
- assertEquals(mutableList, ImmutableList.copyOf(converted));
+ assertThat(converted).isNotSameAs(mutableList);
+ assertThat(ImmutableList.copyOf(converted)).isEqualTo(mutableList);
}
private static enum Small { ALPHA, BRAVO }
@@ -139,7 +132,7 @@ public class CollectionUtilsTest {
for (int i = 0; i < maxBits; i++) {
EnumSet<T> set = CollectionUtils.fromBits(i, clazz);
int back = CollectionUtils.toBits(set);
- assertEquals(back, i); // Assert that a roundtrip is idempotent
+ assertThat(i).isEqualTo(back); // Assert that a roundtrip is idempotent
allSets.add(set);
}
@@ -148,12 +141,12 @@ public class CollectionUtilsTest {
@Test
public void testEnumBitfields() throws Exception {
- assertEquals(0, CollectionUtils.<Small>toBits());
- assertEquals(EnumSet.noneOf(Small.class), CollectionUtils.fromBits(0, Small.class));
- assertEquals(3, CollectionUtils.toBits(Small.ALPHA, Small.BRAVO));
- assertEquals(10, CollectionUtils.toBits(Medium.TWO, Medium.FOUR));
- assertEquals(EnumSet.of(Medium.SEVEN, Medium.EIGHT),
- CollectionUtils.fromBits(192, Medium.class));
+ assertThat(CollectionUtils.<Small>toBits()).isEqualTo(0);
+ assertThat(CollectionUtils.fromBits(0, Small.class)).isEqualTo(EnumSet.noneOf(Small.class));
+ assertThat(CollectionUtils.toBits(Small.ALPHA, Small.BRAVO)).isEqualTo(3);
+ assertThat(CollectionUtils.toBits(Medium.TWO, Medium.FOUR)).isEqualTo(10);
+ assertThat(CollectionUtils.fromBits(192, Medium.class))
+ .isEqualTo(EnumSet.of(Medium.SEVEN, Medium.EIGHT));
assertAllDifferent(Small.class);
assertAllDifferent(Medium.class);
diff --git a/src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyListMultimapTest.java b/src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyListMultimapTest.java
index 7b3f8e7f7a..56424ec716 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyListMultimapTest.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyListMultimapTest.java
@@ -13,10 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.collect;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ArrayListMultimap;
@@ -52,9 +49,9 @@ public class ImmutableSortedKeyListMultimapTest {
builder.putAll("bar", Arrays.asList(4, 5));
builder.putAll("foo", Arrays.asList(6, 7));
Multimap<String, Integer> multimap = builder.build();
- assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo"));
- assertEquals(Arrays.asList(4, 5), multimap.get("bar"));
- assertEquals(7, multimap.size());
+ assertThat(multimap).valuesForKey("foo").containsExactly(1, 2, 3, 6, 7).inOrder();
+ assertThat(multimap).valuesForKey("bar").containsExactly(4, 5).inOrder();
+ assertThat(multimap).hasSize(7);
}
@Test
@@ -65,9 +62,9 @@ public class ImmutableSortedKeyListMultimapTest {
builder.putAll("bar", 4, 5);
builder.putAll("foo", 6, 7);
Multimap<String, Integer> multimap = builder.build();
- assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo"));
- assertEquals(Arrays.asList(4, 5), multimap.get("bar"));
- assertEquals(7, multimap.size());
+ assertThat(multimap).valuesForKey("foo").containsExactly(1, 2, 3, 6, 7).inOrder();
+ assertThat(multimap).valuesForKey("bar").containsExactly(4, 5).inOrder();
+ assertThat(multimap).hasSize(7);
}
@Test
@@ -86,9 +83,9 @@ public class ImmutableSortedKeyListMultimapTest {
builder.putAll(toPut);
builder.putAll(moreToPut);
Multimap<String, Integer> multimap = builder.build();
- assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo"));
- assertEquals(Arrays.asList(4, 5), multimap.get("bar"));
- assertEquals(7, multimap.size());
+ assertThat(multimap).valuesForKey("foo").containsExactly(1, 2, 3, 6, 7).inOrder();
+ assertThat(multimap).valuesForKey("bar").containsExactly(4, 5).inOrder();
+ assertThat(multimap).hasSize(7);
}
@Test
@@ -99,9 +96,9 @@ public class ImmutableSortedKeyListMultimapTest {
builder.putAll("bar", 4, 5);
builder.putAll("foo", 1, 6, 7);
ImmutableSortedKeyListMultimap<String, Integer> multimap = builder.build();
- assertEquals(Arrays.asList(1, 2, 3, 1, 6, 7), multimap.get("foo"));
- assertEquals(Arrays.asList(4, 5), multimap.get("bar"));
- assertEquals(8, multimap.size());
+ assertThat(multimap).valuesForKey("foo").containsExactly(1, 2, 3, 1, 6, 7).inOrder();
+ assertThat(multimap).valuesForKey("bar").containsExactly(4, 5).inOrder();
+ assertThat(multimap).hasSize(8);
}
@Test
@@ -112,9 +109,9 @@ public class ImmutableSortedKeyListMultimapTest {
builder.putAll("bar", 4, 5);
builder.put("foo", 1);
ImmutableSortedKeyListMultimap<String, Integer> multimap = builder.build();
- assertEquals(Arrays.asList(1, 2, 3, 1), multimap.get("foo"));
- assertEquals(Arrays.asList(4, 5), multimap.get("bar"));
- assertEquals(6, multimap.size());
+ assertThat(multimap).valuesForKey("foo").containsExactly(1, 2, 3, 1).inOrder();
+ assertThat(multimap).valuesForKey("bar").containsExactly(4, 5).inOrder();
+ assertThat(multimap).hasSize(6);
}
@Test
@@ -135,9 +132,9 @@ public class ImmutableSortedKeyListMultimapTest {
builder.putAll(toPut);
builder.putAll(moreToPut);
Multimap<String, Integer> multimap = builder.build();
- assertEquals(Arrays.asList(1, 2, 1, 6, 7, 2), multimap.get("foo"));
- assertEquals(Arrays.asList(4, 5, 4), multimap.get("bar"));
- assertEquals(9, multimap.size());
+ assertThat(multimap).valuesForKey("foo").containsExactly(1, 2, 1, 6, 7, 2).inOrder();
+ assertThat(multimap).valuesForKey("bar").containsExactly(4, 5, 4).inOrder();
+ assertThat(multimap).hasSize(9);
}
@Test
@@ -195,8 +192,8 @@ public class ImmutableSortedKeyListMultimapTest {
input.put("bar", 2);
input.put("foo", 3);
Multimap<String, Integer> multimap = ImmutableSortedKeyListMultimap.copyOf(input);
- assertEquals(multimap, input);
- assertEquals(input, multimap);
+ assertThat(input).isEqualTo(multimap);
+ assertThat(multimap).isEqualTo(input);
}
@Test
@@ -207,22 +204,22 @@ public class ImmutableSortedKeyListMultimapTest {
input.put("foo", 3);
input.put("foo", 1);
Multimap<String, Integer> multimap = ImmutableSortedKeyListMultimap.copyOf(input);
- assertEquals(multimap, input);
- assertEquals(input, multimap);
+ assertThat(input).isEqualTo(multimap);
+ assertThat(multimap).isEqualTo(input);
}
@Test
public void copyOfEmpty() {
ListMultimap<String, Integer> input = ArrayListMultimap.create();
Multimap<String, Integer> multimap = ImmutableSortedKeyListMultimap.copyOf(input);
- assertEquals(multimap, input);
- assertEquals(input, multimap);
+ assertThat(input).isEqualTo(multimap);
+ assertThat(multimap).isEqualTo(input);
}
@Test
public void copyOfImmutableListMultimap() {
Multimap<String, Integer> multimap = createMultimap();
- assertSame(multimap, ImmutableSortedKeyListMultimap.copyOf(multimap));
+ assertThat(ImmutableSortedKeyListMultimap.copyOf(multimap)).isSameAs(multimap);
}
@Test
@@ -248,19 +245,19 @@ public class ImmutableSortedKeyListMultimapTest {
@Test
public void emptyMultimapReads() {
Multimap<String, Integer> multimap = ImmutableSortedKeyListMultimap.of();
- assertFalse(multimap.containsKey("foo"));
- assertFalse(multimap.containsValue(1));
- assertFalse(multimap.containsEntry("foo", 1));
- assertTrue(multimap.entries().isEmpty());
- assertTrue(multimap.equals(ArrayListMultimap.create()));
- assertEquals(Collections.emptyList(), multimap.get("foo"));
- assertEquals(0, multimap.hashCode());
- assertTrue(multimap.isEmpty());
- assertEquals(HashMultiset.create(), multimap.keys());
- assertEquals(Collections.emptySet(), multimap.keySet());
- assertEquals(0, multimap.size());
- assertTrue(multimap.values().isEmpty());
- assertEquals("{}", multimap.toString());
+ assertThat(multimap).doesNotContainKey("foo");
+ assertThat(multimap.containsValue(1)).isFalse();
+ assertThat(multimap).doesNotContainEntry("foo", 1);
+ assertThat(multimap.entries()).isEmpty();
+ assertThat(multimap.equals(ArrayListMultimap.create())).isTrue();
+ assertThat(multimap).valuesForKey("foo").isEqualTo(Collections.emptyList());
+ assertThat(multimap.hashCode()).isEqualTo(0);
+ assertThat(multimap).isEmpty();
+ assertThat(multimap.keys()).isEqualTo(HashMultiset.create());
+ assertThat(multimap).isEmpty();
+ assertThat(multimap).isEmpty();
+ assertThat(multimap).isEmpty();
+ assertThat(multimap.toString()).isEqualTo("{}");
}
@Test
@@ -278,17 +275,17 @@ public class ImmutableSortedKeyListMultimapTest {
@Test
public void multimapReads() {
Multimap<String, Integer> multimap = createMultimap();
- assertTrue(multimap.containsKey("foo"));
- assertFalse(multimap.containsKey("cat"));
- assertTrue(multimap.containsValue(1));
- assertFalse(multimap.containsValue(5));
- assertTrue(multimap.containsEntry("foo", 1));
- assertFalse(multimap.containsEntry("cat", 1));
- assertFalse(multimap.containsEntry("foo", 5));
- assertFalse(multimap.entries().isEmpty());
- assertEquals(3, multimap.size());
- assertFalse(multimap.isEmpty());
- assertEquals("{bar=[2], foo=[1, 3]}", multimap.toString());
+ assertThat(multimap).containsKey("foo");
+ assertThat(multimap).doesNotContainKey("cat");
+ assertThat(multimap.containsValue(1)).isTrue();
+ assertThat(multimap.containsValue(5)).isFalse();
+ assertThat(multimap).containsEntry("foo", 1);
+ assertThat(multimap).doesNotContainEntry("cat", 1);
+ assertThat(multimap).doesNotContainEntry("foo", 5);
+ assertThat(multimap.entries()).isNotEmpty();
+ assertThat(multimap).hasSize(3);
+ assertThat(multimap).isNotEmpty();
+ assertThat(multimap.toString()).isEqualTo("{bar=[2], foo=[1, 3]}");
}
@Test
@@ -326,12 +323,12 @@ public class ImmutableSortedKeyListMultimapTest {
builder.putAll("foo", Arrays.asList(1, 2, 3));
builder.putAll("bar", Arrays.asList(4, 5));
Map<String, Collection<Integer>> map = builder.build().asMap();
- assertEquals(Arrays.asList(1, 2, 3), map.get("foo"));
- assertEquals(Arrays.asList(4, 5), map.get("bar"));
- assertEquals(2, map.size());
- assertTrue(map.containsKey("foo"));
- assertTrue(map.containsKey("bar"));
- assertFalse(map.containsKey("notfoo"));
+ assertThat(map).containsEntry("foo", Arrays.asList(1, 2, 3));
+ assertThat(map).containsEntry("bar", Arrays.asList(4, 5));
+ assertThat(map).hasSize(2);
+ assertThat(map).containsKey("foo");
+ assertThat(map).containsKey("bar");
+ assertThat(map).doesNotContainKey("notfoo");
}
@Test
@@ -346,6 +343,6 @@ public class ImmutableSortedKeyListMultimapTest {
.add(new SimpleImmutableEntry<String, Collection<Integer>>("foo", Arrays.asList(1, 2, 3)))
.add(new SimpleImmutableEntry<String, Collection<Integer>>("bar", Arrays.asList(4, 5)))
.build();
- assertEquals(other, set);
+ assertThat(set).isEqualTo(other);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyMapTest.java b/src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyMapTest.java
index 13d1f999ea..24282d453f 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyMapTest.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/ImmutableSortedKeyMapTest.java
@@ -14,23 +14,19 @@
package com.google.devtools.build.lib.collect;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import com.google.common.collect.Maps;
import com.google.common.testing.NullPointerTester;
import com.google.devtools.build.lib.collect.ImmutableSortedKeyMap.Builder;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* A test for {@link ImmutableSortedKeyListMultimap}. Started out as a blatant copy of
@@ -195,7 +191,7 @@ public class ImmutableSortedKeyMapTest {
ImmutableSortedKeyMap<String, Integer> copy
= ImmutableSortedKeyMap.copyOf(Collections.<String, Integer>emptyMap());
assertThat(copy).isEmpty();
- assertSame(copy, ImmutableSortedKeyMap.copyOf(copy));
+ assertThat(ImmutableSortedKeyMap.copyOf(copy)).isSameAs(copy);
}
@Test
@@ -203,7 +199,7 @@ public class ImmutableSortedKeyMapTest {
ImmutableSortedKeyMap<String, Integer> copy
= ImmutableSortedKeyMap.copyOf(Collections.singletonMap("one", 1));
assertMapEquals(copy, "one", 1);
- assertSame(copy, ImmutableSortedKeyMap.copyOf(copy));
+ assertThat(ImmutableSortedKeyMap.copyOf(copy)).isSameAs(copy);
}
@Test
@@ -215,7 +211,7 @@ public class ImmutableSortedKeyMapTest {
ImmutableSortedKeyMap<String, Integer> copy = ImmutableSortedKeyMap.copyOf(original);
assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
- assertSame(copy, ImmutableSortedKeyMap.copyOf(copy));
+ assertThat(ImmutableSortedKeyMap.copyOf(copy)).isSameAs(copy);
}
@Test
@@ -238,11 +234,11 @@ public class ImmutableSortedKeyMapTest {
private static <K, V> void assertMapEquals(Map<K, V> map,
Object... alternatingKeysAndValues) {
- assertEquals(map.size(), alternatingKeysAndValues.length / 2);
+ assertThat(alternatingKeysAndValues.length / 2).isEqualTo(map.size());
int i = 0;
for (Entry<K, V> entry : map.entrySet()) {
- assertEquals(alternatingKeysAndValues[i++], entry.getKey());
- assertEquals(alternatingKeysAndValues[i++], entry.getValue());
+ assertThat(entry.getKey()).isEqualTo(alternatingKeysAndValues[i++]);
+ assertThat(entry.getValue()).isEqualTo(alternatingKeysAndValues[i++]);
}
}
@@ -272,15 +268,15 @@ public class ImmutableSortedKeyMapTest {
holderA.value = 3;
assertThat(map.entrySet()).contains(Maps.immutableEntry("a", new IntHolder(3)));
Map<String, Integer> intMap = ImmutableSortedKeyMap.of("a", 3, "b", 2);
- assertEquals(intMap.hashCode(), map.entrySet().hashCode());
- assertEquals(intMap.hashCode(), map.hashCode());
+ assertThat(map.entrySet().hashCode()).isEqualTo(intMap.hashCode());
+ assertThat(map.hashCode()).isEqualTo(intMap.hashCode());
}
@Test
public void toStringTest() {
Map<String, Integer> map = ImmutableSortedKeyMap.of("a", 1, "b", 2);
- assertEquals("{a=1, b=2}", map.toString());
+ assertThat(map.toString()).isEqualTo("{a=1, b=2}");
map = ImmutableSortedKeyMap.of();
- assertEquals("{}", map.toString());
+ assertThat(map.toString()).isEqualTo("{}");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/collect/IterablesChainTest.java b/src/test/java/com/google/devtools/build/lib/collect/IterablesChainTest.java
index 4b69e64532..6cd842d0ac 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/IterablesChainTest.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/IterablesChainTest.java
@@ -13,21 +13,14 @@
// limitations under the License.
package com.google.devtools.build.lib.collect;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Arrays;
-
-/**
- * A test for {@link IterablesChain}.
- */
+/** A test for {@link IterablesChain}. */
@RunWith(JUnit4.class)
public class IterablesChainTest {
@@ -36,25 +29,25 @@ public class IterablesChainTest {
IterablesChain.Builder<String> builder = IterablesChain.builder();
builder.addElement("a");
builder.addElement("b");
- assertEquals(Arrays.asList("a", "b"), ImmutableList.copyOf(builder.build()));
+ assertThat(builder.build()).containsExactly("a", "b").inOrder();
}
@Test
public void add() {
IterablesChain.Builder<String> builder = IterablesChain.builder();
builder.add(ImmutableList.of("a", "b"));
- assertEquals(Arrays.asList("a", "b"), ImmutableList.copyOf(builder.build()));
+ assertThat(builder.build()).containsExactly("a", "b").inOrder();
}
@Test
public void isEmpty() {
IterablesChain.Builder<String> builder = IterablesChain.builder();
- assertTrue(builder.isEmpty());
+ assertThat(builder.isEmpty()).isTrue();
builder.addElement("a");
- assertFalse(builder.isEmpty());
+ assertThat(builder.isEmpty()).isFalse();
builder = IterablesChain.builder();
- assertTrue(builder.isEmpty());
+ assertThat(builder.isEmpty()).isTrue();
builder.add(ImmutableList.of("a"));
- assertFalse(builder.isEmpty());
+ assertThat(builder.isEmpty()).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/collect/nestedset/ExpanderTestBase.java b/src/test/java/com/google/devtools/build/lib/collect/nestedset/ExpanderTestBase.java
index 927d324258..236afecd73 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/nestedset/ExpanderTestBase.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/nestedset/ExpanderTestBase.java
@@ -13,19 +13,15 @@
// limitations under the License.
package com.google.devtools.build.lib.collect.nestedset;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
-
-import org.junit.Test;
-
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import org.junit.Test;
/**
* Base class for tests of {@link NestedSetExpander} implementations.
@@ -44,7 +40,7 @@ public abstract class ExpanderTestBase {
public void simple() {
NestedSet<String> s = prepareBuilder("c", "a", "b").build();
- assertEquals(simpleResult(), s.toList());
+ assertThat(s.toList()).isEqualTo(simpleResult());
assertSetContents(simpleResult(), s);
}
@@ -52,7 +48,7 @@ public abstract class ExpanderTestBase {
public void simpleNoDuplicates() {
NestedSet<String> s = prepareBuilder("c", "a", "a", "a", "b").build();
- assertEquals(simpleResult(), s.toList());
+ assertThat(s.toList()).isEqualTo(simpleResult());
assertSetContents(simpleResult(), s);
}
@@ -192,15 +188,15 @@ public abstract class ExpanderTestBase {
@Test
public void getOrderingEmpty() {
NestedSet<String> s = prepareBuilder().build();
- assertTrue(s.isEmpty());
- assertEquals(expanderOrder(), s.getOrder());
+ assertThat(s.isEmpty()).isTrue();
+ assertThat(s.getOrder()).isEqualTo(expanderOrder());
}
@Test
public void getOrdering() {
NestedSet<String> s = prepareBuilder("a", "b").build();
- assertFalse(s.isEmpty());
- assertEquals(expanderOrder(), s.getOrder());
+ assertThat(s.isEmpty()).isFalse();
+ assertThat(s.getOrder()).isEqualTo(expanderOrder());
}
@Test
@@ -228,15 +224,15 @@ public abstract class ExpanderTestBase {
}
protected final void assertSetContents(Collection<String> expected, NestedSet<String> set) {
- assertEquals(expected, Lists.newArrayList(set));
- assertEquals(expected, Lists.newArrayList(set.toCollection()));
- assertEquals(expected, Lists.newArrayList(set.toList()));
- assertEquals(expected, Lists.newArrayList(set.toSet()));
+ assertThat(Lists.newArrayList(set)).isEqualTo(expected);
+ assertThat(Lists.newArrayList(set.toCollection())).isEqualTo(expected);
+ assertThat(Lists.newArrayList(set.toList())).isEqualTo(expected);
+ assertThat(Lists.newArrayList(set.toSet())).isEqualTo(expected);
}
protected final void assertCollectionsEqual(
Collection<String> expected, Collection<String> actual) {
- assertEquals(Lists.newArrayList(expected), Lists.newArrayList(actual));
+ assertThat(Lists.newArrayList(actual)).isEqualTo(Lists.newArrayList(expected));
}
/**
diff --git a/src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetImplTest.java b/src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetImplTest.java
index a5eb38a5b6..ff4515276b 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetImplTest.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetImplTest.java
@@ -13,15 +13,11 @@
// limitations under the License.
package com.google.devtools.build.lib.collect.nestedset;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.testing.EqualsTester;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -42,15 +38,15 @@ public class NestedSetImplTest {
public void simple() {
NestedSet<String> set = nestedSetBuilder("a").build();
- assertEquals(ImmutableList.of("a"), set.toList());
- assertFalse(set.isEmpty());
+ assertThat(set.toList()).containsExactly("a");
+ assertThat(set.isEmpty()).isFalse();
}
@Test
public void flatToString() {
- assertEquals("{}", nestedSetBuilder().build().toString());
- assertEquals("{a}", nestedSetBuilder("a").build().toString());
- assertEquals("{a, b}", nestedSetBuilder("a", "b").build().toString());
+ assertThat(nestedSetBuilder().build().toString()).isEqualTo("{}");
+ assertThat(nestedSetBuilder("a").build().toString()).isEqualTo("{a}");
+ assertThat(nestedSetBuilder("a", "b").build().toString()).isEqualTo("{a, b}");
}
@Test
@@ -58,33 +54,33 @@ public class NestedSetImplTest {
NestedSet<String> b = nestedSetBuilder("b1", "b2").build();
NestedSet<String> c = nestedSetBuilder("c1", "c2").build();
- assertEquals("{{b1, b2}, a}",
- nestedSetBuilder("a").addTransitive(b).build().toString());
- assertEquals("{{b1, b2}, {c1, c2}, a}",
- nestedSetBuilder("a").addTransitive(b).addTransitive(c).build().toString());
+ assertThat(nestedSetBuilder("a").addTransitive(b).build().toString())
+ .isEqualTo("{{b1, b2}, a}");
+ assertThat(nestedSetBuilder("a").addTransitive(b).addTransitive(c).build().toString())
+ .isEqualTo("{{b1, b2}, {c1, c2}, a}");
- assertEquals("{b1, b2}", nestedSetBuilder().addTransitive(b).build().toString());
+ assertThat(nestedSetBuilder().addTransitive(b).build().toString()).isEqualTo("{b1, b2}");
}
@Test
public void isEmpty() {
NestedSet<String> triviallyEmpty = nestedSetBuilder().build();
- assertTrue(triviallyEmpty.isEmpty());
+ assertThat(triviallyEmpty.isEmpty()).isTrue();
NestedSet<String> emptyLevel1 = nestedSetBuilder().addTransitive(triviallyEmpty).build();
- assertTrue(emptyLevel1.isEmpty());
+ assertThat(emptyLevel1.isEmpty()).isTrue();
NestedSet<String> emptyLevel2 = nestedSetBuilder().addTransitive(emptyLevel1).build();
- assertTrue(emptyLevel2.isEmpty());
+ assertThat(emptyLevel2.isEmpty()).isTrue();
NestedSet<String> triviallyNonEmpty = nestedSetBuilder("mango").build();
- assertFalse(triviallyNonEmpty.isEmpty());
+ assertThat(triviallyNonEmpty.isEmpty()).isFalse();
NestedSet<String> nonEmptyLevel1 = nestedSetBuilder().addTransitive(triviallyNonEmpty).build();
- assertFalse(nonEmptyLevel1.isEmpty());
+ assertThat(nonEmptyLevel1.isEmpty()).isFalse();
NestedSet<String> nonEmptyLevel2 = nestedSetBuilder().addTransitive(nonEmptyLevel1).build();
- assertFalse(nonEmptyLevel2.isEmpty());
+ assertThat(nonEmptyLevel2.isEmpty()).isFalse();
}
@Test
@@ -208,11 +204,13 @@ public class NestedSetImplTest {
for (Order order : Order.values()) {
for (int numDirects = 0; numDirects < 3; numDirects++) {
for (int numTransitives = 0; numTransitives < 3; numTransitives++) {
- assertEquals(order, createNestedSet(order, numDirects, numTransitives, order).getOrder());
+ assertThat(createNestedSet(order, numDirects, numTransitives, order).getOrder())
+ .isEqualTo(order);
// We allow mixing orders if one of them is stable. This tests that the top level order is
// the correct one.
- assertEquals(order,
- createNestedSet(order, numDirects, numTransitives, Order.STABLE_ORDER).getOrder());
+ assertThat(
+ createNestedSet(order, numDirects, numTransitives, Order.STABLE_ORDER).getOrder())
+ .isEqualTo(order);
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetViewTest.java b/src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetViewTest.java
index 157347358b..19f0135c21 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetViewTest.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/nestedset/NestedSetViewTest.java
@@ -13,9 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.collect.nestedset;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableSet;
import java.util.Set;
@@ -36,20 +34,18 @@ public class NestedSetViewTest {
NestedSetBuilder.<String>stableOrder().add("a").add("b").add("c").build();
// The identifier should be independent of the view instance.
- assertEquals(
- (new NestedSetView<String>(inner)).identifier(),
- (new NestedSetView<String>(inner)).identifier());
+ assertThat((new NestedSetView<String>(inner)).identifier())
+ .isEqualTo((new NestedSetView<String>(inner)).identifier());
// Sets with different internal structure should have different identifiers
- assertNotEquals(
- (new NestedSetView<String>(outer)).identifier(),
- (new NestedSetView<String>(flat)).identifier());
+ assertThat((new NestedSetView<String>(flat)).identifier())
+ .isNotEqualTo((new NestedSetView<String>(outer)).identifier());
// Decomposing a set, the transitive sets should be correctly identified.
Set<NestedSetView<String>> transitives = (new NestedSetView<String>(outer)).transitives();
- assertEquals(1, transitives.size());
+ assertThat(transitives).hasSize(1);
NestedSetView<String> extracted = transitives.iterator().next();
- assertEquals((new NestedSetView<String>(inner)).identifier(), extracted.identifier());
+ assertThat(extracted.identifier()).isEqualTo((new NestedSetView<String>(inner)).identifier());
}
@Test
@@ -64,7 +60,7 @@ public class NestedSetViewTest {
.build();
// The direct members should correctly be identified.
- assertEquals(ImmutableSet.of("c", "d", "e"), (new NestedSetView<String>(outer)).directs());
+ assertThat((new NestedSetView<String>(outer)).directs()).containsExactly("c", "d", "e");
}
@Test
@@ -94,7 +90,7 @@ public class NestedSetViewTest {
for (NestedSetView<String> transitive : (new NestedSetView<String>(outer)).transitives()) {
found.add(transitive.identifier());
}
- assertEquals(expected, found.build());
+ assertThat(found.build()).isEqualTo(expected);
}
/** Naively traverse a view and collect all elements reachable. */
@@ -133,8 +129,8 @@ public class NestedSetViewTest {
.build();
NestedSetView<String> view = new NestedSetView<String>(outer);
- assertEquals(ImmutableSet.of("a", "b", "c1", "c2", "x", "y", "z"), contents(view));
- assertTrue(
- identifiers(view.transitives()).contains((new NestedSetView<String>(multi)).identifier()));
+ assertThat(contents(view)).containsExactly("a", "b", "c1", "c2", "x", "y", "z");
+ assertThat(identifiers(view.transitives()))
+ .contains((new NestedSetView<String>(multi)).identifier());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/collect/nestedset/OrderTest.java b/src/test/java/com/google/devtools/build/lib/collect/nestedset/OrderTest.java
index 7f6308dc48..30ef309089 100644
--- a/src/test/java/com/google/devtools/build/lib/collect/nestedset/OrderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/collect/nestedset/OrderTest.java
@@ -48,7 +48,7 @@ public class OrderTest {
Order.parse(invalidName);
fail();
} catch (IllegalArgumentException ex) {
- assertThat(ex.getMessage()).startsWith("Invalid order");
+ assertThat(ex).hasMessageThat().startsWith("Invalid order");
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitorTest.java b/src/test/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitorTest.java
index 5aa63dd94c..07544f670b 100644
--- a/src/test/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitorTest.java
+++ b/src/test/java/com/google/devtools/build/lib/concurrent/AbstractQueueVisitorTest.java
@@ -14,10 +14,7 @@
package com.google.devtools.build.lib.concurrent;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.collect.Lists;
@@ -52,23 +49,24 @@ public class AbstractQueueVisitorTest {
CountingQueueVisitor counter = new CountingQueueVisitor();
counter.enqueue();
counter.awaitQuiescence(/*interruptWorkers=*/ false);
- assertSame(10, counter.getCount());
- assertSame(0, counter.activeParallelTasks());
+ assertThat(counter.getCount()).isSameAs(10);
+ assertThat(counter.activeParallelTasks()).isSameAs(0);
}
@Test
public void callerOwnedPool() throws Exception {
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
- assertSame(0, executor.getActiveCount());
+ assertThat(executor.getActiveCount()).isSameAs(0);
CountingQueueVisitor counter = new CountingQueueVisitor(executor);
counter.enqueue();
counter.awaitQuiescence(/*interruptWorkers=*/ false);
- assertSame(10, counter.getCount());
+ assertThat(counter.getCount()).isSameAs(10);
executor.shutdown();
- assertTrue(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
+ .isTrue();
}
@Test
@@ -77,7 +75,7 @@ public class AbstractQueueVisitorTest {
counter.enqueue();
counter.enqueue();
counter.awaitQuiescence(/*interruptWorkers=*/ false);
- assertSame(10, counter.getCount());
+ assertThat(counter.getCount()).isSameAs(10);
}
@Test
@@ -98,7 +96,7 @@ public class AbstractQueueVisitorTest {
visitor.awaitQuiescence(/*interruptWorkers=*/ false);
fail();
} catch (Exception e) {
- assertSame(myException, e);
+ assertThat(e).isSameAs(myException);
}
}
@@ -131,10 +129,10 @@ public class AbstractQueueVisitorTest {
} catch (Error expected) {
assertThat(expected).hasMessage("Could not create thread (fakeout)");
}
- assertSame(5, counter.getCount());
+ assertThat(counter.getCount()).isSameAs(5);
executor.shutdown();
- assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+ assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
}
// Regression test to make sure that AbstractQueueVisitor doesn't swallow unchecked exceptions if
@@ -149,21 +147,22 @@ public class AbstractQueueVisitorTest {
@Override
public void run() {
threadStarted.countDown();
- assertTrue(
- Uninterruptibles.awaitUninterruptibly(
- visitor.getInterruptionLatchForTestingOnly(), 2, TimeUnit.SECONDS));
+ assertThat(
+ Uninterruptibles.awaitUninterruptibly(
+ visitor.getInterruptionLatchForTestingOnly(), 2, TimeUnit.SECONDS))
+ .isTrue();
throw THROWABLE;
}
});
- assertTrue(threadStarted.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(threadStarted.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue();
// Interrupt will not be processed until work starts.
Thread.currentThread().interrupt();
try {
visitor.awaitQuiescence(/*interruptWorkers=*/ true);
fail();
} catch (Exception e) {
- assertEquals(THROWABLE, e);
- assertTrue(Thread.interrupted());
+ assertThat(e).isEqualTo(THROWABLE);
+ assertThat(Thread.interrupted()).isTrue();
}
}
@@ -195,10 +194,11 @@ public class AbstractQueueVisitorTest {
public void runTest() throws Exception {
latch1.await();
mainThread.interrupt();
- assertTrue(
- visitor
- .getInterruptionLatchForTestingOnly()
- .await(TestUtils.WAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS));
+ assertThat(
+ visitor
+ .getInterruptionLatchForTestingOnly()
+ .await(TestUtils.WAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS))
+ .isTrue();
latch2.countDown();
}
};
@@ -213,7 +213,7 @@ public class AbstractQueueVisitorTest {
}
interrupterThread.joinAndAssertState(400);
- assertTrue(workerThreadCompleted[0]);
+ assertThat(workerThreadCompleted[0]).isTrue();
}
@Test
@@ -258,7 +258,7 @@ public class AbstractQueueVisitorTest {
// Expected.
}
- assertTrue(workerThreadInterrupted[0]);
+ assertThat(workerThreadInterrupted[0]).isTrue();
}
@Test
@@ -287,7 +287,8 @@ public class AbstractQueueVisitorTest {
assertFailFast(executor, false, true, "a", "b");
executor.shutdown();
- assertTrue(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
+ .isTrue();
}
private static void assertFailFast(
@@ -296,7 +297,7 @@ public class AbstractQueueVisitorTest {
boolean interrupt,
String... expectedVisited)
throws Exception {
- assertTrue(executor == null || !executor.isShutdown());
+ assertThat(executor == null || !executor.isShutdown()).isTrue();
AbstractQueueVisitor visitor =
(executor == null)
? new ConcreteQueueVisitor(failFastOnException)
@@ -330,15 +331,16 @@ public class AbstractQueueVisitorTest {
if (interrupt) {
assertThat(e).isInstanceOf(InterruptedException.class);
} else {
- assertSame(THROWABLE, e);
+ assertThat(e).isSameAs(THROWABLE);
}
}
- assertEquals("got: " + visitedList + "\nwant: " + Arrays.toString(expectedVisited),
- Sets.newHashSet(expectedVisited), Sets.newHashSet(visitedList));
+ assertWithMessage("got: " + visitedList + "\nwant: " + Arrays.toString(expectedVisited))
+ .that(Sets.newHashSet(visitedList))
+ .isEqualTo(Sets.newHashSet(expectedVisited));
if (executor != null) {
- assertFalse(executor.isShutdown());
- assertEquals(0, visitor.getTaskCount());
+ assertThat(executor.isShutdown()).isFalse();
+ assertThat(visitor.getTaskCount()).isEqualTo(0);
}
}
@@ -377,12 +379,12 @@ public class AbstractQueueVisitorTest {
visitor.awaitQuiescence(/*interruptWorkers=*/ true);
fail();
} catch (Exception e) {
- assertSame(THROWABLE, e);
+ assertThat(e).isSameAs(THROWABLE);
}
- assertTrue(wasInterrupted.get());
- assertTrue(executor.isShutdown());
- assertTrue(exnLatch.await(0, TimeUnit.MILLISECONDS));
+ assertThat(wasInterrupted.get()).isTrue();
+ assertThat(executor.isShutdown()).isTrue();
+ assertThat(exnLatch.await(0, TimeUnit.MILLISECONDS)).isTrue();
}
@Test
@@ -430,10 +432,10 @@ public class AbstractQueueVisitorTest {
} catch (Error e) {
thrownError = e;
}
- assertTrue(sleepInterrupted.get());
- assertFalse(sleepFinished.get());
- assertEquals(error, thrownError);
- assertTrue(exnLatch.await(0, TimeUnit.MILLISECONDS));
+ assertThat(sleepInterrupted.get()).isTrue();
+ assertThat(sleepFinished.get()).isFalse();
+ assertThat(thrownError).isEqualTo(error);
+ assertThat(exnLatch.await(0, TimeUnit.MILLISECONDS)).isTrue();
}
private static class ClassifiedException extends RuntimeException {
@@ -497,7 +499,7 @@ public class AbstractQueueVisitorTest {
} catch (ClassifiedException e) {
exn = e;
}
- assertEquals(criticalAndLogException, exn);
+ assertThat(exn).isEqualTo(criticalAndLogException);
}
private static Runnable throwingRunnable() {
@@ -532,10 +534,11 @@ public class AbstractQueueVisitorTest {
}
try {
- assertTrue(
- interrupt
- ? visitor.getInterruptionLatchForTestingOnly().await(1, TimeUnit.MINUTES)
- : visitor.getExceptionLatchForTestingOnly().await(1, TimeUnit.MINUTES));
+ assertThat(
+ interrupt
+ ? visitor.getInterruptionLatchForTestingOnly().await(1, TimeUnit.MINUTES)
+ : visitor.getExceptionLatchForTestingOnly().await(1, TimeUnit.MINUTES))
+ .isTrue();
} catch (InterruptedException e) {
// Unexpected.
throw new RuntimeException(e);
diff --git a/src/test/java/com/google/devtools/build/lib/concurrent/KeyedLockerTest.java b/src/test/java/com/google/devtools/build/lib/concurrent/KeyedLockerTest.java
index 9370aeafe5..44cdae52d6 100644
--- a/src/test/java/com/google/devtools/build/lib/concurrent/KeyedLockerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/concurrent/KeyedLockerTest.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.concurrent;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.base.Supplier;
@@ -139,28 +138,29 @@ public abstract class KeyedLockerTest {
throws Exception {
final AtomicReference<Long> currentThreadIdRef = new AtomicReference<>(new Long(-1L));
final AtomicInteger count = new AtomicInteger(0);
- Runnable runnable = new Runnable() {
- @Override
- public void run() {
- Long currentThreadId = Thread.currentThread().getId();
- try (AutoUnlocker unlocker1 = lockFn.get()) {
- currentThreadIdRef.set(currentThreadId);
- try (AutoUnlocker unlocker2 = lockFn.get()) {
- assertEquals(currentThreadId, currentThreadIdRef.get());
- try (AutoUnlocker unlocker3 = lockFn.get()) {
- assertEquals(currentThreadId, currentThreadIdRef.get());
- try (AutoUnlocker unlocker4 = lockFn.get()) {
- assertEquals(currentThreadId, currentThreadIdRef.get());
- try (AutoUnlocker unlocker5 = lockFn.get()) {
- assertEquals(currentThreadId, currentThreadIdRef.get());
- count.incrementAndGet();
+ Runnable runnable =
+ new Runnable() {
+ @Override
+ public void run() {
+ Long currentThreadId = Thread.currentThread().getId();
+ try (AutoUnlocker unlocker1 = lockFn.get()) {
+ currentThreadIdRef.set(currentThreadId);
+ try (AutoUnlocker unlocker2 = lockFn.get()) {
+ assertThat(currentThreadIdRef.get()).isEqualTo(currentThreadId);
+ try (AutoUnlocker unlocker3 = lockFn.get()) {
+ assertThat(currentThreadIdRef.get()).isEqualTo(currentThreadId);
+ try (AutoUnlocker unlocker4 = lockFn.get()) {
+ assertThat(currentThreadIdRef.get()).isEqualTo(currentThreadId);
+ try (AutoUnlocker unlocker5 = lockFn.get()) {
+ assertThat(currentThreadIdRef.get()).isEqualTo(currentThreadId);
+ count.incrementAndGet();
+ }
+ }
}
}
}
}
- }
- }
- };
+ };
for (int i = 0; i < NUM_EXECUTOR_THREADS; i++) {
@SuppressWarnings("unused")
Future<?> possiblyIgnoredError = executorService.submit(wrapper.wrap(runnable));
@@ -171,7 +171,7 @@ public abstract class KeyedLockerTest {
Thread.currentThread().interrupt();
throw new InterruptedException();
}
- assertEquals(NUM_EXECUTOR_THREADS, count.get());
+ assertThat(count.get()).isEqualTo(NUM_EXECUTOR_THREADS);
}
@Test
@@ -218,7 +218,7 @@ public abstract class KeyedLockerTest {
Thread.currentThread().interrupt();
throw new InterruptedException();
}
- assertTrue(runnable2Executed.get());
+ assertThat(runnable2Executed.get()).isTrue();
}
@Test
@@ -230,7 +230,7 @@ public abstract class KeyedLockerTest {
Set<AutoUnlocker> unlockers = new HashSet<>();
for (int i = 0; i < 1000; i++) {
try (AutoUnlocker unlocker = lockFn.get()) {
- assertTrue(unlockers.add(unlocker));
+ assertThat(unlockers.add(unlocker)).isTrue();
}
}
}
@@ -246,23 +246,24 @@ public abstract class KeyedLockerTest {
final AtomicInteger mutexCounter = new AtomicInteger(0);
final AtomicInteger runnableCounter = new AtomicInteger(0);
final AtomicBoolean runnableInterrupted = new AtomicBoolean(false);
- Runnable runnable = new Runnable() {
- @Override
- public void run() {
- runnableLatch.countDown();
- try {
- // Wait until all the Runnables are ready to try to acquire the lock all at once.
- runnableLatch.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- runnableInterrupted.set(true);
- }
- try (AutoUnlocker unlocker = lockFn.get()) {
- runnableCounter.incrementAndGet();
- assertEquals(1, mutexCounter.incrementAndGet());
- assertEquals(0, mutexCounter.decrementAndGet());
- }
- }
- };
+ Runnable runnable =
+ new Runnable() {
+ @Override
+ public void run() {
+ runnableLatch.countDown();
+ try {
+ // Wait until all the Runnables are ready to try to acquire the lock all at once.
+ runnableLatch.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ runnableInterrupted.set(true);
+ }
+ try (AutoUnlocker unlocker = lockFn.get()) {
+ runnableCounter.incrementAndGet();
+ assertThat(mutexCounter.incrementAndGet()).isEqualTo(1);
+ assertThat(mutexCounter.decrementAndGet()).isEqualTo(0);
+ }
+ }
+ };
for (int i = 0; i < NUM_EXECUTOR_THREADS; i++) {
@SuppressWarnings("unused")
Future<?> possiblyIgnoredError = executorService.submit(wrapper.wrap(runnable));
@@ -273,7 +274,7 @@ public abstract class KeyedLockerTest {
Thread.currentThread().interrupt();
throw new InterruptedException();
}
- assertEquals(NUM_EXECUTOR_THREADS, runnableCounter.get());
+ assertThat(runnableCounter.get()).isEqualTo(NUM_EXECUTOR_THREADS);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/concurrent/MoreFuturesTest.java b/src/test/java/com/google/devtools/build/lib/concurrent/MoreFuturesTest.java
index eea935df17..227b9e7249 100644
--- a/src/test/java/com/google/devtools/build/lib/concurrent/MoreFuturesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/concurrent/MoreFuturesTest.java
@@ -14,22 +14,12 @@
package com.google.devtools.build.lib.concurrent;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.devtools.build.lib.testutil.TestUtils;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
@@ -38,6 +28,11 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests for MoreFutures
@@ -72,9 +67,9 @@ public class MoreFuturesTest {
List<Object> result = list.get();
assertThat(result).hasSize(futureList.size());
for (DelayedFuture delayedFuture : futureList) {
- assertFalse(delayedFuture.wasCanceled);
- assertFalse(delayedFuture.wasInterrupted);
- assertNotNull(delayedFuture.get());
+ assertThat(delayedFuture.wasCanceled).isFalse();
+ assertThat(delayedFuture.wasInterrupted).isFalse();
+ assertThat(delayedFuture.get()).isNotNull();
assertThat(result).contains(delayedFuture.get());
}
}
@@ -100,8 +95,8 @@ public class MoreFuturesTest {
}
Thread.sleep(100);
for (DelayedFuture delayedFuture : futureList) {
- assertTrue(delayedFuture.wasCanceled || delayedFuture == toFail);
- assertFalse(delayedFuture.wasInterrupted);
+ assertThat(delayedFuture.wasCanceled || delayedFuture == toFail).isTrue();
+ assertThat(delayedFuture.wasInterrupted).isFalse();
}
}
@@ -115,9 +110,9 @@ public class MoreFuturesTest {
}
MoreFutures.waitForAllInterruptiblyFailFast(futureList);
for (DelayedFuture delayedFuture : futureList) {
- assertFalse(delayedFuture.wasCanceled);
- assertFalse(delayedFuture.wasInterrupted);
- assertNotNull(delayedFuture.get());
+ assertThat(delayedFuture.wasCanceled).isFalse();
+ assertThat(delayedFuture.wasInterrupted).isFalse();
+ assertThat(delayedFuture.get()).isNotNull();
}
}
@@ -188,7 +183,7 @@ public class MoreFuturesTest {
MoreFutures.waitForAllInterruptiblyFailFast(futureList);
fail();
} catch (ExecutionException ee) {
- assertThat(ee.getCause()).hasMessage("I like to fail!!");
+ assertThat(ee).hasCauseThat().hasMessage("I like to fail!!");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/events/AbstractEventHandlerTest.java b/src/test/java/com/google/devtools/build/lib/events/AbstractEventHandlerTest.java
index ab7c9ed761..4863da9852 100644
--- a/src/test/java/com/google/devtools/build/lib/events/AbstractEventHandlerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/events/AbstractEventHandlerTest.java
@@ -13,17 +13,14 @@
// limitations under the License.
package com.google.devtools.build.lib.events;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
+import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Set;
-
-/**
- * Tests {@link AbstractEventHandler}.
- */
+/** Tests {@link AbstractEventHandler}. */
@RunWith(JUnit4.class)
public class AbstractEventHandlerTest {
@@ -36,12 +33,10 @@ public class AbstractEventHandlerTest {
@Test
public void retainsEventMask() {
- assertEquals(EventKind.ALL_EVENTS,
- create(EventKind.ALL_EVENTS).getEventMask());
- assertEquals(EventKind.ERRORS_AND_WARNINGS,
- create(EventKind.ERRORS_AND_WARNINGS).getEventMask());
- assertEquals(EventKind.ERRORS,
- create(EventKind.ERRORS).getEventMask());
+ assertThat(create(EventKind.ALL_EVENTS).getEventMask()).isEqualTo(EventKind.ALL_EVENTS);
+ assertThat(create(EventKind.ERRORS_AND_WARNINGS).getEventMask())
+ .isEqualTo(EventKind.ERRORS_AND_WARNINGS);
+ assertThat(create(EventKind.ERRORS).getEventMask()).isEqualTo(EventKind.ERRORS);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/events/EventCollectorTest.java b/src/test/java/com/google/devtools/build/lib/events/EventCollectorTest.java
index aab4a904ae..ce339c95bd 100644
--- a/src/test/java/com/google/devtools/build/lib/events/EventCollectorTest.java
+++ b/src/test/java/com/google/devtools/build/lib/events/EventCollectorTest.java
@@ -13,9 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.events;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
+import static com.google.common.truth.Truth.assertThat;
import java.util.ArrayList;
import java.util.Collection;
@@ -36,13 +34,13 @@ public class EventCollectorTest extends EventTestTemplate {
EventCollector collector = new EventCollector(EventKind.ALL_EVENTS, events);
collector.handle(event);
Event onlyEvent = events.iterator().next();
- assertEquals(event.getMessage(), onlyEvent.getMessage());
- assertSame(location, onlyEvent.getLocation());
- assertEquals(event.getKind(), onlyEvent.getKind());
- assertEquals(event.getLocation().getStartOffset(),
- onlyEvent.getLocation().getStartOffset());
- assertEquals(1, collector.count());
- assertEquals(1, events.size());
+ assertThat(onlyEvent.getMessage()).isEqualTo(event.getMessage());
+ assertThat(onlyEvent.getLocation()).isSameAs(location);
+ assertThat(onlyEvent.getKind()).isEqualTo(event.getKind());
+ assertThat(onlyEvent.getLocation().getStartOffset())
+ .isEqualTo(event.getLocation().getStartOffset());
+ assertThat(collector.count()).isEqualTo(1);
+ assertThat(events).hasSize(1);
}
@Test
@@ -51,11 +49,11 @@ public class EventCollectorTest extends EventTestTemplate {
collector.handle(event);
Iterator<Event> collectedEventIt = collector.iterator();
Event onlyEvent = collectedEventIt.next();
- assertEquals(event.getMessage(), onlyEvent.getMessage());
- assertSame(location, onlyEvent.getLocation());
- assertEquals(event.getKind(), onlyEvent.getKind());
- assertEquals(event.getLocation().getStartOffset(),
- onlyEvent.getLocation().getStartOffset());
- assertFalse(collectedEventIt.hasNext());
+ assertThat(onlyEvent.getMessage()).isEqualTo(event.getMessage());
+ assertThat(onlyEvent.getLocation()).isSameAs(location);
+ assertThat(onlyEvent.getKind()).isEqualTo(event.getKind());
+ assertThat(onlyEvent.getLocation().getStartOffset())
+ .isEqualTo(event.getLocation().getStartOffset());
+ assertThat(collectedEventIt.hasNext()).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/events/EventSensorTest.java b/src/test/java/com/google/devtools/build/lib/events/EventSensorTest.java
index d765f23038..b98c36eec1 100644
--- a/src/test/java/com/google/devtools/build/lib/events/EventSensorTest.java
+++ b/src/test/java/com/google/devtools/build/lib/events/EventSensorTest.java
@@ -13,9 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.events;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.eventbus.EventBus;
import org.junit.Test;
@@ -30,9 +28,9 @@ public class EventSensorTest extends EventTestTemplate {
@Test
public void sensorStartsOutWithFalse() {
- assertFalse(new EventSensor(EventKind.ALL_EVENTS).wasTriggered());
- assertFalse(new EventSensor(EventKind.ERRORS).wasTriggered());
- assertFalse(new EventSensor(EventKind.ERRORS_AND_WARNINGS).wasTriggered());
+ assertThat(new EventSensor(EventKind.ALL_EVENTS).wasTriggered()).isFalse();
+ assertThat(new EventSensor(EventKind.ERRORS).wasTriggered()).isFalse();
+ assertThat(new EventSensor(EventKind.ERRORS_AND_WARNINGS).wasTriggered()).isFalse();
}
@Test
@@ -40,7 +38,7 @@ public class EventSensorTest extends EventTestTemplate {
EventSensor sensor = new EventSensor(EventKind.ERRORS);
Reporter reporter = new Reporter(new EventBus(), sensor);
reporter.handle(Event.error(location, "An ERROR event."));
- assertTrue(sensor.wasTriggered());
+ assertThat(sensor.wasTriggered()).isTrue();
}
@Test
@@ -49,7 +47,7 @@ public class EventSensorTest extends EventTestTemplate {
Reporter reporter = new Reporter(new EventBus(), sensor);
reporter.handle(Event.error(location, "An ERROR event."));
reporter.handle(Event.warn(location, "A warning event."));
- assertTrue(sensor.wasTriggered());
+ assertThat(sensor.wasTriggered()).isTrue();
}
@Test
@@ -57,7 +55,7 @@ public class EventSensorTest extends EventTestTemplate {
EventSensor sensor = new EventSensor(EventKind.ERRORS_AND_WARNINGS);
Reporter reporter = new Reporter(new EventBus(), sensor);
reporter.handle(Event.info(location, "An INFO event."));
- assertFalse(sensor.wasTriggered());
+ assertThat(sensor.wasTriggered()).isFalse();
}
@Test
@@ -68,8 +66,8 @@ public class EventSensorTest extends EventTestTemplate {
reporter.handle(Event.error(location, "Another ERROR event."));
reporter.handle(Event.warn(location, "A warning event."));
reporter.handle(Event.info(location, "An info event.")); // not in mask
- assertEquals(3, sensor.getTriggerCount());
- assertTrue(sensor.wasTriggered());
+ assertThat(sensor.getTriggerCount()).isEqualTo(3);
+ assertThat(sensor.wasTriggered()).isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/events/EventTest.java b/src/test/java/com/google/devtools/build/lib/events/EventTest.java
index 28e9fe5b25..2bfe0593d8 100644
--- a/src/test/java/com/google/devtools/build/lib/events/EventTest.java
+++ b/src/test/java/com/google/devtools/build/lib/events/EventTest.java
@@ -15,7 +15,6 @@ package com.google.devtools.build.lib.events;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -29,18 +28,18 @@ public class EventTest extends EventTestTemplate {
@Test
public void eventRetainsEventKind() {
- assertEquals(EventKind.WARNING, event.getKind());
+ assertThat(event.getKind()).isEqualTo(EventKind.WARNING);
}
@Test
public void eventRetainsMessage() {
- assertEquals("This is not an error message.", event.getMessage());
+ assertThat(event.getMessage()).isEqualTo("This is not an error message.");
}
@Test
public void eventRetainsLocation() {
- assertEquals(21, event.getLocation().getStartOffset());
- assertEquals(31, event.getLocation().getEndOffset());
+ assertThat(event.getLocation().getStartOffset()).isEqualTo(21);
+ assertThat(event.getLocation().getEndOffset()).isEqualTo(31);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/events/LocationTest.java b/src/test/java/com/google/devtools/build/lib/events/LocationTest.java
index 5c1c8875ac..481ca8d0d0 100644
--- a/src/test/java/com/google/devtools/build/lib/events/LocationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/events/LocationTest.java
@@ -13,11 +13,9 @@
// limitations under the License.
package com.google.devtools.build.lib.events;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -28,31 +26,31 @@ public class LocationTest extends EventTestTemplate {
@Test
public void fromFile() throws Exception {
Location location = Location.fromPathFragment(path);
- assertEquals(path, location.getPath());
- assertEquals(0, location.getStartOffset());
- assertEquals(0, location.getEndOffset());
- assertNull(location.getStartLineAndColumn());
- assertNull(location.getEndLineAndColumn());
- assertEquals(path + ":1", location.print());
+ assertThat(location.getPath()).isEqualTo(path);
+ assertThat(location.getStartOffset()).isEqualTo(0);
+ assertThat(location.getEndOffset()).isEqualTo(0);
+ assertThat(location.getStartLineAndColumn()).isNull();
+ assertThat(location.getEndLineAndColumn()).isNull();
+ assertThat(location.print()).isEqualTo(path + ":1");
}
@Test
public void testPrintRelative() throws Exception {
Location location = Location.fromPathFragment(path);
- assertEquals(
- "/path/to/workspace/my/sample/path.txt:1",
- location.print(PathFragment.create("/some/other/path"), PathFragment.create("baz")));
- assertEquals(
- "new/sample/path.txt:1",
- location.print(PathFragment.create("/path/to/workspace/my"), PathFragment.create("new")));
- assertEquals(
- "new/path.txt:1",
- location.print(
- PathFragment.create("/path/to/workspace/my/sample"), PathFragment.create("new")));
- assertEquals(
- "new:1",
- location.print(
- PathFragment.create("/path/to/workspace/my/sample/path.txt"),
- PathFragment.create("new")));
+ assertThat(location.print(PathFragment.create("/some/other/path"), PathFragment.create("baz")))
+ .isEqualTo("/path/to/workspace/my/sample/path.txt:1");
+ assertThat(
+ location.print(
+ PathFragment.create("/path/to/workspace/my"), PathFragment.create("new")))
+ .isEqualTo("new/sample/path.txt:1");
+ assertThat(
+ location.print(
+ PathFragment.create("/path/to/workspace/my/sample"), PathFragment.create("new")))
+ .isEqualTo("new/path.txt:1");
+ assertThat(
+ location.print(
+ PathFragment.create("/path/to/workspace/my/sample/path.txt"),
+ PathFragment.create("new")))
+ .isEqualTo("new:1");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/events/ReporterTest.java b/src/test/java/com/google/devtools/build/lib/events/ReporterTest.java
index 27617cb5fd..ebaac26578 100644
--- a/src/test/java/com/google/devtools/build/lib/events/ReporterTest.java
+++ b/src/test/java/com/google/devtools/build/lib/events/ReporterTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.events;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus;
@@ -55,7 +54,7 @@ public class ReporterTest extends EventTestTemplate {
reporter.handle(interesting);
reporter.handle(Event.warn(null, "ignore-me").withTag("good"));
- assertEquals(ImmutableList.copyOf(collector), ImmutableList.of(interesting));
+ assertThat(ImmutableList.of(interesting)).isEqualTo(ImmutableList.copyOf(collector));
}
@Test
@@ -67,7 +66,7 @@ public class ReporterTest extends EventTestTemplate {
reporter.handle(e);
}
ImmutableList<Event> got = ImmutableList.copyOf(collector);
- assertEquals(got, want);
+ assertThat(want).isEqualTo(got);
}
@Test
@@ -79,10 +78,10 @@ public class ReporterTest extends EventTestTemplate {
reporter.addHandler(outAppender);
reporter.addHandler(outAppender); // Should have 4 handlers now.
copiedReporter.handle(Event.error(location, "."));
- assertEquals("...", out.toString()); // The copied reporter has 3 handlers.
+ assertThat(out.toString()).isEqualTo("..."); // The copied reporter has 3 handlers.
out = new StringBuilder();
reporter.handle(Event.error(location, "."));
- assertEquals("....", out.toString()); // The old reporter has 4 handlers.
+ assertThat(out.toString()).isEqualTo("...."); // The old reporter has 4 handlers.
}
@Test
@@ -90,7 +89,7 @@ public class ReporterTest extends EventTestTemplate {
assertThat(out.toString()).isEmpty();
reporter.addHandler(outAppender);
reporter.handle(Event.error(location, "Event gets registered."));
- assertEquals("Event gets registered.", out.toString());
+ assertThat(out.toString()).isEqualTo("Event gets registered.");
out = new StringBuilder();
reporter.removeHandler(outAppender);
reporter.handle(Event.error(location, "Event gets ignored."));
diff --git a/src/test/java/com/google/devtools/build/lib/events/SimpleReportersTest.java b/src/test/java/com/google/devtools/build/lib/events/SimpleReportersTest.java
index f99df103d2..d314465bfe 100644
--- a/src/test/java/com/google/devtools/build/lib/events/SimpleReportersTest.java
+++ b/src/test/java/com/google/devtools/build/lib/events/SimpleReportersTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.events;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.eventbus.EventBus;
import org.junit.Test;
@@ -41,6 +41,6 @@ public class SimpleReportersTest extends EventTestTemplate {
reporter.handle(Event.info(location, "Add to handlerCount."));
reporter.handle(Event.info(location, "Add to handlerCount."));
reporter.handle(Event.info(location, "Add to handlerCount."));
- assertEquals(3, handlerCount);
+ assertThat(handlerCount).isEqualTo(3);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/events/StoredErrorEventHandlerTest.java b/src/test/java/com/google/devtools/build/lib/events/StoredErrorEventHandlerTest.java
index 1a8fb6cc62..eff1c507a1 100644
--- a/src/test/java/com/google/devtools/build/lib/events/StoredErrorEventHandlerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/events/StoredErrorEventHandlerTest.java
@@ -13,34 +13,28 @@
// limitations under the License.
package com.google.devtools.build.lib.events;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
-
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.List;
-
-/**
- * Tests the {@link StoredEventHandler} class.
- */
+/** Tests the {@link StoredEventHandler} class. */
@RunWith(JUnit4.class)
public class StoredErrorEventHandlerTest {
@Test
public void hasErrors() {
StoredEventHandler eventHandler = new StoredEventHandler();
- assertFalse(eventHandler.hasErrors());
+ assertThat(eventHandler.hasErrors()).isFalse();
eventHandler.handle(Event.warn("warning"));
- assertFalse(eventHandler.hasErrors());
+ assertThat(eventHandler.hasErrors()).isFalse();
eventHandler.handle(Event.info("info"));
- assertFalse(eventHandler.hasErrors());
+ assertThat(eventHandler.hasErrors()).isFalse();
eventHandler.handle(Event.error("error"));
- assertTrue(eventHandler.hasErrors());
+ assertThat(eventHandler.hasErrors()).isTrue();
}
@Test
@@ -49,7 +43,7 @@ public class StoredErrorEventHandlerTest {
StoredEventHandler sink = new StoredEventHandler();
eventHandler.replayOn(sink);
- assertTrue(sink.isEmpty());
+ assertThat(sink.isEmpty()).isTrue();
}
@Test
@@ -67,6 +61,6 @@ public class StoredErrorEventHandlerTest {
}
eventHandler.replayOn(sink);
- assertEquals(events, sink.getEvents());
+ assertThat(sink.getEvents()).isEqualTo(events);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/exec/DigestTest.java b/src/test/java/com/google/devtools/build/lib/exec/DigestTest.java
index 27edca06d2..a39b438012 100644
--- a/src/test/java/com/google/devtools/build/lib/exec/DigestTest.java
+++ b/src/test/java/com/google/devtools/build/lib/exec/DigestTest.java
@@ -14,10 +14,8 @@
package com.google.devtools.build.lib.exec;
+import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.devtools.build.lib.actions.cache.VirtualActionInput;
import com.google.devtools.build.lib.testutil.Suite;
@@ -46,51 +44,51 @@ public class DigestTest {
@Test
public void testFromString() {
- assertEquals(
- "d41d8cd98f00b204e9800998ecf8427e", Digest.fromContent("".getBytes(UTF_8)).toStringUtf8());
- assertEquals("d41d8cd98f00b204e9800998ecf8427e",
- Digest.fromBuffer(ByteBuffer.wrap(new byte[]{})).toStringUtf8());
+ assertThat(Digest.fromContent("".getBytes(UTF_8)).toStringUtf8())
+ .isEqualTo("d41d8cd98f00b204e9800998ecf8427e");
+ assertThat(Digest.fromBuffer(ByteBuffer.wrap(new byte[] {})).toStringUtf8())
+ .isEqualTo("d41d8cd98f00b204e9800998ecf8427e");
// Whitespace counts.
- assertEquals(
- "7215ee9c7d9dc229d2921a40e899ec5f", Digest.fromContent(" ".getBytes(UTF_8)).toStringUtf8());
- assertEquals(
- "23b58def11b45727d3351702515f86af",
- Digest.fromContent(" ".getBytes(UTF_8)).toStringUtf8());
+ assertThat(Digest.fromContent(" ".getBytes(UTF_8)).toStringUtf8())
+ .isEqualTo("7215ee9c7d9dc229d2921a40e899ec5f");
+ assertThat(Digest.fromContent(" ".getBytes(UTF_8)).toStringUtf8())
+ .isEqualTo("23b58def11b45727d3351702515f86af");
- assertEquals(
- "8b1a9953c4611296a827abf8c47804d7",
- Digest.fromContent("Hello".getBytes(UTF_8)).toStringUtf8());
+ assertThat(Digest.fromContent("Hello".getBytes(UTF_8)).toStringUtf8())
+ .isEqualTo("8b1a9953c4611296a827abf8c47804d7");
- assertEquals(UGLY_DIGEST, Digest.fromContent(UGLY.getBytes(UTF_8)).toStringUtf8());
+ assertThat(Digest.fromContent(UGLY.getBytes(UTF_8)).toStringUtf8()).isEqualTo(UGLY_DIGEST);
// ByteBuffer digest not idempotent because ByteBuffer manages a "position" internally.
ByteBuffer buffer = ByteBuffer.wrap(UGLY.getBytes(UTF_8));
- assertEquals(UGLY_DIGEST, Digest.fromBuffer(buffer).toStringUtf8());
- assertEquals("d41d8cd98f00b204e9800998ecf8427e",
- Digest.fromBuffer(buffer).toStringUtf8());
+ assertThat(Digest.fromBuffer(buffer).toStringUtf8()).isEqualTo(UGLY_DIGEST);
+ assertThat(Digest.fromBuffer(buffer).toStringUtf8())
+ .isEqualTo("d41d8cd98f00b204e9800998ecf8427e");
buffer.rewind();
- assertEquals("e5df5a39f2b8cb71b24e1d8038f93131",
- Digest.fromBuffer(buffer).toStringUtf8());
+ assertThat(Digest.fromBuffer(buffer).toStringUtf8())
+ .isEqualTo("e5df5a39f2b8cb71b24e1d8038f93131");
}
@Test
public void testEmpty() {
- assertFalse(Digest.isEmpty(ByteString.EMPTY));
- assertTrue(Digest.isEmpty(ByteString.copyFromUtf8("d41d8cd98f00b204e9800998ecf8427e")));
- assertTrue(Digest.isEmpty(Digest.EMPTY_DIGEST));
- assertFalse(Digest.isEmpty(ByteString.copyFromUtf8("xyz")));
- assertFalse(Digest.isEmpty(Digest.fromContent(" ".getBytes(UTF_8))));
- assertEquals("d41d8cd98f00b204e9800998ecf8427e", Digest.EMPTY_DIGEST.toStringUtf8());
+ assertThat(Digest.isEmpty(ByteString.EMPTY)).isFalse();
+ assertThat(Digest.isEmpty(ByteString.copyFromUtf8("d41d8cd98f00b204e9800998ecf8427e")))
+ .isTrue();
+ assertThat(Digest.isEmpty(Digest.EMPTY_DIGEST)).isTrue();
+ assertThat(Digest.isEmpty(ByteString.copyFromUtf8("xyz"))).isFalse();
+ assertThat(Digest.isEmpty(Digest.fromContent(" ".getBytes(UTF_8)))).isFalse();
+ assertThat(Digest.EMPTY_DIGEST.toStringUtf8()).isEqualTo("d41d8cd98f00b204e9800998ecf8427e");
}
@Test
public void testIsDigest() {
- assertFalse(Digest.isDigest(null));
- assertFalse(Digest.isDigest(ByteString.EMPTY));
- assertFalse(Digest.isDigest(ByteString.copyFromUtf8("a")));
- assertFalse(Digest.isDigest(ByteString.copyFromUtf8("xyz")));
- assertTrue(Digest.isDigest(ByteString.copyFromUtf8("8b1a9953c4611296a827abf8c47804d7")));
+ assertThat(Digest.isDigest(null)).isFalse();
+ assertThat(Digest.isDigest(ByteString.EMPTY)).isFalse();
+ assertThat(Digest.isDigest(ByteString.copyFromUtf8("a"))).isFalse();
+ assertThat(Digest.isDigest(ByteString.copyFromUtf8("xyz"))).isFalse();
+ assertThat(Digest.isDigest(ByteString.copyFromUtf8("8b1a9953c4611296a827abf8c47804d7")))
+ .isTrue();
}
@Test
@@ -113,8 +111,8 @@ public class DigestTest {
throw new UnsupportedOperationException();
}
});
- assertEquals(UGLY_DIGEST, result.first.toStringUtf8());
- assertEquals(UGLY.length(), result.second.longValue());
+ assertThat(result.first.toStringUtf8()).isEqualTo(UGLY_DIGEST);
+ assertThat(result.second.longValue()).isEqualTo(UGLY.length());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/exec/MiddlemanActionTest.java b/src/test/java/com/google/devtools/build/lib/exec/MiddlemanActionTest.java
index b58554cada..dade507c4c 100644
--- a/src/test/java/com/google/devtools/build/lib/exec/MiddlemanActionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/exec/MiddlemanActionTest.java
@@ -12,11 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.exec;
+
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
@@ -69,8 +68,9 @@ public class MiddlemanActionTest extends BuildViewTestCase {
@Test
public void testActionIsAMiddleman() {
Action middleman = getGeneratingAction(middle);
- assertTrue("Encountered instance of " + middleman.getClass(),
- middleman.getActionType().isMiddleman());
+ assertWithMessage("Encountered instance of " + middleman.getClass())
+ .that(middleman.getActionType().isMiddleman())
+ .isTrue();
}
@Test
@@ -87,18 +87,24 @@ public class MiddlemanActionTest extends BuildViewTestCase {
@Test
public void testMiddlemanIsNullForEmptyInputs() throws Exception {
- assertNull(middlemanFactory.createAggregatingMiddleman(NULL_ACTION_OWNER,
- "middleman_test", new ArrayList<Artifact>(),
- targetConfig.getMiddlemanDirectory(RepositoryName.MAIN)));
+ assertThat(
+ middlemanFactory.createAggregatingMiddleman(
+ NULL_ACTION_OWNER,
+ "middleman_test",
+ new ArrayList<Artifact>(),
+ targetConfig.getMiddlemanDirectory(RepositoryName.MAIN)))
+ .isNull();
}
@Test
public void testMiddlemanIsIdentityForLonelyInput() throws Exception {
- assertEquals(a,
- middlemanFactory.createAggregatingMiddleman(
- NULL_ACTION_OWNER, "middleman_test",
- Lists.newArrayList(a),
- targetConfig.getMiddlemanDirectory(RepositoryName.MAIN)));
+ assertThat(
+ middlemanFactory.createAggregatingMiddleman(
+ NULL_ACTION_OWNER,
+ "middleman_test",
+ Lists.newArrayList(a),
+ targetConfig.getMiddlemanDirectory(RepositoryName.MAIN)))
+ .isEqualTo(a);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/exec/ParameterFileTest.java b/src/test/java/com/google/devtools/build/lib/exec/ParameterFileTest.java
index 5c97c2a2a6..92ea767ca1 100644
--- a/src/test/java/com/google/devtools/build/lib/exec/ParameterFileTest.java
+++ b/src/test/java/com/google/devtools/build/lib/exec/ParameterFileTest.java
@@ -13,14 +13,14 @@
// limitations under the License.
package com.google.devtools.build.lib.exec;
-import static org.junit.Assert.assertEquals;
+
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.actions.ParameterFile;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.testutil.Suite;
import com.google.devtools.build.lib.testutil.TestSpec;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -34,11 +34,9 @@ public class ParameterFileTest extends FoundationTestCase {
@Test
public void testDerive() {
- assertEquals(
- PathFragment.create("a/b-2.params"),
- ParameterFile.derivePath(PathFragment.create("a/b")));
- assertEquals(
- PathFragment.create("b-2.params"),
- ParameterFile.derivePath(PathFragment.create("b")));
+ assertThat(ParameterFile.derivePath(PathFragment.create("a/b")))
+ .isEqualTo(PathFragment.create("a/b-2.params"));
+ assertThat(ParameterFile.derivePath(PathFragment.create("b")))
+ .isEqualTo(PathFragment.create("b-2.params"));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/exec/SingleBuildFileCacheTest.java b/src/test/java/com/google/devtools/build/lib/exec/SingleBuildFileCacheTest.java
index 579fe0c923..3c101c3a1a 100644
--- a/src/test/java/com/google/devtools/build/lib/exec/SingleBuildFileCacheTest.java
+++ b/src/test/java/com/google/devtools/build/lib/exec/SingleBuildFileCacheTest.java
@@ -15,8 +15,6 @@
package com.google.devtools.build.lib.exec;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import com.google.common.io.BaseEncoding;
@@ -28,18 +26,16 @@ import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import com.google.protobuf.ByteString;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/** Tests SingleBuildFileCache. */
@RunWith(JUnit4.class)
@@ -93,7 +89,7 @@ public class SingleBuildFileCacheTest {
underTest.getSizeInBytes(empty);
fail("non existent file should raise exception.");
} catch (IOException expected) {
- assertSame(caught, expected);
+ assertThat(expected).isSameAs(caught);
}
}
@@ -102,21 +98,21 @@ public class SingleBuildFileCacheTest {
ActionInput empty = ActionInputHelper.fromPath("/empty");
underTest.getDigest(empty);
assert(calls.containsKey("/empty"));
- assertEquals(1, (int) calls.get("/empty"));
+ assertThat((int) calls.get("/empty")).isEqualTo(1);
underTest.getDigest(empty);
- assertEquals(1, (int) calls.get("/empty"));
+ assertThat((int) calls.get("/empty")).isEqualTo(1);
}
@Test
public void testBasic() throws Exception {
ActionInput empty = ActionInputHelper.fromPath("/empty");
- assertEquals(0, underTest.getSizeInBytes(empty));
+ assertThat(underTest.getSizeInBytes(empty)).isEqualTo(0);
byte[] digestBytes = underTest.getDigest(empty);
ByteString digest = ByteString.copyFromUtf8(
BaseEncoding.base16().lowerCase().encode(digestBytes));
- assertEquals(EMPTY_MD5, digest.toStringUtf8());
- assertEquals("/empty", underTest.getInputFromDigest(digest).getExecPathString());
+ assertThat(digest.toStringUtf8()).isEqualTo(EMPTY_MD5);
+ assertThat(underTest.getInputFromDigest(digest).getExecPathString()).isEqualTo("/empty");
assert(underTest.contentsAvailableLocally(digest));
ByteString other = ByteString.copyFrom("f41d8cd98f00b204e9800998ecf8427e", "UTF-16");
diff --git a/src/test/java/com/google/devtools/build/lib/packages/AttributeContainerTest.java b/src/test/java/com/google/devtools/build/lib/packages/AttributeContainerTest.java
index df3a9e2430..b9e9c1099c 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/AttributeContainerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/AttributeContainerTest.java
@@ -13,11 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.events.Location.LineAndColumn;
@@ -56,17 +52,17 @@ public class AttributeContainerTest {
Object someValue2 = new Object();
container.setAttributeValueByName(attribute1.getName(), someValue1);
container.setAttributeValueByName(attribute2.getName(), someValue2);
- assertEquals(someValue1, container.getAttr(attribute1.getName()));
- assertEquals(someValue2, container.getAttr(attribute2.getName()));
- assertNull(container.getAttr("nomatch"));
+ assertThat(container.getAttr(attribute1.getName())).isEqualTo(someValue1);
+ assertThat(container.getAttr(attribute2.getName())).isEqualTo(someValue2);
+ assertThat(container.getAttr("nomatch")).isNull();
}
@Test
public void testExplicitSpecificationsByName() throws Exception {
// Name-based setters are automatically considered explicit.
container.setAttributeValueByName(attribute1.getName(), new Object());
- assertTrue(container.isAttributeValueExplicitlySpecified(attribute1));
- assertFalse(container.isAttributeValueExplicitlySpecified("nomatch"));
+ assertThat(container.isAttributeValueExplicitlySpecified(attribute1)).isTrue();
+ assertThat(container.isAttributeValueExplicitlySpecified("nomatch")).isFalse();
}
@Test
@@ -74,8 +70,8 @@ public class AttributeContainerTest {
Object someValue = new Object();
container.setAttributeValue(attribute1, someValue, true);
container.setAttributeValue(attribute2, someValue, false);
- assertTrue(container.isAttributeValueExplicitlySpecified(attribute1));
- assertFalse(container.isAttributeValueExplicitlySpecified(attribute2));
+ assertThat(container.isAttributeValueExplicitlySpecified(attribute1)).isTrue();
+ assertThat(container.isAttributeValueExplicitlySpecified(attribute2)).isFalse();
}
private static Location newLocation() {
@@ -88,9 +84,9 @@ public class AttributeContainerTest {
Location location2 = newLocation();
container.setAttributeLocation(attribute1, location1);
container.setAttributeLocation(attribute2, location2);
- assertEquals(location1, container.getAttributeLocation(attribute1.getName()));
- assertEquals(location2, container.getAttributeLocation(attribute2.getName()));
- assertNull(container.getAttributeLocation("nomatch"));
+ assertThat(container.getAttributeLocation(attribute1.getName())).isEqualTo(location1);
+ assertThat(container.getAttributeLocation(attribute2.getName())).isEqualTo(location2);
+ assertThat(container.getAttributeLocation("nomatch")).isNull();
}
@Test
@@ -108,7 +104,8 @@ public class AttributeContainerTest {
for (int i = 0; i < N; ++i) {
locations[i] = newLocation();
}
- assertTrue(locations[0] != locations[1]); // test relies on checking reference inequality
+ assertThat(locations[0] != locations[1])
+ .isTrue(); // test relies on checking reference inequality
for (int explicitCount = 0; explicitCount <= N; ++explicitCount) {
for (int locationCount = 0; locationCount <= N; ++locationCount) {
AttributeContainer container = new AttributeContainer(ruleClass);
@@ -132,11 +129,12 @@ public class AttributeContainerTest {
}
for (int i = 0; i < N; ++i) {
boolean expected = i < explicitCount;
- assertEquals(expected, container.isAttributeValueExplicitlySpecified(attributes[i]));
+ assertThat(container.isAttributeValueExplicitlySpecified(attributes[i]))
+ .isEqualTo(expected);
}
for (int i = 0; i < N; ++i) {
Location expected = i < locationCount ? locations[i] : null;
- assertSame(expected, container.getAttributeLocation(attributes[i].getName()));
+ assertThat(container.getAttributeLocation(attributes[i].getName())).isSameAs(expected);
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/AttributeTest.java b/src/test/java/com/google/devtools/build/lib/packages/AttributeTest.java
index c6d7ce2476..1f507b57f2 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/AttributeTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/AttributeTest.java
@@ -22,9 +22,6 @@ import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static com.google.devtools.build.lib.syntax.Type.INTEGER;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import static com.google.devtools.build.lib.syntax.Type.STRING_LIST;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Predicates;
@@ -37,39 +34,35 @@ import com.google.devtools.build.lib.packages.Attribute.SplitTransitionProvider;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.FileType;
import com.google.devtools.build.lib.util.FileTypeSet;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
-/**
- * Tests of Attribute code.
- */
+/** Tests of Attribute code. */
@RunWith(JUnit4.class)
public class AttributeTest {
private void assertDefaultValue(Object expected, Attribute attr) {
- assertEquals(expected, attr.getDefaultValue(null));
+ assertThat(attr.getDefaultValue(null)).isEqualTo(expected);
}
private void assertType(Type<?> expectedType, Attribute attr) {
- assertEquals(expectedType, attr.getType());
+ assertThat(attr.getType()).isEqualTo(expectedType);
}
@Test
public void testBasics() throws Exception {
Attribute attr = attr("foo", Type.INTEGER).mandatory().value(3).build();
- assertEquals("foo", attr.getName());
- assertEquals(3, attr.getDefaultValue(null));
- assertEquals(Type.INTEGER, attr.getType());
- assertTrue(attr.isMandatory());
- assertTrue(attr.isDocumented());
+ assertThat(attr.getName()).isEqualTo("foo");
+ assertThat(attr.getDefaultValue(null)).isEqualTo(3);
+ assertThat(attr.getType()).isEqualTo(Type.INTEGER);
+ assertThat(attr.isMandatory()).isTrue();
+ assertThat(attr.isDocumented()).isTrue();
attr = attr("$foo", Type.INTEGER).build();
- assertFalse(attr.isDocumented());
+ assertThat(attr.isDocumented()).isFalse();
}
@Test
@@ -85,9 +78,9 @@ public class AttributeTest {
@Test
public void testNonEmpty() throws Exception {
Attribute attr = attr("foo", BuildType.LABEL_LIST).nonEmpty().legacyAllowAnyFileType().build();
- assertEquals("foo", attr.getName());
- assertEquals(BuildType.LABEL_LIST, attr.getType());
- assertTrue(attr.isNonEmpty());
+ assertThat(attr.getName()).isEqualTo("foo");
+ assertThat(attr.getType()).isEqualTo(BuildType.LABEL_LIST);
+ assertThat(attr.isNonEmpty()).isTrue();
}
@Test
@@ -224,11 +217,11 @@ public class AttributeTest {
{
Attribute childAttr1 = parentAttr.cloneBuilder().build();
- assertEquals("x", childAttr1.getName());
- assertEquals(txtFiles, childAttr1.getAllowedFileTypesPredicate());
- assertEquals(Predicates.alwaysTrue(), childAttr1.getAllowedRuleClassesPredicate());
- assertTrue(childAttr1.isMandatory());
- assertFalse(childAttr1.isNonEmpty());
+ assertThat(childAttr1.getName()).isEqualTo("x");
+ assertThat(childAttr1.getAllowedFileTypesPredicate()).isEqualTo(txtFiles);
+ assertThat(childAttr1.getAllowedRuleClassesPredicate()).isEqualTo(Predicates.alwaysTrue());
+ assertThat(childAttr1.isMandatory()).isTrue();
+ assertThat(childAttr1.isNonEmpty()).isFalse();
assertThat(childAttr1.getAspects(null /* rule */)).hasSize(1);
}
@@ -240,17 +233,17 @@ public class AttributeTest {
.allowedRuleClasses(ruleClasses)
.aspect(TestAspects.ERROR_ASPECT)
.build();
- assertEquals("x", childAttr2.getName());
- assertEquals(txtFiles, childAttr2.getAllowedFileTypesPredicate());
- assertEquals(ruleClasses, childAttr2.getAllowedRuleClassesPredicate());
- assertTrue(childAttr2.isMandatory());
- assertTrue(childAttr2.isNonEmpty());
+ assertThat(childAttr2.getName()).isEqualTo("x");
+ assertThat(childAttr2.getAllowedFileTypesPredicate()).isEqualTo(txtFiles);
+ assertThat(childAttr2.getAllowedRuleClassesPredicate()).isEqualTo(ruleClasses);
+ assertThat(childAttr2.isMandatory()).isTrue();
+ assertThat(childAttr2.isNonEmpty()).isTrue();
assertThat(childAttr2.getAspects(null /* rule */)).hasSize(2);
}
- //Check if the parent attribute is unchanged
- assertFalse(parentAttr.isNonEmpty());
- assertEquals(Predicates.alwaysTrue(), parentAttr.getAllowedRuleClassesPredicate());
+ // Check if the parent attribute is unchanged
+ assertThat(parentAttr.isNonEmpty()).isFalse();
+ assertThat(parentAttr.getAllowedRuleClassesPredicate()).isEqualTo(Predicates.alwaysTrue());
}
/**
@@ -258,10 +251,19 @@ public class AttributeTest {
*/
@Test
public void testConfigurability() {
- assertTrue(attr("foo_configurable", BuildType.LABEL_LIST).legacyAllowAnyFileType().build()
- .isConfigurable());
- assertFalse(attr("foo_nonconfigurable", BuildType.LABEL_LIST).legacyAllowAnyFileType()
- .nonconfigurable("test").build().isConfigurable());
+ assertThat(
+ attr("foo_configurable", BuildType.LABEL_LIST)
+ .legacyAllowAnyFileType()
+ .build()
+ .isConfigurable())
+ .isTrue();
+ assertThat(
+ attr("foo_nonconfigurable", BuildType.LABEL_LIST)
+ .legacyAllowAnyFileType()
+ .nonconfigurable("test")
+ .build()
+ .isConfigurable())
+ .isFalse();
}
@Test
@@ -269,7 +271,7 @@ public class AttributeTest {
TestSplitTransition splitTransition = new TestSplitTransition();
Attribute attr = attr("foo", LABEL).cfg(splitTransition).allowedFileTypes().build();
assertThat(attr.getConfigurationTransition()).isEqualTo(SPLIT);
- assertTrue(attr.hasSplitConfigurationTransition());
+ assertThat(attr.hasSplitConfigurationTransition()).isTrue();
assertThat(attr.getSplitTransition(null)).isEqualTo(splitTransition);
}
@@ -279,15 +281,15 @@ public class AttributeTest {
Attribute attr =
attr("foo", LABEL).cfg(splitTransitionProvider).allowedFileTypes().build();
assertThat(attr.getConfigurationTransition()).isEqualTo(SPLIT);
- assertTrue(attr.hasSplitConfigurationTransition());
- assertTrue(attr.getSplitTransition(null) instanceof TestSplitTransition);
+ assertThat(attr.hasSplitConfigurationTransition()).isTrue();
+ assertThat(attr.getSplitTransition(null) instanceof TestSplitTransition).isTrue();
}
@Test
public void testHostTransition() throws Exception {
Attribute attr = attr("foo", LABEL).cfg(HOST).allowedFileTypes().build();
assertThat(attr.getConfigurationTransition()).isEqualTo(HOST);
- assertFalse(attr.hasSplitConfigurationTransition());
+ assertThat(attr.hasSplitConfigurationTransition()).isFalse();
}
private static class TestSplitTransition implements SplitTransition<BuildOptions> {
diff --git a/src/test/java/com/google/devtools/build/lib/packages/BuildTypeTest.java b/src/test/java/com/google/devtools/build/lib/packages/BuildTypeTest.java
index 63c15d9ef4..97a38b25e8 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/BuildTypeTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/BuildTypeTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
@@ -239,7 +236,7 @@ public class BuildTypeTest {
/* destDir */ null,
/* symlinkBehavior */ null,
/* stripPrefix */ null);
- assertEquals(input, BuildType.FILESET_ENTRY.convert(input, null, currentRule));
+ assertThat(BuildType.FILESET_ENTRY.convert(input, null, currentRule)).isEqualTo(input);
assertThat(collectLabels(BuildType.FILESET_ENTRY, input)).containsExactly(entryLabel);
}
@@ -263,7 +260,7 @@ public class BuildTypeTest {
/* destDir */ null,
/* symlinkBehavior */ null,
/* stripPrefix */ null));
- assertEquals(input, BuildType.FILESET_ENTRY_LIST.convert(input, null, currentRule));
+ assertThat(BuildType.FILESET_ENTRY_LIST.convert(input, null, currentRule)).isEqualTo(input);
assertThat(collectLabels(BuildType.FILESET_ENTRY_LIST, input)).containsExactly(
entry1Label, entry2Label);
}
@@ -278,7 +275,7 @@ public class BuildTypeTest {
"//conditions:b", "//b:b",
Selector.DEFAULT_CONDITION_KEY, "//d:d");
Selector<Label> selector = new Selector<>(input, null, currentRule, BuildType.LABEL);
- assertEquals(BuildType.LABEL, selector.getOriginalType());
+ assertThat(selector.getOriginalType()).isEqualTo(BuildType.LABEL);
Map<Label, Label> expectedMap = ImmutableMap.of(
Label.parseAbsolute("//conditions:a"), Label.create("@//a", "a"),
@@ -300,7 +297,7 @@ public class BuildTypeTest {
new Selector<>(input, null, currentRule, BuildType.LABEL);
fail("Expected Selector instantiation to fail since the input isn't a selection of labels");
} catch (ConversionException e) {
- assertThat(e.getMessage()).contains("invalid label 'not a/../label'");
+ assertThat(e).hasMessageThat().contains("invalid label 'not a/../label'");
}
}
@@ -316,7 +313,7 @@ public class BuildTypeTest {
new Selector<>(input, null, currentRule, BuildType.LABEL);
fail("Expected Selector instantiation to fail since the key isn't a label");
} catch (ConversionException e) {
- assertThat(e.getMessage()).contains("invalid label 'not a/../label'");
+ assertThat(e).hasMessageThat().contains("invalid label 'not a/../label'");
}
}
@@ -329,9 +326,8 @@ public class BuildTypeTest {
"//conditions:a", "//a:a",
"//conditions:b", "//b:b",
BuildType.Selector.DEFAULT_CONDITION_KEY, "//d:d");
- assertEquals(
- Label.create("@//d", "d"),
- new Selector<>(input, null, currentRule, BuildType.LABEL).getDefault());
+ assertThat(new Selector<>(input, null, currentRule, BuildType.LABEL).getDefault())
+ .isEqualTo(Label.create("@//d", "d"));
}
@Test
@@ -343,12 +339,13 @@ public class BuildTypeTest {
BuildType.SelectorList<List<Label>> selectorList = new BuildType.SelectorList<>(
ImmutableList.of(selector1, selector2), null, currentRule, BuildType.LABEL_LIST);
- assertEquals(BuildType.LABEL_LIST, selectorList.getOriginalType());
+ assertThat(selectorList.getOriginalType()).isEqualTo(BuildType.LABEL_LIST);
assertThat(selectorList.getKeyLabels())
- .containsExactlyElementsIn(
- ImmutableSet.of(
- Label.parseAbsolute("//conditions:a"), Label.parseAbsolute("//conditions:b"),
- Label.parseAbsolute("//conditions:c"), Label.parseAbsolute("//conditions:d")));
+ .containsExactly(
+ Label.parseAbsolute("//conditions:a"),
+ Label.parseAbsolute("//conditions:b"),
+ Label.parseAbsolute("//conditions:c"),
+ Label.parseAbsolute("//conditions:d"));
List<Selector<List<Label>>> selectors = selectorList.getSelectors();
assertThat(selectors.get(0).getEntries().entrySet())
@@ -376,7 +373,7 @@ public class BuildTypeTest {
BuildType.LABEL_LIST);
fail("Expected SelectorList initialization to fail on mixed element types");
} catch (ConversionException e) {
- assertThat(e.getMessage()).contains("expected value of type 'list(label)'");
+ assertThat(e).hasMessageThat().contains("expected value of type 'list(label)'");
}
}
@@ -398,7 +395,7 @@ public class BuildTypeTest {
// Conversion to direct type:
Object converted = BuildType
.selectableConvert(BuildType.LABEL_LIST, nativeInput, null, currentRule);
- assertTrue(converted instanceof List<?>);
+ assertThat(converted instanceof List<?>).isTrue();
assertThat((List<Label>) converted).containsExactlyElementsIn(expectedLabels);
// Conversion to selectable type:
@@ -427,7 +424,7 @@ public class BuildTypeTest {
BuildType.LABEL_LIST.convert(selectableInput, null, currentRule);
fail("Expected conversion to fail on a selectable input");
} catch (ConversionException e) {
- assertThat(e.getMessage()).contains("expected value of type 'list(label)'");
+ assertThat(e).hasMessageThat().contains("expected value of type 'list(label)'");
}
}
@@ -436,31 +433,40 @@ public class BuildTypeTest {
*/
@Test
public void testReservedKeyLabels() throws Exception {
- assertFalse(BuildType.Selector.isReservedLabel(Label.parseAbsolute("//condition:a")));
- assertTrue(BuildType.Selector.isReservedLabel(
- Label.parseAbsolute(BuildType.Selector.DEFAULT_CONDITION_KEY)));
+ assertThat(BuildType.Selector.isReservedLabel(Label.parseAbsolute("//condition:a"))).isFalse();
+ assertThat(
+ BuildType.Selector.isReservedLabel(
+ Label.parseAbsolute(BuildType.Selector.DEFAULT_CONDITION_KEY)))
+ .isTrue();
}
@Test
public void testUnconditionalSelects() throws Exception {
- assertFalse(
- new Selector<>(
- ImmutableMap.of("//conditions:a", "//a:a"),
- null, currentRule, BuildType.LABEL
- ).isUnconditional());
- assertFalse(
- new Selector<>(
- ImmutableMap.of(
- "//conditions:a", "//a:a",
- BuildType.Selector.DEFAULT_CONDITION_KEY, "//b:b"),
- null, currentRule, BuildType.LABEL
- ).isUnconditional());
- assertTrue(
- new Selector<>(
- ImmutableMap.of(
- BuildType.Selector.DEFAULT_CONDITION_KEY, "//b:b"),
- null, currentRule, BuildType.LABEL
- ).isUnconditional());
+ assertThat(
+ new Selector<>(
+ ImmutableMap.of("//conditions:a", "//a:a"), null, currentRule, BuildType.LABEL)
+ .isUnconditional())
+ .isFalse();
+ assertThat(
+ new Selector<>(
+ ImmutableMap.of(
+ "//conditions:a",
+ "//a:a",
+ BuildType.Selector.DEFAULT_CONDITION_KEY,
+ "//b:b"),
+ null,
+ currentRule,
+ BuildType.LABEL)
+ .isUnconditional())
+ .isFalse();
+ assertThat(
+ new Selector<>(
+ ImmutableMap.of(BuildType.Selector.DEFAULT_CONDITION_KEY, "//b:b"),
+ null,
+ currentRule,
+ BuildType.LABEL)
+ .isUnconditional())
+ .isTrue();
}
private static FilesetEntry makeFilesetEntry() {
@@ -519,7 +525,8 @@ public class BuildTypeTest {
// with a List<Label> even though this isn't a valid datatype in the
// interpreter.
// Fileset isn't part of bazel, even though FilesetEntry is.
- assertEquals(createExpectedFilesetEntryString('"'), Printer.repr(createTestFilesetEntry()));
+ assertThat(Printer.repr(createTestFilesetEntry()))
+ .isEqualTo(createExpectedFilesetEntryString('"'));
}
@Test
@@ -533,9 +540,8 @@ public class BuildTypeTest {
FilesetEntry entryDereference =
createTestFilesetEntry(FilesetEntry.SymlinkBehavior.DEREFERENCE);
- assertEquals(
- createExpectedFilesetEntryString(FilesetEntry.SymlinkBehavior.DEREFERENCE, '"'),
- Printer.repr(entryDereference));
+ assertThat(Printer.repr(entryDereference))
+ .isEqualTo(createExpectedFilesetEntryString(FilesetEntry.SymlinkBehavior.DEREFERENCE, '"'));
}
private FilesetEntry createStripPrefixFilesetEntry(String stripPrefix) throws Exception {
@@ -585,8 +591,8 @@ public class BuildTypeTest {
@Test
public void testFilesetTypeDefinition() throws Exception {
- assertEquals("FilesetEntry", EvalUtils.getDataTypeName(makeFilesetEntry()));
- assertFalse(EvalUtils.isImmutable(makeFilesetEntry()));
+ assertThat(EvalUtils.getDataTypeName(makeFilesetEntry())).isEqualTo("FilesetEntry");
+ assertThat(EvalUtils.isImmutable(makeFilesetEntry())).isFalse();
}
private static ImmutableList<Label> collectLabels(Type<?> type, Object value)
diff --git a/src/test/java/com/google/devtools/build/lib/packages/EnvironmentGroupTest.java b/src/test/java/com/google/devtools/build/lib/packages/EnvironmentGroupTest.java
index c8e09644fc..f9dde14fbf 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/EnvironmentGroupTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/EnvironmentGroupTest.java
@@ -14,16 +14,12 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.packages.util.PackageLoadingTestCase;
import com.google.devtools.build.lib.vfs.Path;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -62,25 +58,25 @@ public class EnvironmentGroupTest extends PackageLoadingTestCase {
@Test
public void testGroupMembership() throws Exception {
- assertEquals(
- ImmutableSet.of(
- Label.parseAbsolute("//pkg:foo"),
- Label.parseAbsolute("//pkg:bar"),
- Label.parseAbsolute("//pkg:baz")),
- group.getEnvironments());
+ assertThat(group.getEnvironments())
+ .isEqualTo(
+ ImmutableSet.of(
+ Label.parseAbsolute("//pkg:foo"),
+ Label.parseAbsolute("//pkg:bar"),
+ Label.parseAbsolute("//pkg:baz")));
}
@Test
public void testDefaultsMembership() throws Exception {
- assertEquals(ImmutableSet.of(Label.parseAbsolute("//pkg:foo")), group.getDefaults());
+ assertThat(group.getDefaults()).isEqualTo(ImmutableSet.of(Label.parseAbsolute("//pkg:foo")));
}
@Test
public void testIsDefault() throws Exception {
- assertTrue(group.isDefault(Label.parseAbsolute("//pkg:foo")));
- assertFalse(group.isDefault(Label.parseAbsolute("//pkg:bar")));
- assertFalse(group.isDefault(Label.parseAbsolute("//pkg:baz")));
- assertFalse(group.isDefault(Label.parseAbsolute("//pkg:not_in_group")));
+ assertThat(group.isDefault(Label.parseAbsolute("//pkg:foo"))).isTrue();
+ assertThat(group.isDefault(Label.parseAbsolute("//pkg:bar"))).isFalse();
+ assertThat(group.isDefault(Label.parseAbsolute("//pkg:baz"))).isFalse();
+ assertThat(group.isDefault(Label.parseAbsolute("//pkg:not_in_group"))).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/packages/ExportsFilesTest.java b/src/test/java/com/google/devtools/build/lib/packages/ExportsFilesTest.java
index 31ca540590..a968d4aab6 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/ExportsFilesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/ExportsFilesTest.java
@@ -14,8 +14,6 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
@@ -23,19 +21,14 @@ import com.google.devtools.build.lib.events.util.EventCollectionApparatus;
import com.google.devtools.build.lib.packages.util.PackageFactoryApparatus;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.vfs.Path;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
-/**
- * A test for the {@code exports_files} function defined in
- * {@link PackageFactory}.
- */
+/** A test for the {@code exports_files} function defined in {@link PackageFactory}. */
@RunWith(JUnit4.class)
public class ExportsFilesTest {
@@ -53,7 +46,7 @@ public class ExportsFilesTest {
public void testExportsFilesRegistersFilesWithPackage() throws Exception {
List<String> names = getFileNamesOf(pkg());
String expected = "//pkg:BUILD //pkg:bar.txt //pkg:foo.txt";
- assertEquals(expected, Joiner.on(' ').join(names));
+ assertThat(Joiner.on(' ').join(names)).isEqualTo(expected);
}
/**
@@ -83,8 +76,8 @@ public class ExportsFilesTest {
@Test
public void testRegisteredFilesAreRetrievable() throws Exception {
Package pkg = pkg();
- assertEquals("foo.txt", pkg.getTarget("foo.txt").getName());
- assertEquals("bar.txt", pkg.getTarget("bar.txt").getName());
+ assertThat(pkg.getTarget("foo.txt").getName()).isEqualTo("foo.txt");
+ assertThat(pkg.getTarget("bar.txt").getName()).isEqualTo("bar.txt");
}
@Test
@@ -98,7 +91,7 @@ public class ExportsFilesTest {
Package pkg = packages.createPackage("pkg2", buildFile);
events.assertContainsError("rule 'foo' in package 'pkg2' conflicts with "
+ "existing source file");
- assertTrue(pkg.getTarget("foo") instanceof InputFile);
+ assertThat(pkg.getTarget("foo") instanceof InputFile).isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/ExternalPackageTest.java b/src/test/java/com/google/devtools/build/lib/packages/ExternalPackageTest.java
index e229cee1b0..0dd6dfb787 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/ExternalPackageTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/ExternalPackageTest.java
@@ -13,12 +13,11 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -52,7 +51,8 @@ public class ExternalPackageTest extends BuildViewTestCase {
invalidatePackages(/*alsoConfigs=*/false);
// Make sure the second rule "wins."
- assertEquals("new_local_repository rule", getTarget("//external:my_rule").getTargetKind());
+ assertThat(getTarget("//external:my_rule").getTargetKind())
+ .isEqualTo("new_local_repository rule");
}
@Test
@@ -70,6 +70,7 @@ public class ExternalPackageTest extends BuildViewTestCase {
invalidatePackages(/*alsoConfigs=*/false);
// Make sure the second rule "wins."
- assertEquals("new_local_repository rule", getTarget("//external:my_rule").getTargetKind());
+ assertThat(getTarget("//external:my_rule").getTargetKind())
+ .isEqualTo("new_local_repository rule");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunctionTest.java b/src/test/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunctionTest.java
index 321562475f..97f12b81ff 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/ImplicitOutputsFunctionTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -22,11 +21,6 @@ import com.google.devtools.build.lib.packages.ImplicitOutputsFunction.AttributeV
import com.google.devtools.build.lib.testutil.Suite;
import com.google.devtools.build.lib.testutil.TestSpec;
import com.google.devtools.build.lib.util.Preconditions;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -34,6 +28,9 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests for {@link ImplicitOutputsFunction}.
@@ -44,10 +41,10 @@ public final class ImplicitOutputsFunctionTest {
private void assertPlaceholderCollection(
String template, String expectedTemplate, String... expectedPlaceholders) throws Exception {
List<String> actualPlaceholders = new ArrayList<>();
- assertEquals(
- expectedTemplate,
- ImplicitOutputsFunction.createPlaceholderSubstitutionFormatString(
- template, actualPlaceholders));
+ assertThat(
+ ImplicitOutputsFunction.createPlaceholderSubstitutionFormatString(
+ template, actualPlaceholders))
+ .isEqualTo(expectedTemplate);
assertThat(actualPlaceholders)
.containsExactlyElementsIn(Arrays.asList(expectedPlaceholders))
.inOrder();
@@ -146,7 +143,8 @@ public final class ImplicitOutputsFunctionTest {
assertThat(foundAttributes)
.containsExactlyElementsIn(Arrays.asList(expectedFoundPlaceholders))
.inOrder();
- assertThat(substitutions).containsExactlyElementsIn(Arrays.asList(expectedSubstitutions));
+ assertThat(substitutions)
+ .containsExactlyElementsIn(Arrays.asList(expectedSubstitutions));
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/packages/InputFileTest.java b/src/test/java/com/google/devtools/build/lib/packages/InputFileTest.java
index 021c20a246..a7d78399e1 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/InputFileTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/InputFileTest.java
@@ -13,16 +13,14 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+import com.google.common.testing.EqualsTester;
import com.google.devtools.build.lib.events.util.EventCollectionApparatus;
import com.google.devtools.build.lib.packages.util.PackageFactoryApparatus;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.vfs.Path;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -59,20 +57,20 @@ public class InputFileTest {
}
private static void checkPathMatches(InputFile input, Path expectedPath) {
- assertEquals(expectedPath, input.getPath());
+ assertThat(input.getPath()).isEqualTo(expectedPath);
}
private static void checkName(InputFile input, String expectedName) {
- assertEquals(expectedName, input.getName());
+ assertThat(input.getName()).isEqualTo(expectedName);
}
private static void checkLabel(InputFile input, String expectedLabelString) {
- assertEquals(expectedLabelString, input.getLabel().toString());
+ assertThat(input.getLabel().toString()).isEqualTo(expectedLabelString);
}
@Test
public void testGetAssociatedRule() throws Exception {
- assertNull(null, pkg.getTarget("x").getAssociatedRule());
+ assertWithMessage(null).that(pkg.getTarget("x").getAssociatedRule()).isNull();
}
@Test
@@ -81,7 +79,7 @@ public class InputFileTest {
checkPathMatches(inputFileX, pathX);
checkName(inputFileX, "x");
checkLabel(inputFileX, "//pkg:x");
- assertEquals("source file", inputFileX.getTargetKind());
+ assertThat(inputFileX.getTargetKind()).isEqualTo("source file");
}
@Test
@@ -95,11 +93,12 @@ public class InputFileTest {
@Test
public void testEquivalenceRelation() throws NoSuchTargetException {
InputFile inputFileX = (InputFile) pkg.getTarget("x");
- assertSame(pkg.getTarget("x"), inputFileX);
+ assertThat(inputFileX).isSameAs(pkg.getTarget("x"));
InputFile inputFileY = (InputFile) pkg.getTarget("subdir/y");
- assertSame(pkg.getTarget("subdir/y"), inputFileY);
- assertEquals(inputFileX, inputFileX);
- assertFalse(inputFileX.equals(inputFileY));
- assertFalse(inputFileY.equals(inputFileX));
+ assertThat(inputFileY).isSameAs(pkg.getTarget("subdir/y"));
+ new EqualsTester()
+ .addEqualityGroup(inputFileX)
+ .addEqualityGroup(inputFileY)
+ .testEquals();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/LicenseTest.java b/src/test/java/com/google/devtools/build/lib/packages/LicenseTest.java
index 0032dc8ba9..845f0b519c 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/LicenseTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/LicenseTest.java
@@ -13,28 +13,26 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.packages.License.LicenseType;
-
+import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Arrays;
-
@RunWith(JUnit4.class)
public class LicenseTest {
@Test
public void testLeastRestrictive() {
- assertEquals(
- LicenseType.RESTRICTED, License.leastRestrictive(Arrays.asList(LicenseType.RESTRICTED)));
- assertEquals(
- LicenseType.RESTRICTED,
- License.leastRestrictive(
- Arrays.asList(LicenseType.RESTRICTED, LicenseType.BY_EXCEPTION_ONLY)));
- assertEquals(
- LicenseType.BY_EXCEPTION_ONLY, License.leastRestrictive(Arrays.<LicenseType>asList()));
+ assertThat(License.leastRestrictive(Arrays.asList(LicenseType.RESTRICTED)))
+ .isEqualTo(LicenseType.RESTRICTED);
+ assertThat(
+ License.leastRestrictive(
+ Arrays.asList(LicenseType.RESTRICTED, LicenseType.BY_EXCEPTION_ONLY)))
+ .isEqualTo(LicenseType.RESTRICTED);
+ assertThat(License.leastRestrictive(Arrays.<LicenseType>asList()))
+ .isEqualTo(LicenseType.BY_EXCEPTION_ONLY);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/OutputFileTest.java b/src/test/java/com/google/devtools/build/lib/packages/OutputFileTest.java
index 34a3a9bbb7..57b7c59090 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/OutputFileTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/OutputFileTest.java
@@ -13,14 +13,12 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
+import static com.google.common.truth.Truth.assertThat;
+import com.google.common.testing.EqualsTester;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.packages.util.PackageLoadingTestCase;
import com.google.devtools.build.lib.vfs.Path;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -49,20 +47,20 @@ public class OutputFileTest extends PackageLoadingTestCase {
}
private void checkTargetRetainsGeneratingRule(OutputFile output) throws Exception {
- assertSame(rule, output.getGeneratingRule());
+ assertThat(output.getGeneratingRule()).isSameAs(rule);
}
private void checkName(OutputFile output, String expectedName) throws Exception {
- assertEquals(expectedName, output.getName());
+ assertThat(output.getName()).isEqualTo(expectedName);
}
private void checkLabel(OutputFile output, String expectedLabelString) throws Exception {
- assertEquals(expectedLabelString, output.getLabel().toString());
+ assertThat(output.getLabel().toString()).isEqualTo(expectedLabelString);
}
@Test
public void testGetAssociatedRule() throws Exception {
- assertSame(rule, pkg.getTarget("x").getAssociatedRule());
+ assertThat(pkg.getTarget("x").getAssociatedRule()).isSameAs(rule);
}
@Test
@@ -71,7 +69,7 @@ public class OutputFileTest extends PackageLoadingTestCase {
checkTargetRetainsGeneratingRule(outputFileX);
checkName(outputFileX, "x");
checkLabel(outputFileX, "//pkg:x");
- assertEquals("generated file", outputFileX.getTargetKind());
+ assertThat(outputFileX.getTargetKind()).isEqualTo("generated file");
}
@Test
@@ -88,16 +86,12 @@ public class OutputFileTest extends PackageLoadingTestCase {
OutputFile outputFileX2 = (OutputFile) pkg.getTarget("x");
OutputFile outputFileY1 = (OutputFile) pkg.getTarget("subdir/y");
OutputFile outputFileY2 = (OutputFile) pkg.getTarget("subdir/y");
- assertSame(outputFileX1, outputFileX2);
- assertSame(outputFileY1, outputFileY2);
- assertEquals(outputFileX1, outputFileX2);
- assertEquals(outputFileX2, outputFileX1);
- assertEquals(outputFileY1, outputFileY2);
- assertEquals(outputFileY2, outputFileY1);
- assertFalse(outputFileX1.equals(outputFileY1));
- assertFalse(outputFileY1.equals(outputFileX1));
- assertEquals(outputFileX1.hashCode(), outputFileX2.hashCode());
- assertEquals(outputFileY1.hashCode(), outputFileY2.hashCode());
+ assertThat(outputFileX2).isSameAs(outputFileX1);
+ assertThat(outputFileY2).isSameAs(outputFileY1);
+ new EqualsTester()
+ .addEqualityGroup(outputFileX1, outputFileX2)
+ .addEqualityGroup(outputFileY1, outputFileY2)
+ .testEquals();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java b/src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java
index 99c811d729..a7457c74cf 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java
@@ -15,12 +15,6 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -61,7 +55,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
public void testCreatePackage() throws Exception {
Path buildFile = scratch.file("/pkgname/BUILD", "# empty build file ");
Package pkg = packages.createPackage("pkgname", buildFile);
- assertEquals("pkgname", pkg.getName());
+ assertThat(pkg.getName()).isEqualTo("pkgname");
assertThat(Sets.newHashSet(pkg.getTargets(Rule.class))).isEmpty();
}
@@ -83,10 +77,11 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
// wait for all to finish
e.shutdown();
- assertTrue(e.awaitTermination(TestUtils.WAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS));
+ assertThat(e.awaitTermination(TestUtils.WAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS))
+ .isTrue();
log.removeHandler(parser);
log.setLevel(originalLevel);
- assertTrue(parser.hasParsed());
+ assertThat(parser.hasParsed()).isTrue();
}
@Test
@@ -97,7 +92,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.createPackage("badrulename", buildFile);
events.assertContainsError("cc_library 'name' attribute must be a string");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
}
@Test
@@ -108,7 +103,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.createPackage("badrulename", buildFile);
events.assertContainsError("cc_library rule has no 'name' attribute");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
}
@Test
@@ -120,7 +115,8 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
emptyBuildFile("not even a legal/.../label"));
fail();
} catch (NoSuchPackageException e) {
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.contains(
"no such package 'not even a legal/.../label': "
+ "illegal package name: 'not even a legal/.../label' ");
@@ -138,16 +134,16 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
events.assertContainsError("target names may not contain ':'");
assertThat(pkg.getTargets(FileTarget.class).toString())
.doesNotContain("houseads/house_ads:ca-aol_parenting_html");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
}
@Test
public void testPackageNameWithPROTECTEDIsOk() throws Exception {
events.setFailFast(false);
// One "PROTECTED":
- assertTrue(isValidPackageName("foo/PROTECTED/bar"));
+ assertThat(isValidPackageName("foo/PROTECTED/bar")).isTrue();
// Multiple "PROTECTED"s:
- assertTrue(isValidPackageName("foo/PROTECTED/bar/PROTECTED/wiz"));
+ assertThat(isValidPackageName("foo/PROTECTED/bar/PROTECTED/wiz")).isTrue();
}
@Test
@@ -164,7 +160,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
events.assertContainsError(
"cc_library rule 'spell_proto' in package "
+ "'duplicaterulename' conflicts with existing proto_library rule");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
}
@Test
@@ -179,11 +175,11 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.createPackage("has_dupe", buildFile);
events.assertContainsError(
"Label '//has_dupe:dep' is duplicated in the 'deps' " + "attribute of rule 'has_dupe'");
- assertTrue(pkg.containsErrors());
- assertNotNull(pkg.getRule("has_dupe"));
- assertNotNull(pkg.getRule("dep"));
- assertTrue(pkg.getRule("has_dupe").containsErrors());
- assertTrue(pkg.getRule("dep").containsErrors()); // because all rules in an
+ assertThat(pkg.containsErrors()).isTrue();
+ assertThat(pkg.getRule("has_dupe")).isNotNull();
+ assertThat(pkg.getRule("dep")).isNotNull();
+ assertThat(pkg.getRule("has_dupe").containsErrors()).isTrue();
+ assertThat(pkg.getRule("dep").containsErrors()).isTrue(); // because all rules in an
// errant package are
// themselves errant.
}
@@ -245,10 +241,10 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.createPackage("pina", buildFile);
events.assertNoWarningsOrErrors();
- assertFalse(pkg.containsErrors());
- assertNotNull(pkg.getRule("pina-colada"));
- assertFalse(pkg.getRule("pina-colada").containsErrors());
- assertSame(1, Sets.newHashSet(pkg.getTargets(Rule.class)).size());
+ assertThat(pkg.containsErrors()).isFalse();
+ assertThat(pkg.getRule("pina-colada")).isNotNull();
+ assertThat(pkg.getRule("pina-colada").containsErrors()).isFalse();
+ assertThat(Sets.newHashSet(pkg.getTargets(Rule.class)).size()).isSameAs(1);
}
@Test
@@ -257,10 +253,10 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.createPackage("pina", buildFile);
events.assertNoWarningsOrErrors();
- assertFalse(pkg.containsErrors());
- assertNotNull(pkg.getRule("pina-colada"));
- assertFalse(pkg.getRule("pina-colada").containsErrors());
- assertSame(1, Sets.newHashSet(pkg.getTargets(Rule.class)).size());
+ assertThat(pkg.containsErrors()).isFalse();
+ assertThat(pkg.getRule("pina-colada")).isNotNull();
+ assertThat(pkg.getRule("pina-colada").containsErrors()).isFalse();
+ assertThat(Sets.newHashSet(pkg.getTargets(Rule.class)).size()).isSameAs(1);
}
@Test
@@ -313,7 +309,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
events.assertContainsError(
"cc_library rule 'spell_proto' in package "
+ "'multipleduplicaterulename' conflicts with existing proto_library rule");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
}
@Test
@@ -322,10 +318,10 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.createPackage("foo", buildFile);
Target target = pkg.getTarget("BUILD");
- assertEquals("BUILD", target.getName());
+ assertThat(target.getName()).isEqualTo("BUILD");
// Test that it's memoized:
- assertSame(target, pkg.getTarget("BUILD"));
+ assertThat(pkg.getTarget("BUILD")).isSameAs(target);
}
@Test
@@ -338,16 +334,16 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
"cc_library(name='X', srcs=['X'])",
"cc_library(name='Y')");
Package pkg = packages.createPackage("foo", buildFile);
- assertFalse(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isFalse();
// X is a rule with a circular self-dependency.
- assertSame(Rule.class, pkg.getTarget("X").getClass());
+ assertThat(pkg.getTarget("X").getClass()).isSameAs(Rule.class);
// Y is a rule
- assertSame(Rule.class, pkg.getTarget("Y").getClass());
+ assertThat(pkg.getTarget("Y").getClass()).isSameAs(Rule.class);
// Z is a file
- assertSame(InputFile.class, pkg.getTarget("Z").getClass());
+ assertThat(pkg.getTarget("Z").getClass()).isSameAs(InputFile.class);
// A is nothing
try {
@@ -365,7 +361,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
for (InputFile inputFile : pkg.getTargets(InputFile.class)) {
inputFiles.add(inputFile.getName());
}
- assertEquals(ImmutableList.of("BUILD", "Z"), Lists.newArrayList(inputFiles));
+ assertThat(Lists.newArrayList(inputFiles)).containsExactly("BUILD", "Z").inOrder();
}
@Test
@@ -378,7 +374,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
"third-party rule '//third_party/foo:bar' lacks a license "
+ "declaration with one of the following types: "
+ "notice, reciprocal, permissive, restricted, unencumbered, by_exception_only");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
}
@Test
@@ -390,7 +386,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
"third-party file 'bar' lacks a license "
+ "declaration with one of the following types: "
+ "notice, reciprocal, permissive, restricted, unencumbered, by_exception_only");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
}
@Test
@@ -409,12 +405,12 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
events.assertContainsError(
"cc_library rule 'dup_proto' in package 'dup' "
+ "conflicts with existing proto_library rule");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
Rule dupProto = pkg.getRule("dup_proto");
// Check that the first rule of the given name "wins", and that each of the
// "winning" rule's outputs is a member of the package.
- assertEquals("proto_library", dupProto.getRuleClass());
+ assertThat(dupProto.getRuleClass()).isEqualTo("proto_library");
for (OutputFile out : dupProto.getOutputFiles()) {
assertThat(pkg.getTargets(FileTarget.class)).contains(out);
}
@@ -443,12 +439,13 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
events.assertContainsError(
"generated file 'out2' in rule 'rule2' "
+ "conflicts with existing generated file from rule 'rule1'");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
- assertNull(pkg.getRule("rule2"));
+ assertThat(pkg.getRule("rule2")).isNull();
// Ensure that rule2's "out2" didn't overwrite rule1's:
- assertSame(pkg.getRule("rule1"), ((OutputFile) pkg.getTarget("out2")).getGeneratingRule());
+ assertThat(((OutputFile) pkg.getTarget("out2")).getGeneratingRule())
+ .isSameAs(pkg.getRule("rule1"));
// None of rule2, its inputs, or its outputs should belong to pkg:
List<Target> found = new ArrayList<>();
@@ -483,17 +480,18 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.createPackage("error", path);
events.assertContainsError("name 'PopulateList' is not defined");
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
// rule1 would be fine but is still marked as in error:
- assertTrue(pkg.getRule("rule1").containsErrors());
+ assertThat(pkg.getRule("rule1").containsErrors()).isTrue();
// rule2 is considered "in error" because it's after an error.
// Indeed, it has the wrong "outs" set because the call to PopulateList
// failed.
Rule rule2 = pkg.getRule("rule2");
- assertTrue(rule2.containsErrors());
- assertEquals(Sets.newHashSet(pkg.getTarget("bad")), Sets.newHashSet(rule2.getOutputFiles()));
+ assertThat(rule2.containsErrors()).isTrue();
+ assertThat(Sets.newHashSet(rule2.getOutputFiles()))
+ .isEqualTo(Sets.newHashSet(pkg.getTarget("bad")));
}
@Test
@@ -505,7 +503,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.createPackage("x", path);
- assertNotNull(pkg.getTarget("x.cc")); // existing and mentioned.
+ assertThat(pkg.getTarget("x.cc")).isNotNull(); // existing and mentioned.
try {
pkg.getTarget("y.cc"); // existing but not mentioned.
@@ -879,7 +877,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
@Test
public void testPackageSpecMinimal() throws Exception {
Package pkg = expectEvalSuccess("package(default_visibility=[])");
- assertNotNull(pkg.getDefaultVisibility());
+ assertThat(pkg.getDefaultVisibility()).isNotNull();
}
@Test
@@ -908,21 +906,21 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
@Test
public void testDefaultTestonly() throws Exception {
Package pkg = expectEvalSuccess("package(default_testonly = 1)");
- assertTrue(pkg.getDefaultTestOnly());
+ assertThat(pkg.getDefaultTestOnly()).isTrue();
}
@Test
public void testDefaultDeprecation() throws Exception {
String testMessage = "OMG PONIES!";
Package pkg = expectEvalSuccess("package(default_deprecation = \"" + testMessage + "\")");
- assertEquals(testMessage, pkg.getDefaultDeprecation());
+ assertThat(pkg.getDefaultDeprecation()).isEqualTo(testMessage);
}
@Test
public void testExportsBuildFile() throws Exception {
Package pkg =
expectEvalSuccess("exports_files(['BUILD'], visibility=['//visibility:private'])");
- assertEquals(pkg.getBuildFile(), pkg.getTarget("BUILD"));
+ assertThat(pkg.getTarget("BUILD")).isEqualTo(pkg.getBuildFile());
}
@Test
@@ -938,7 +936,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Rule fooRule = (Rule) pkg.getTarget("bar");
String deprAttr =
attributes(fooRule).get("deprecation", com.google.devtools.build.lib.syntax.Type.STRING);
- assertEquals(msg, deprAttr);
+ assertThat(deprAttr).isEqualTo(msg);
}
@Test
@@ -952,12 +950,14 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Package pkg = packages.eval("foo", file);
Rule fooRule = (Rule) pkg.getTarget("foo");
- assertTrue(
- attributes(fooRule).get("testonly", com.google.devtools.build.lib.syntax.Type.BOOLEAN));
+ assertThat(
+ attributes(fooRule).get("testonly", com.google.devtools.build.lib.syntax.Type.BOOLEAN))
+ .isTrue();
Rule barRule = (Rule) pkg.getTarget("bar");
- assertFalse(
- attributes(barRule).get("testonly", com.google.devtools.build.lib.syntax.Type.BOOLEAN));
+ assertThat(
+ attributes(barRule).get("testonly", com.google.devtools.build.lib.syntax.Type.BOOLEAN))
+ .isFalse();
}
@Test
@@ -974,7 +974,7 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
Rule fooRule = (Rule) pkg.getTarget("bar");
String deprAttr =
attributes(fooRule).get("deprecation", com.google.devtools.build.lib.syntax.Type.STRING);
- assertEquals(msg, deprAttr);
+ assertThat(deprAttr).isEqualTo(msg);
}
@Test
@@ -1001,12 +1001,12 @@ public class PackageFactoryTest extends PackageFactoryTestBase {
scratch.file("/e/data.txt");
throwOnReaddir = parentDir;
Package pkg = packages.createPackage("e", buildFile);
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
events.setFailFast(true);
throwOnReaddir = null;
pkg = packages.createPackage("e", buildFile);
- assertFalse(pkg.containsErrors());
- assertNotNull(pkg.getRule("e"));
+ assertThat(pkg.containsErrors()).isFalse();
+ assertThat(pkg.getRule("e")).isNotNull();
GlobList globList = (GlobList) pkg.getRule("e").getAttributeContainer().getAttr("data");
assertThat(globList).containsExactly(Label.parseAbsolute("//e:data.txt"));
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/PackageGroupStaticInitializationTest.java b/src/test/java/com/google/devtools/build/lib/packages/PackageGroupStaticInitializationTest.java
index f05709d4e4..e778d89898 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/PackageGroupStaticInitializationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/PackageGroupStaticInitializationTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertFalse;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.RepositoryName;
@@ -83,8 +83,8 @@ public class PackageGroupStaticInitializationTest {
producingThread.start();
producingThread.join(3000);
consumingThread.join(3000);
- assertFalse(producingThread.isAlive());
- assertFalse(consumingThread.isAlive());
+ assertThat(producingThread.isAlive()).isFalse();
+ assertThat(consumingThread.isAlive()).isFalse();
}
private Package getPackage(String packageName) throws Exception {
diff --git a/src/test/java/com/google/devtools/build/lib/packages/PackageGroupTest.java b/src/test/java/com/google/devtools/build/lib/packages/PackageGroupTest.java
index 55e8da9c21..7bb8caeb17 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/PackageGroupTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/PackageGroupTest.java
@@ -14,10 +14,7 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.events.util.EventCollectionApparatus;
import com.google.devtools.build.lib.packages.util.PackageFactoryApparatus;
import com.google.devtools.build.lib.testutil.Scratch;
@@ -64,8 +61,8 @@ public class PackageGroupTest {
scratch.file("fruits/vegetables/BUILD");
PackageGroup grp = getPackageGroup("fruits", "apple");
- assertTrue(grp.contains(getPackage("vegetables")));
- assertFalse(grp.contains(getPackage("fruits/vegetables")));
+ assertThat(grp.contains(getPackage("vegetables"))).isTrue();
+ assertThat(grp.contains(getPackage("fruits/vegetables"))).isFalse();
}
@Test
@@ -150,7 +147,7 @@ public class PackageGroupTest {
scratch.file("fruits/BUILD", "package_group(name = 'mango', packages = ['//...'])");
PackageGroup packageGroup = getPackageGroup("fruits", "mango");
assertThat(packageGroup.getPackageSpecifications())
- .containsExactlyElementsIn(ImmutableList.of(PackageSpecification.everything()));
+ .containsExactly(PackageSpecification.everything());
}
private Package getPackage(String packageName) throws Exception {
diff --git a/src/test/java/com/google/devtools/build/lib/packages/RelativePackageNameResolverTest.java b/src/test/java/com/google/devtools/build/lib/packages/RelativePackageNameResolverTest.java
index fee2a7c3d2..7ddc2bc83e 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/RelativePackageNameResolverTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/RelativePackageNameResolverTest.java
@@ -13,11 +13,10 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -117,6 +116,6 @@ public class RelativePackageNameResolverTest {
private void assertResolvesTo(String relative, String expectedAbsolute) throws Exception {
String result = resolver.resolve(relative);
- assertEquals(expectedAbsolute, result);
+ assertThat(result).isEqualTo(expectedAbsolute);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/RuleClassBuilderTest.java b/src/test/java/com/google/devtools/build/lib/packages/RuleClassBuilderTest.java
index e906b9572e..b93fe6c836 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/RuleClassBuilderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/RuleClassBuilderTest.java
@@ -19,14 +19,10 @@ import static com.google.devtools.build.lib.syntax.Type.BOOLEAN;
import static com.google.devtools.build.lib.syntax.Type.INTEGER;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import static com.google.devtools.build.lib.syntax.Type.STRING_LIST;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType;
import com.google.devtools.build.lib.packages.util.PackageLoadingTestCase;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -55,18 +51,18 @@ public class RuleClassBuilderTest extends PackageLoadingTestCase {
.add(attr("X", com.google.devtools.build.lib.syntax.Type.INTEGER).mandatory())
.build();
- assertEquals("ruleA", ruleClassA.getName());
- assertEquals(3, ruleClassA.getAttributeCount());
- assertTrue(ruleClassA.hasBinaryOutput());
+ assertThat(ruleClassA.getName()).isEqualTo("ruleA");
+ assertThat(ruleClassA.getAttributeCount()).isEqualTo(3);
+ assertThat(ruleClassA.hasBinaryOutput()).isTrue();
- assertEquals(0, (int) ruleClassA.getAttributeIndex("srcs"));
- assertEquals(ruleClassA.getAttribute(0), ruleClassA.getAttributeByName("srcs"));
+ assertThat((int) ruleClassA.getAttributeIndex("srcs")).isEqualTo(0);
+ assertThat(ruleClassA.getAttributeByName("srcs")).isEqualTo(ruleClassA.getAttribute(0));
- assertEquals(1, (int) ruleClassA.getAttributeIndex("tags"));
- assertEquals(ruleClassA.getAttribute(1), ruleClassA.getAttributeByName("tags"));
+ assertThat((int) ruleClassA.getAttributeIndex("tags")).isEqualTo(1);
+ assertThat(ruleClassA.getAttributeByName("tags")).isEqualTo(ruleClassA.getAttribute(1));
- assertEquals(2, (int) ruleClassA.getAttributeIndex("X"));
- assertEquals(ruleClassA.getAttribute(2), ruleClassA.getAttributeByName("X"));
+ assertThat((int) ruleClassA.getAttributeIndex("X")).isEqualTo(2);
+ assertThat(ruleClassA.getAttributeByName("X")).isEqualTo(ruleClassA.getAttribute(2));
}
@Test
@@ -81,7 +77,7 @@ public class RuleClassBuilderTest extends PackageLoadingTestCase {
.add(attr("shard_count", INTEGER).value(-1))
.add(attr("local", BOOLEAN))
.build();
- assertTrue(ruleClassA.hasBinaryOutput());
+ assertThat(ruleClassA.hasBinaryOutput()).isTrue();
}
@Test
@@ -92,7 +88,7 @@ public class RuleClassBuilderTest extends PackageLoadingTestCase {
.setOutputToGenfiles()
.add(attr("tags", STRING_LIST))
.build();
- assertFalse(ruleClassA.hasBinaryOutput());
+ assertThat(ruleClassA.hasBinaryOutput()).isFalse();
}
@Test
@@ -181,9 +177,9 @@ public class RuleClassBuilderTest extends PackageLoadingTestCase {
new RuleClass.Builder("c", RuleClassType.NORMAL, false, a)
.factory(DUMMY_CONFIGURED_TARGET_FACTORY);
RuleClass c = builder.removeAttribute("a").add(attr("a", INTEGER)).removeAttribute("b").build();
- assertFalse(c.hasAttr("a", STRING));
- assertTrue(c.hasAttr("a", INTEGER));
- assertFalse(c.hasAttr("b", STRING));
+ assertThat(c.hasAttr("a", STRING)).isFalse();
+ assertThat(c.hasAttr("a", INTEGER)).isTrue();
+ assertThat(c.hasAttr("b", STRING)).isFalse();
try {
builder.removeAttribute("c");
diff --git a/src/test/java/com/google/devtools/build/lib/packages/RuleClassTest.java b/src/test/java/com/google/devtools/build/lib/packages/RuleClassTest.java
index 63ccc2422b..6b18d72a9c 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/RuleClassTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/RuleClassTest.java
@@ -26,9 +26,6 @@ import static com.google.devtools.build.lib.syntax.Type.INTEGER;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import static com.google.devtools.build.lib.syntax.Type.STRING_LIST;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
@@ -162,46 +159,42 @@ public class RuleClassTest extends PackageLoadingTestCase {
public void testRuleClassBasics() throws Exception {
RuleClass ruleClassA = createRuleClassA();
- assertEquals("ruleA", ruleClassA.getName());
- assertEquals(7, ruleClassA.getAttributeCount());
-
- assertEquals(0, (int) ruleClassA.getAttributeIndex("my-string-attr"));
- assertEquals(1, (int) ruleClassA.getAttributeIndex("my-label-attr"));
- assertEquals(2, (int) ruleClassA.getAttributeIndex("my-labellist-attr"));
- assertEquals(3, (int) ruleClassA.getAttributeIndex("my-integer-attr"));
- assertEquals(4, (int) ruleClassA.getAttributeIndex("my-string-attr2"));
- assertEquals(5, (int) ruleClassA.getAttributeIndex("my-stringlist-attr"));
- assertEquals(6, (int) ruleClassA.getAttributeIndex("my-sorted-stringlist-attr"));
-
- assertEquals(ruleClassA.getAttribute(0),
- ruleClassA.getAttributeByName("my-string-attr"));
- assertEquals(ruleClassA.getAttribute(1),
- ruleClassA.getAttributeByName("my-label-attr"));
- assertEquals(ruleClassA.getAttribute(2),
- ruleClassA.getAttributeByName("my-labellist-attr"));
- assertEquals(ruleClassA.getAttribute(3),
- ruleClassA.getAttributeByName("my-integer-attr"));
- assertEquals(ruleClassA.getAttribute(4),
- ruleClassA.getAttributeByName("my-string-attr2"));
- assertEquals(ruleClassA.getAttribute(5),
- ruleClassA.getAttributeByName("my-stringlist-attr"));
- assertEquals(ruleClassA.getAttribute(6),
- ruleClassA.getAttributeByName("my-sorted-stringlist-attr"));
+ assertThat(ruleClassA.getName()).isEqualTo("ruleA");
+ assertThat(ruleClassA.getAttributeCount()).isEqualTo(7);
+
+ assertThat((int) ruleClassA.getAttributeIndex("my-string-attr")).isEqualTo(0);
+ assertThat((int) ruleClassA.getAttributeIndex("my-label-attr")).isEqualTo(1);
+ assertThat((int) ruleClassA.getAttributeIndex("my-labellist-attr")).isEqualTo(2);
+ assertThat((int) ruleClassA.getAttributeIndex("my-integer-attr")).isEqualTo(3);
+ assertThat((int) ruleClassA.getAttributeIndex("my-string-attr2")).isEqualTo(4);
+ assertThat((int) ruleClassA.getAttributeIndex("my-stringlist-attr")).isEqualTo(5);
+ assertThat((int) ruleClassA.getAttributeIndex("my-sorted-stringlist-attr")).isEqualTo(6);
+
+ assertThat(ruleClassA.getAttributeByName("my-string-attr"))
+ .isEqualTo(ruleClassA.getAttribute(0));
+ assertThat(ruleClassA.getAttributeByName("my-label-attr"))
+ .isEqualTo(ruleClassA.getAttribute(1));
+ assertThat(ruleClassA.getAttributeByName("my-labellist-attr"))
+ .isEqualTo(ruleClassA.getAttribute(2));
+ assertThat(ruleClassA.getAttributeByName("my-integer-attr"))
+ .isEqualTo(ruleClassA.getAttribute(3));
+ assertThat(ruleClassA.getAttributeByName("my-string-attr2"))
+ .isEqualTo(ruleClassA.getAttribute(4));
+ assertThat(ruleClassA.getAttributeByName("my-stringlist-attr"))
+ .isEqualTo(ruleClassA.getAttribute(5));
+ assertThat(ruleClassA.getAttributeByName("my-sorted-stringlist-attr"))
+ .isEqualTo(ruleClassA.getAttribute(6));
assertEquals("", // default based on type
ruleClassA.getAttribute(0).getDefaultValue(null));
- assertEquals(Label.parseAbsolute("//default:label"),
- ruleClassA.getAttribute(1).getDefaultValue(null));
- assertEquals(Collections.emptyList(),
- ruleClassA.getAttribute(2).getDefaultValue(null));
- assertEquals(42,
- ruleClassA.getAttribute(3).getDefaultValue(null));
+ assertThat(ruleClassA.getAttribute(1).getDefaultValue(null))
+ .isEqualTo(Label.parseAbsolute("//default:label"));
+ assertThat(ruleClassA.getAttribute(2).getDefaultValue(null)).isEqualTo(Collections.emptyList());
+ assertThat(ruleClassA.getAttribute(3).getDefaultValue(null)).isEqualTo(42);
assertEquals(null, // default explicitly specified
ruleClassA.getAttribute(4).getDefaultValue(null));
- assertEquals(Collections.emptyList(),
- ruleClassA.getAttribute(5).getDefaultValue(null));
- assertEquals(Collections.emptyList(),
- ruleClassA.getAttribute(6).getDefaultValue(null));
+ assertThat(ruleClassA.getAttribute(5).getDefaultValue(null)).isEqualTo(Collections.emptyList());
+ assertThat(ruleClassA.getAttribute(6).getDefaultValue(null)).isEqualTo(Collections.emptyList());
}
@Test
@@ -209,34 +202,34 @@ public class RuleClassTest extends PackageLoadingTestCase {
RuleClass ruleClassA = createRuleClassA();
RuleClass ruleClassB = createRuleClassB(ruleClassA);
- assertEquals("ruleB", ruleClassB.getName());
- assertEquals(8, ruleClassB.getAttributeCount());
-
- assertEquals(0, (int) ruleClassB.getAttributeIndex("my-string-attr"));
- assertEquals(1, (int) ruleClassB.getAttributeIndex("my-label-attr"));
- assertEquals(2, (int) ruleClassB.getAttributeIndex("my-labellist-attr"));
- assertEquals(3, (int) ruleClassB.getAttributeIndex("my-integer-attr"));
- assertEquals(4, (int) ruleClassB.getAttributeIndex("my-string-attr2"));
- assertEquals(5, (int) ruleClassB.getAttributeIndex("my-stringlist-attr"));
- assertEquals(6, (int) ruleClassB.getAttributeIndex("my-sorted-stringlist-attr"));
- assertEquals(7, (int) ruleClassB.getAttributeIndex("another-string-attr"));
-
- assertEquals(ruleClassB.getAttribute(0),
- ruleClassB.getAttributeByName("my-string-attr"));
- assertEquals(ruleClassB.getAttribute(1),
- ruleClassB.getAttributeByName("my-label-attr"));
- assertEquals(ruleClassB.getAttribute(2),
- ruleClassB.getAttributeByName("my-labellist-attr"));
- assertEquals(ruleClassB.getAttribute(3),
- ruleClassB.getAttributeByName("my-integer-attr"));
- assertEquals(ruleClassB.getAttribute(4),
- ruleClassB.getAttributeByName("my-string-attr2"));
- assertEquals(ruleClassB.getAttribute(5),
- ruleClassB.getAttributeByName("my-stringlist-attr"));
- assertEquals(ruleClassB.getAttribute(6),
- ruleClassB.getAttributeByName("my-sorted-stringlist-attr"));
- assertEquals(ruleClassB.getAttribute(7),
- ruleClassB.getAttributeByName("another-string-attr"));
+ assertThat(ruleClassB.getName()).isEqualTo("ruleB");
+ assertThat(ruleClassB.getAttributeCount()).isEqualTo(8);
+
+ assertThat((int) ruleClassB.getAttributeIndex("my-string-attr")).isEqualTo(0);
+ assertThat((int) ruleClassB.getAttributeIndex("my-label-attr")).isEqualTo(1);
+ assertThat((int) ruleClassB.getAttributeIndex("my-labellist-attr")).isEqualTo(2);
+ assertThat((int) ruleClassB.getAttributeIndex("my-integer-attr")).isEqualTo(3);
+ assertThat((int) ruleClassB.getAttributeIndex("my-string-attr2")).isEqualTo(4);
+ assertThat((int) ruleClassB.getAttributeIndex("my-stringlist-attr")).isEqualTo(5);
+ assertThat((int) ruleClassB.getAttributeIndex("my-sorted-stringlist-attr")).isEqualTo(6);
+ assertThat((int) ruleClassB.getAttributeIndex("another-string-attr")).isEqualTo(7);
+
+ assertThat(ruleClassB.getAttributeByName("my-string-attr"))
+ .isEqualTo(ruleClassB.getAttribute(0));
+ assertThat(ruleClassB.getAttributeByName("my-label-attr"))
+ .isEqualTo(ruleClassB.getAttribute(1));
+ assertThat(ruleClassB.getAttributeByName("my-labellist-attr"))
+ .isEqualTo(ruleClassB.getAttribute(2));
+ assertThat(ruleClassB.getAttributeByName("my-integer-attr"))
+ .isEqualTo(ruleClassB.getAttribute(3));
+ assertThat(ruleClassB.getAttributeByName("my-string-attr2"))
+ .isEqualTo(ruleClassB.getAttribute(4));
+ assertThat(ruleClassB.getAttributeByName("my-stringlist-attr"))
+ .isEqualTo(ruleClassB.getAttribute(5));
+ assertThat(ruleClassB.getAttributeByName("my-sorted-stringlist-attr"))
+ .isEqualTo(ruleClassB.getAttribute(6));
+ assertThat(ruleClassB.getAttributeByName("another-string-attr"))
+ .isEqualTo(ruleClassB.getAttribute(7));
}
private static final String TEST_PACKAGE_NAME = "testpackage";
@@ -301,7 +294,7 @@ public class RuleClassTest extends PackageLoadingTestCase {
reporter.removeHandler(failFastHandler);
createRule(depsRuleClass, "depsRule", attributeValues, testRuleLocation);
- assertSame(3, eventCollector.count());
+ assertThat(eventCollector.count()).isSameAs(3);
assertDupError("//testpackage:dup1", "list1", "depsRule");
assertDupError("//testpackage:dup1", "list3", "depsRule");
assertDupError("//testpackage:dup2", "list3", "depsRule");
@@ -380,29 +373,28 @@ public class RuleClassTest extends PackageLoadingTestCase {
).iterator();
for (Event event : collector) {
- assertEquals(TEST_RULE_DEFINED_AT_LINE,
- event.getLocation().getStartLineAndColumn().getLine());
- assertEquals(testBuildfilePath.asFragment(), event.getLocation().getPath());
- assertEquals(TEST_RULE_LABEL.toString().substring(1)
- + ": " + expectedMessages.next(), event.getMessage());
+ assertThat(event.getLocation().getStartLineAndColumn().getLine())
+ .isEqualTo(TEST_RULE_DEFINED_AT_LINE);
+ assertThat(event.getLocation().getPath()).isEqualTo(testBuildfilePath.asFragment());
+ assertThat(event.getMessage())
+ .isEqualTo(TEST_RULE_LABEL.toString().substring(1) + ": " + expectedMessages.next());
}
// Test basic rule properties:
- assertEquals("ruleA", rule.getRuleClass());
- assertEquals(TEST_RULE_NAME, rule.getName());
- assertEquals(TEST_RULE_LABEL.substring(1), rule.getLabel().toString());
+ assertThat(rule.getRuleClass()).isEqualTo("ruleA");
+ assertThat(rule.getName()).isEqualTo(TEST_RULE_NAME);
+ assertThat(rule.getLabel().toString()).isEqualTo(TEST_RULE_LABEL.substring(1));
// Test attribute access:
AttributeMap attributes = RawAttributeMapper.of(rule);
- assertEquals("//default:label",
- attributes.get("my-label-attr", BuildType.LABEL).toString());
- assertEquals(42,
- attributes.get("my-integer-attr", Type.INTEGER).intValue());
+ assertThat(attributes.get("my-label-attr", BuildType.LABEL).toString())
+ .isEqualTo("//default:label");
+ assertThat(attributes.get("my-integer-attr", Type.INTEGER).intValue()).isEqualTo(42);
assertEquals("", // missing attribute -> default chosen based on type
attributes.get("my-string-attr", Type.STRING));
assertThat(attributes.get("my-labellist-attr", BuildType.LABEL_LIST)).isEmpty();
- assertEquals(Arrays.asList("foo", "bar"),
- attributes.get("my-stringlist-attr", Type.STRING_LIST));
+ assertThat(attributes.get("my-stringlist-attr", Type.STRING_LIST))
+ .isEqualTo(Arrays.asList("foo", "bar"));
try {
attributes.get("my-labellist-attr", Type.STRING); // wrong type
fail();
@@ -449,7 +441,7 @@ public class RuleClassTest extends PackageLoadingTestCase {
Set<String> set = new HashSet<>();
for (OutputFile outputFile : rule.getOutputFiles()) {
set.add(outputFile.getName());
- assertSame(rule, outputFile.getGeneratingRule());
+ assertThat(outputFile.getGeneratingRule()).isSameAs(rule);
}
assertThat(set).containsExactly("foo-myrule.bar", "libmyrule-wazoo-myrule.mumble",
"stuff-explicit_out-bar", "explicit_out");
@@ -482,12 +474,13 @@ public class RuleClassTest extends PackageLoadingTestCase {
Rule rule = createRule(ruleClass, "myRule", Collections.<String, Object>emptyMap(),
testRuleLocation);
- assertEquals("libmyRule.bar", Iterables.getOnlyElement(rule.getOutputFiles()).getName());
+ assertThat(Iterables.getOnlyElement(rule.getOutputFiles()).getName())
+ .isEqualTo("libmyRule.bar");
Rule ruleWithSlash = createRule(ruleClass, "myRule/with/slash",
Collections.<String, Object>emptyMap(), testRuleLocation);
- assertEquals("myRule/with/libslash.bar",
- Iterables.getOnlyElement(ruleWithSlash.getOutputFiles()).getName());
+ assertThat(Iterables.getOnlyElement(ruleWithSlash.getOutputFiles()).getName())
+ .isEqualTo("myRule/with/libslash.bar");
}
/**
@@ -528,13 +521,13 @@ public class RuleClassTest extends PackageLoadingTestCase {
*/
private void checkValidComputedDefault(Object expectedValue, Attribute computedDefault,
ImmutableMap<String, Object> attrValueMap) throws Exception {
- assertTrue(computedDefault.getDefaultValueForTesting() instanceof Attribute.ComputedDefault);
+ assertThat(computedDefault.getDefaultValueForTesting() instanceof Attribute.ComputedDefault)
+ .isTrue();
Rule rule = createRule(getRuleClassWithComputedDefault(computedDefault), "myRule",
attrValueMap, testRuleLocation);
AttributeMap attributes = RawAttributeMapper.of(rule);
- assertEquals(
- expectedValue,
- attributes.get(computedDefault.getName(), computedDefault.getType()));
+ assertThat(attributes.get(computedDefault.getName(), computedDefault.getType()))
+ .isEqualTo(expectedValue);
}
/**
@@ -691,7 +684,7 @@ public class RuleClassTest extends PackageLoadingTestCase {
List<String> actual = new ArrayList<>();
for (OutputFile outputFile : rule.getOutputFiles()) {
actual.add(outputFile.getName());
- assertSame(rule, outputFile.getGeneratingRule());
+ assertThat(outputFile.getGeneratingRule()).isSameAs(rule);
}
assertWithMessage("unexpected output set").that(actual).containsExactly("first-myrule",
"second-myrule", "out-third", "out-fourth", "third", "fourth");
@@ -768,10 +761,9 @@ public class RuleClassTest extends PackageLoadingTestCase {
Rule rule = createRule(ruleClassA, "testrule", attributeValues, testRuleLocation);
AttributeMap attributes = RawAttributeMapper.of(rule);
- assertEquals(list,
- attributes.get("my-stringlist-attr", Type.STRING_LIST));
- assertEquals(Arrays.asList("bar", "baz", "foo"),
- attributes.get("my-sorted-stringlist-attr", Type.STRING_LIST));
+ assertThat(attributes.get("my-stringlist-attr", Type.STRING_LIST)).isEqualTo(list);
+ assertThat(attributes.get("my-sorted-stringlist-attr", Type.STRING_LIST))
+ .isEqualTo(Arrays.asList("bar", "baz", "foo"));
}
private Rule createRule(
@@ -839,7 +831,7 @@ public class RuleClassTest extends PackageLoadingTestCase {
reporter.removeHandler(failFastHandler);
createRule(childRuleClass, "child_rule", childValues, testRuleLocation);
- assertSame(1, eventCollector.count());
+ assertThat(eventCollector.count()).isSameAs(1);
assertContainsEvent("//testpackage:child_rule: missing value for mandatory "
+ "attribute 'attr' in 'child_rule' rule");
}
@@ -959,20 +951,21 @@ public class RuleClassTest extends PackageLoadingTestCase {
final Rule dep2 = createRule(depClass, "dep2", Collections.<String, Object>emptyMap(),
testRuleLocation);
- ValidityPredicate checker = new ValidityPredicate() {
- @Override
- public String checkValid(Rule from, Rule to) {
- assertEquals("top", from.getName());
- if (to.getName().equals("dep1")) {
- return "pear";
- } else if (to.getName().equals("dep2")) {
- return null;
- } else {
- fail("invalid dependency");
- return null;
- }
- }
- };
+ ValidityPredicate checker =
+ new ValidityPredicate() {
+ @Override
+ public String checkValid(Rule from, Rule to) {
+ assertThat(from.getName()).isEqualTo("top");
+ if (to.getName().equals("dep1")) {
+ return "pear";
+ } else if (to.getName().equals("dep2")) {
+ return null;
+ } else {
+ fail("invalid dependency");
+ return null;
+ }
+ }
+ };
RuleClass topClass = new RuleClass.Builder("top", RuleClassType.NORMAL, false)
.factory(DUMMY_CONFIGURED_TARGET_FACTORY)
@@ -984,10 +977,10 @@ public class RuleClassTest extends PackageLoadingTestCase {
Rule topRule = createRule(topClass, "top", Collections.<String, Object>emptyMap(),
testRuleLocation);
- assertEquals("pear", topClass.getAttributeByName("deps").getValidityPredicate().checkValid(
- topRule, dep1));
- assertEquals(null, topClass.getAttributeByName("deps").getValidityPredicate().checkValid(
- topRule, dep2));
+ assertThat(topClass.getAttributeByName("deps").getValidityPredicate().checkValid(topRule, dep1))
+ .isEqualTo("pear");
+ assertThat(topClass.getAttributeByName("deps").getValidityPredicate().checkValid(topRule, dep2))
+ .isNull();
}
/**
@@ -1006,8 +999,8 @@ public class RuleClassTest extends PackageLoadingTestCase {
.build();
final Rule defaultRule = createRule(defaultClass, "defaultRule",
Collections.<String, Object>emptyMap(), testRuleLocation);
- assertFalse(defaultRule.getRuleClassObject().isPreferredDependency(cppFile));
- assertFalse(defaultRule.getRuleClassObject().isPreferredDependency(textFile));
+ assertThat(defaultRule.getRuleClassObject().isPreferredDependency(cppFile)).isFalse();
+ assertThat(defaultRule.getRuleClassObject().isPreferredDependency(textFile)).isFalse();
// Make a rule that's preferred for C++ sources.
RuleClass cppClass = new RuleClass.Builder("cppClass", RuleClassType.NORMAL, false)
@@ -1022,8 +1015,8 @@ public class RuleClassTest extends PackageLoadingTestCase {
.build();
final Rule cppRule = createRule(cppClass, "cppRule",
Collections.<String, Object>emptyMap(), testRuleLocation);
- assertTrue(cppRule.getRuleClassObject().isPreferredDependency(cppFile));
- assertFalse(cppRule.getRuleClassObject().isPreferredDependency(textFile));
+ assertThat(cppRule.getRuleClassObject().isPreferredDependency(cppFile)).isTrue();
+ assertThat(cppRule.getRuleClassObject().isPreferredDependency(textFile)).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/packages/RuleFactoryTest.java b/src/test/java/com/google/devtools/build/lib/packages/RuleFactoryTest.java
index a2d34f36c5..a2dc4d3412 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/RuleFactoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/RuleFactoryTest.java
@@ -14,10 +14,7 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.collect.Lists;
@@ -72,26 +69,26 @@ public class RuleFactoryTest extends PackageLoadingTestCase {
/*env=*/ null,
new AttributeContainer(ruleClass));
- assertSame(rule, rule.getAssociatedRule());
+ assertThat(rule.getAssociatedRule()).isSameAs(rule);
// pkg.getRules() = [rule]
Package pkg = pkgBuilder.build();
assertThat(Sets.newHashSet(pkg.getTargets(Rule.class))).hasSize(1);
- assertEquals(rule, pkg.getTargets(Rule.class).iterator().next());
+ assertThat(pkg.getTargets(Rule.class).iterator().next()).isEqualTo(rule);
- assertSame(rule, pkg.getTarget("foo"));
+ assertThat(pkg.getTarget("foo")).isSameAs(rule);
- assertEquals(Label.parseAbsolute("//mypkg:foo"), rule.getLabel());
- assertEquals("foo", rule.getName());
+ assertThat(rule.getLabel()).isEqualTo(Label.parseAbsolute("//mypkg:foo"));
+ assertThat(rule.getName()).isEqualTo("foo");
- assertEquals("cc_library", rule.getRuleClass());
- assertEquals("cc_library rule", rule.getTargetKind());
- assertEquals(42, rule.getLocation().getStartOffset());
- assertFalse(rule.containsErrors());
+ assertThat(rule.getRuleClass()).isEqualTo("cc_library");
+ assertThat(rule.getTargetKind()).isEqualTo("cc_library rule");
+ assertThat(rule.getLocation().getStartOffset()).isEqualTo(42);
+ assertThat(rule.containsErrors()).isFalse();
// Attr with explicitly-supplied value:
AttributeMap attributes = RawAttributeMapper.of(rule);
- assertTrue(attributes.get("alwayslink", Type.BOOLEAN));
+ assertThat(attributes.get("alwayslink", Type.BOOLEAN)).isTrue();
try {
attributes.get("alwayslink", Type.STRING); // type error: boolean, not string!
fail();
@@ -107,8 +104,8 @@ public class RuleFactoryTest extends PackageLoadingTestCase {
// Attrs with default values:
// cc_library linkstatic default=0 according to build encyc.
- assertFalse(attributes.get("linkstatic", Type.BOOLEAN));
- assertFalse(attributes.get("testonly", Type.BOOLEAN));
+ assertThat(attributes.get("linkstatic", Type.BOOLEAN)).isFalse();
+ assertThat(attributes.get("testonly", Type.BOOLEAN)).isFalse();
assertThat(attributes.get("srcs", BuildType.LABEL_LIST)).isEmpty();
}
@@ -132,7 +129,7 @@ public class RuleFactoryTest extends PackageLoadingTestCase {
Location.fromFileAndOffsets(myPkgPath.asFragment(), 42, 42),
/*env=*/ null,
new AttributeContainer(ruleClass));
- assertFalse(rule.containsErrors());
+ assertThat(rule.containsErrors()).isFalse();
}
@Test
@@ -160,7 +157,7 @@ public class RuleFactoryTest extends PackageLoadingTestCase {
new AttributeContainer(ruleClass));
fail();
} catch (RuleFactory.InvalidRuleException e) {
- assertThat(e.getMessage()).contains("must be in the WORKSPACE file");
+ assertThat(e).hasMessageThat().contains("must be in the WORKSPACE file");
}
}
@@ -189,20 +186,21 @@ public class RuleFactoryTest extends PackageLoadingTestCase {
new AttributeContainer(ruleClass));
fail();
} catch (RuleFactory.InvalidRuleException e) {
- assertThat(e.getMessage()).contains("cannot be in the WORKSPACE file");
+ assertThat(e).hasMessageThat().contains("cannot be in the WORKSPACE file");
}
}
private void assertAttr(RuleClass ruleClass, String attrName, Type<?> type) throws Exception {
- assertTrue(
- "Rule class '"
- + ruleClass.getName()
- + "' should have attribute '"
- + attrName
- + "' of type '"
- + type
- + "'",
- ruleClass.hasAttr(attrName, type));
+ assertWithMessage(
+ "Rule class '"
+ + ruleClass.getName()
+ + "' should have attribute '"
+ + attrName
+ + "' of type '"
+ + type
+ + "'")
+ .that(ruleClass.hasAttr(attrName, type))
+ .isTrue();
}
@Test
@@ -229,7 +227,9 @@ public class RuleFactoryTest extends PackageLoadingTestCase {
new AttributeContainer(ruleClass));
fail();
} catch (RuleFactory.InvalidRuleException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("output file name can't be equal '.'"));
+ assertWithMessage(e.getMessage())
+ .that(e.getMessage().contains("output file name can't be equal '.'"))
+ .isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/RuleTest.java b/src/test/java/com/google/devtools/build/lib/packages/RuleTest.java
index 2876a62cf6..28715230d9 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/RuleTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/RuleTest.java
@@ -14,17 +14,13 @@
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.events.Location.LineAndColumn;
import com.google.devtools.build.lib.events.util.EventCollectionApparatus;
import com.google.devtools.build.lib.packages.util.PackageFactoryApparatus;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.vfs.Path;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -47,26 +43,26 @@ public class RuleTest {
Package pkg = packages.createPackage("x", buildFile);
Rule rule = pkg.getRule("x");
- assertEquals(new LineAndColumn(1, 1), rule.getLocation().getStartLineAndColumn());
+ assertThat(rule.getLocation().getStartLineAndColumn()).isEqualTo(new LineAndColumn(1, 1));
// Special "name" attribute always has same location as rule:
- assertEquals(new LineAndColumn(1, 1),
- rule.getAttributeLocation("name").getStartLineAndColumn());
+ assertThat(rule.getAttributeLocation("name").getStartLineAndColumn())
+ .isEqualTo(new LineAndColumn(1, 1));
// User-provided attributes have precise locations:
- assertEquals(new LineAndColumn(2, 18),
- rule.getAttributeLocation("srcs").getStartLineAndColumn());
- assertEquals(new LineAndColumn(3, 21),
- rule.getAttributeLocation("defines").getStartLineAndColumn());
+ assertThat(rule.getAttributeLocation("srcs").getStartLineAndColumn())
+ .isEqualTo(new LineAndColumn(2, 18));
+ assertThat(rule.getAttributeLocation("defines").getStartLineAndColumn())
+ .isEqualTo(new LineAndColumn(3, 21));
// Default attributes have same location as rule:
- assertEquals(new LineAndColumn(1, 1),
- rule.getAttributeLocation("malloc").getStartLineAndColumn());
+ assertThat(rule.getAttributeLocation("malloc").getStartLineAndColumn())
+ .isEqualTo(new LineAndColumn(1, 1));
// Attempts to locate non-existent attributes don't fail;
// the rule location is returned:
- assertEquals(new LineAndColumn(1, 1),
- rule.getAttributeLocation("no-such-attr").getStartLineAndColumn());
+ assertThat(rule.getAttributeLocation("no-such-attr").getStartLineAndColumn())
+ .isEqualTo(new LineAndColumn(1, 1));
}
@Test
@@ -80,7 +76,7 @@ public class RuleTest {
Package pkg = packages.createPackage("namecollide", buildFile);
Rule genRule = pkg.getRule("hello_world");
- assertFalse(genRule.containsErrors()); // TODO: assertTrue
+ assertThat(genRule.containsErrors()).isFalse(); // TODO: assertTrue
events.assertContainsWarning("target 'hello_world' is both a rule and a file; please choose "
+ "another name for the rule");
}
@@ -96,9 +92,9 @@ public class RuleTest {
" local = 1)");
Package pkg = packages.createPackage("x", buildFile);
Rule y = pkg.getRule("y");
- assertFalse(TargetUtils.isLocalTestRule(y));
+ assertThat(TargetUtils.isLocalTestRule(y)).isFalse();
Rule z = pkg.getRule("z");
- assertTrue(TargetUtils.isLocalTestRule(z));
+ assertThat(TargetUtils.isLocalTestRule(z)).isTrue();
}
@Test
@@ -108,9 +104,9 @@ public class RuleTest {
"cc_test(name = 'z', deprecation = 'Foo')");
Package pkg = packages.createPackage("x", buildFile);
Rule y = pkg.getRule("y");
- assertNull(TargetUtils.getDeprecation(y));
+ assertThat(TargetUtils.getDeprecation(y)).isNull();
Rule z = pkg.getRule("z");
- assertEquals("Foo", TargetUtils.getDeprecation(z));
+ assertThat(TargetUtils.getDeprecation(z)).isEqualTo("Foo");
}
@Test
@@ -123,9 +119,7 @@ public class RuleTest {
"cc_binary(name = 'cu',",
" visibility = ['//a:b'])"));
- assertEquals(ConstantRuleVisibility.PUBLIC,
- pkg.getRule("pu").getVisibility());
- assertEquals(ConstantRuleVisibility.PRIVATE,
- pkg.getRule("pr").getVisibility());
+ assertThat(pkg.getRule("pu").getVisibility()).isEqualTo(ConstantRuleVisibility.PUBLIC);
+ assertThat(pkg.getRule("pr").getVisibility()).isEqualTo(ConstantRuleVisibility.PRIVATE);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/TargetUtilsTest.java b/src/test/java/com/google/devtools/build/lib/packages/TargetUtilsTest.java
index c1fb849fd4..6d49de9024 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/TargetUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/TargetUtilsTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
@@ -33,8 +30,8 @@ public class TargetUtilsTest extends PackageLoadingTestCase {
@Test
public void getRuleLanguage() {
- assertEquals("java", TargetUtils.getRuleLanguage("java_binary"));
- assertEquals("foobar", TargetUtils.getRuleLanguage("foobar"));
+ assertThat(TargetUtils.getRuleLanguage("java_binary")).isEqualTo("java");
+ assertThat(TargetUtils.getRuleLanguage("foobar")).isEqualTo("foobar");
assertThat(TargetUtils.getRuleLanguage("")).isEmpty();
}
@@ -51,31 +48,31 @@ public class TargetUtilsTest extends PackageLoadingTestCase {
Target tag1b = getTarget("//tests:tag1b");
Predicate<Target> tagFilter = TargetUtils.tagFilter(Lists.<String>newArrayList());
- assertTrue(tagFilter.apply(tag1));
- assertTrue(tagFilter.apply(tag2));
- assertTrue(tagFilter.apply(tag1b));
+ assertThat(tagFilter.apply(tag1)).isTrue();
+ assertThat(tagFilter.apply(tag2)).isTrue();
+ assertThat(tagFilter.apply(tag1b)).isTrue();
tagFilter = TargetUtils.tagFilter(Lists.newArrayList("tag1", "tag2"));
- assertTrue(tagFilter.apply(tag1));
- assertTrue(tagFilter.apply(tag2));
- assertTrue(tagFilter.apply(tag1b));
+ assertThat(tagFilter.apply(tag1)).isTrue();
+ assertThat(tagFilter.apply(tag2)).isTrue();
+ assertThat(tagFilter.apply(tag1b)).isTrue();
tagFilter = TargetUtils.tagFilter(Lists.newArrayList("tag1"));
- assertTrue(tagFilter.apply(tag1));
- assertFalse(tagFilter.apply(tag2));
- assertTrue(tagFilter.apply(tag1b));
+ assertThat(tagFilter.apply(tag1)).isTrue();
+ assertThat(tagFilter.apply(tag2)).isFalse();
+ assertThat(tagFilter.apply(tag1b)).isTrue();
tagFilter = TargetUtils.tagFilter(Lists.newArrayList("-tag2"));
- assertTrue(tagFilter.apply(tag1));
- assertFalse(tagFilter.apply(tag2));
- assertTrue(tagFilter.apply(tag1b));
+ assertThat(tagFilter.apply(tag1)).isTrue();
+ assertThat(tagFilter.apply(tag2)).isFalse();
+ assertThat(tagFilter.apply(tag1b)).isTrue();
// Applying same tag as positive and negative filter produces an empty
// result because the negative filter is applied first and positive filter will
// not match anything.
tagFilter = TargetUtils.tagFilter(Lists.newArrayList("tag2", "-tag2"));
- assertFalse(tagFilter.apply(tag1));
- assertFalse(tagFilter.apply(tag2));
- assertFalse(tagFilter.apply(tag1b));
+ assertThat(tagFilter.apply(tag1)).isFalse();
+ assertThat(tagFilter.apply(tag2)).isFalse();
+ assertThat(tagFilter.apply(tag1b)).isFalse();
tagFilter = TargetUtils.tagFilter(Lists.newArrayList("tag2", "-tag1"));
- assertFalse(tagFilter.apply(tag1));
- assertTrue(tagFilter.apply(tag2));
- assertFalse(tagFilter.apply(tag1b));
+ assertThat(tagFilter.apply(tag1)).isFalse();
+ assertThat(tagFilter.apply(tag2)).isTrue();
+ assertThat(tagFilter.apply(tag1b)).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/TestSizeTest.java b/src/test/java/com/google/devtools/build/lib/packages/TestSizeTest.java
index b9ff3c8e8f..a3d1f15600 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/TestSizeTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/TestSizeTest.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -28,43 +27,43 @@ public class TestSizeTest {
@Test
public void testBasicConversion() {
- assertEquals(TestSize.SMALL, TestSize.valueOf("SMALL"));
- assertEquals(TestSize.MEDIUM, TestSize.valueOf("MEDIUM"));
- assertEquals(TestSize.LARGE, TestSize.valueOf("LARGE"));
- assertEquals(TestSize.ENORMOUS, TestSize.valueOf("ENORMOUS"));
+ assertThat(TestSize.valueOf("SMALL")).isEqualTo(TestSize.SMALL);
+ assertThat(TestSize.valueOf("MEDIUM")).isEqualTo(TestSize.MEDIUM);
+ assertThat(TestSize.valueOf("LARGE")).isEqualTo(TestSize.LARGE);
+ assertThat(TestSize.valueOf("ENORMOUS")).isEqualTo(TestSize.ENORMOUS);
}
@Test
public void testGetDefaultTimeout() {
- assertEquals(TestTimeout.SHORT, TestSize.SMALL.getDefaultTimeout());
- assertEquals(TestTimeout.MODERATE, TestSize.MEDIUM.getDefaultTimeout());
- assertEquals(TestTimeout.LONG, TestSize.LARGE.getDefaultTimeout());
- assertEquals(TestTimeout.ETERNAL, TestSize.ENORMOUS.getDefaultTimeout());
+ assertThat(TestSize.SMALL.getDefaultTimeout()).isEqualTo(TestTimeout.SHORT);
+ assertThat(TestSize.MEDIUM.getDefaultTimeout()).isEqualTo(TestTimeout.MODERATE);
+ assertThat(TestSize.LARGE.getDefaultTimeout()).isEqualTo(TestTimeout.LONG);
+ assertThat(TestSize.ENORMOUS.getDefaultTimeout()).isEqualTo(TestTimeout.ETERNAL);
}
@Test
public void testGetDefaultShards() {
- assertEquals(2, TestSize.SMALL.getDefaultShards());
- assertEquals(10, TestSize.MEDIUM.getDefaultShards());
- assertEquals(20, TestSize.LARGE.getDefaultShards());
- assertEquals(30, TestSize.ENORMOUS.getDefaultShards());
+ assertThat(TestSize.SMALL.getDefaultShards()).isEqualTo(2);
+ assertThat(TestSize.MEDIUM.getDefaultShards()).isEqualTo(10);
+ assertThat(TestSize.LARGE.getDefaultShards()).isEqualTo(20);
+ assertThat(TestSize.ENORMOUS.getDefaultShards()).isEqualTo(30);
}
@Test
public void testGetTestSizeFromString() {
- assertNull(TestSize.getTestSize("Small"));
- assertNull(TestSize.getTestSize("Koala"));
- assertEquals(TestSize.SMALL, TestSize.getTestSize("small"));
- assertEquals(TestSize.MEDIUM, TestSize.getTestSize("medium"));
- assertEquals(TestSize.LARGE, TestSize.getTestSize("large"));
- assertEquals(TestSize.ENORMOUS, TestSize.getTestSize("enormous"));
+ assertThat(TestSize.getTestSize("Small")).isNull();
+ assertThat(TestSize.getTestSize("Koala")).isNull();
+ assertThat(TestSize.getTestSize("small")).isEqualTo(TestSize.SMALL);
+ assertThat(TestSize.getTestSize("medium")).isEqualTo(TestSize.MEDIUM);
+ assertThat(TestSize.getTestSize("large")).isEqualTo(TestSize.LARGE);
+ assertThat(TestSize.getTestSize("enormous")).isEqualTo(TestSize.ENORMOUS);
}
@Test
public void testGetTestSizeFromDefaultTimeout() {
- assertEquals(TestSize.SMALL, TestSize.getTestSize(TestTimeout.SHORT));
- assertEquals(TestSize.MEDIUM, TestSize.getTestSize(TestTimeout.MODERATE));
- assertEquals(TestSize.LARGE, TestSize.getTestSize(TestTimeout.LONG));
- assertEquals(TestSize.ENORMOUS, TestSize.getTestSize(TestTimeout.ETERNAL));
+ assertThat(TestSize.getTestSize(TestTimeout.SHORT)).isEqualTo(TestSize.SMALL);
+ assertThat(TestSize.getTestSize(TestTimeout.MODERATE)).isEqualTo(TestSize.MEDIUM);
+ assertThat(TestSize.getTestSize(TestTimeout.LONG)).isEqualTo(TestSize.LARGE);
+ assertThat(TestSize.getTestSize(TestTimeout.ETERNAL)).isEqualTo(TestSize.ENORMOUS);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/TestTargetUtilsTest.java b/src/test/java/com/google/devtools/build/lib/packages/TestTargetUtilsTest.java
index 0258d527ad..2ff6446c3c 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/TestTargetUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/TestTargetUtilsTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
@@ -85,13 +82,13 @@ public class TestTargetUtilsTest extends PackageLoadingTestCase {
public void testFilterBySize() throws Exception {
Predicate<Target> sizeFilter =
TestTargetUtils.testSizeFilter(EnumSet.of(TestSize.SMALL, TestSize.LARGE));
- assertTrue(sizeFilter.apply(test1));
- assertTrue(sizeFilter.apply(test2));
- assertTrue(sizeFilter.apply(test1b));
+ assertThat(sizeFilter.apply(test1)).isTrue();
+ assertThat(sizeFilter.apply(test2)).isTrue();
+ assertThat(sizeFilter.apply(test1b)).isTrue();
sizeFilter = TestTargetUtils.testSizeFilter(EnumSet.of(TestSize.SMALL));
- assertTrue(sizeFilter.apply(test1));
- assertTrue(sizeFilter.apply(test2));
- assertFalse(sizeFilter.apply(test1b));
+ assertThat(sizeFilter.apply(test1)).isTrue();
+ assertThat(sizeFilter.apply(test2)).isTrue();
+ assertThat(sizeFilter.apply(test1b)).isFalse();
}
@Test
@@ -115,9 +112,9 @@ public class TestTargetUtilsTest extends PackageLoadingTestCase {
Predicate<Target> timeoutFilter =
TestTargetUtils.testTimeoutFilter(EnumSet.of(TestTimeout.SHORT, TestTimeout.LONG));
- assertTrue(timeoutFilter.apply(longTest));
- assertTrue(timeoutFilter.apply(shortTest));
- assertFalse(timeoutFilter.apply(moderateTest));
+ assertThat(timeoutFilter.apply(longTest)).isTrue();
+ assertThat(timeoutFilter.apply(shortTest)).isTrue();
+ assertThat(timeoutFilter.apply(moderateTest)).isFalse();
}
@Test
@@ -156,7 +153,7 @@ public class TestTargetUtilsTest extends PackageLoadingTestCase {
Sets.newHashSet(getTarget("//broken")), /*strict=*/
false, /*keep_going=*/
true);
- assertTrue(actual.hasError());
+ assertThat(actual.hasError()).isTrue();
assertThat(actual.getTargets()).isEmpty();
}
@@ -165,7 +162,7 @@ public class TestTargetUtilsTest extends PackageLoadingTestCase {
ResolvedTargets<Target> actual =
TestTargetUtils.expandTestSuites(
getPackageManager(), reporter, suites, /*strict=*/ false, /*keep_going=*/ true);
- assertFalse(actual.hasError());
+ assertThat(actual.hasError()).isFalse();
assertThat(actual.getTargets()).containsExactlyElementsIn(expected);
}
@@ -186,7 +183,7 @@ public class TestTargetUtilsTest extends PackageLoadingTestCase {
.getDriverForTesting()
.evaluate(ImmutableList.of(key), false, 1, reporter);
ResolvedTargets<Target> actual = result.get(key).getTargets();
- assertFalse(actual.hasError());
+ assertThat(actual.hasError()).isFalse();
assertThat(actual.getTargets()).containsExactlyElementsIn(expected);
}
@@ -208,8 +205,8 @@ public class TestTargetUtilsTest extends PackageLoadingTestCase {
false, /*keep_going=*/
true);
} catch (TargetParsingException e) {
- assertNotNull(e.getMessage());
+ assertThat(e).hasMessageThat().isNotNull();
}
- assertTrue(Thread.currentThread().isInterrupted());
+ assertThat(Thread.currentThread().isInterrupted()).isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/TestTimeoutTest.java b/src/test/java/com/google/devtools/build/lib/packages/TestTimeoutTest.java
index 8b6201c88e..ec87911f38 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/TestTimeoutTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/TestTimeoutTest.java
@@ -13,15 +13,12 @@
// limitations under the License.
package com.google.devtools.build.lib.packages;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.packages.TestTimeout.ETERNAL;
import static com.google.devtools.build.lib.packages.TestTimeout.LONG;
import static com.google.devtools.build.lib.packages.TestTimeout.MODERATE;
import static com.google.devtools.build.lib.packages.TestTimeout.SHORT;
import static com.google.devtools.build.lib.packages.TestTimeout.getSuggestedTestTimeout;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,39 +32,39 @@ public class TestTimeoutTest {
@Test
public void testBasicConversion() throws Exception {
- assertSame(SHORT, TestTimeout.valueOf("SHORT"));
- assertSame(MODERATE, TestTimeout.valueOf("MODERATE"));
- assertSame(LONG, TestTimeout.valueOf("LONG"));
- assertSame(ETERNAL, TestTimeout.valueOf("ETERNAL"));
+ assertThat(TestTimeout.valueOf("SHORT")).isSameAs(SHORT);
+ assertThat(TestTimeout.valueOf("MODERATE")).isSameAs(MODERATE);
+ assertThat(TestTimeout.valueOf("LONG")).isSameAs(LONG);
+ assertThat(TestTimeout.valueOf("ETERNAL")).isSameAs(ETERNAL);
}
@Test
public void testSuggestedTestSize() throws Exception {
- assertEquals(SHORT, getSuggestedTestTimeout(0));
- assertEquals(SHORT, getSuggestedTestTimeout(2));
- assertEquals(SHORT, getSuggestedTestTimeout(6));
- assertEquals(SHORT, getSuggestedTestTimeout(59));
- assertEquals(MODERATE, getSuggestedTestTimeout(60));
- assertEquals(MODERATE, getSuggestedTestTimeout(299));
- assertEquals(LONG, getSuggestedTestTimeout(300));
- assertEquals(LONG, getSuggestedTestTimeout(899));
- assertEquals(ETERNAL, getSuggestedTestTimeout(900));
- assertEquals(ETERNAL, getSuggestedTestTimeout(1234567890));
+ assertThat(getSuggestedTestTimeout(0)).isEqualTo(SHORT);
+ assertThat(getSuggestedTestTimeout(2)).isEqualTo(SHORT);
+ assertThat(getSuggestedTestTimeout(6)).isEqualTo(SHORT);
+ assertThat(getSuggestedTestTimeout(59)).isEqualTo(SHORT);
+ assertThat(getSuggestedTestTimeout(60)).isEqualTo(MODERATE);
+ assertThat(getSuggestedTestTimeout(299)).isEqualTo(MODERATE);
+ assertThat(getSuggestedTestTimeout(300)).isEqualTo(LONG);
+ assertThat(getSuggestedTestTimeout(899)).isEqualTo(LONG);
+ assertThat(getSuggestedTestTimeout(900)).isEqualTo(ETERNAL);
+ assertThat(getSuggestedTestTimeout(1234567890)).isEqualTo(ETERNAL);
}
@Test
public void testIsInRangeExact() throws Exception {
- assertTrue(SHORT.isInRangeExact(0));
- assertTrue(SHORT.isInRangeExact(1));
- assertFalse(SHORT.isInRangeExact(60));
- assertTrue(MODERATE.isInRangeExact(60));
- assertTrue(MODERATE.isInRangeExact(299));
- assertFalse(MODERATE.isInRangeExact(300));
- assertTrue(LONG.isInRangeExact(300));
- assertTrue(LONG.isInRangeExact(899));
- assertFalse(LONG.isInRangeExact(900));
- assertTrue(ETERNAL.isInRangeExact(900));
- assertFalse(ETERNAL.isInRangeExact(1234567890));
+ assertThat(SHORT.isInRangeExact(0)).isTrue();
+ assertThat(SHORT.isInRangeExact(1)).isTrue();
+ assertThat(SHORT.isInRangeExact(60)).isFalse();
+ assertThat(MODERATE.isInRangeExact(60)).isTrue();
+ assertThat(MODERATE.isInRangeExact(299)).isTrue();
+ assertThat(MODERATE.isInRangeExact(300)).isFalse();
+ assertThat(LONG.isInRangeExact(300)).isTrue();
+ assertThat(LONG.isInRangeExact(899)).isTrue();
+ assertThat(LONG.isInRangeExact(900)).isFalse();
+ assertThat(ETERNAL.isInRangeExact(900)).isTrue();
+ assertThat(ETERNAL.isInRangeExact(1234567890)).isFalse();
}
@Test
@@ -80,14 +77,14 @@ public class TestTimeoutTest {
private void assertFuzzyRange(TestTimeout timeout, int min, int max) {
if (min > 0) {
- assertFalse(timeout.isInRangeFuzzy(min - 1));
+ assertThat(timeout.isInRangeFuzzy(min - 1)).isFalse();
}
- assertTrue(timeout.isInRangeFuzzy(min));
- assertTrue(timeout.isInRangeFuzzy(min + 1));
- assertTrue(timeout.isInRangeFuzzy(max - 1));
- assertTrue(timeout.isInRangeFuzzy(max));
+ assertThat(timeout.isInRangeFuzzy(min)).isTrue();
+ assertThat(timeout.isInRangeFuzzy(min + 1)).isTrue();
+ assertThat(timeout.isInRangeFuzzy(max - 1)).isTrue();
+ assertThat(timeout.isInRangeFuzzy(max)).isTrue();
if (max < Integer.MAX_VALUE) {
- assertFalse(timeout.isInRangeFuzzy(max + 1));
+ assertThat(timeout.isInRangeFuzzy(max + 1)).isFalse();
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/WorkspaceFactoryTest.java b/src/test/java/com/google/devtools/build/lib/packages/WorkspaceFactoryTest.java
index 84a6a29c31..4fe5b7159f 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/WorkspaceFactoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/WorkspaceFactoryTest.java
@@ -15,8 +15,6 @@
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -52,7 +50,7 @@ public class WorkspaceFactoryTest {
@Test
public void testWorkspaceName() throws Exception {
WorkspaceFactoryHelper helper = parse("workspace(name = 'my_ws')");
- assertEquals("my_ws", helper.getPackage().getWorkspaceName());
+ assertThat(helper.getPackage().getWorkspaceName()).isEqualTo("my_ws");
}
@Test
@@ -140,12 +138,12 @@ public class WorkspaceFactoryTest {
}
public void assertLexingExceptionThrown() {
- assertNotNull(exception);
- assertThat(exception.getMessage()).contains("Failed to parse /workspace/WORKSPACE");
+ assertThat(exception).isNotNull();
+ assertThat(exception).hasMessageThat().contains("Failed to parse /workspace/WORKSPACE");
}
public String getLexerError() {
- assertEquals(1, events.size());
+ assertThat(events).hasSize(1);
return events.get(0).getMessage();
}
diff --git a/src/test/java/com/google/devtools/build/lib/packages/util/PackageFactoryTestBase.java b/src/test/java/com/google/devtools/build/lib/packages/util/PackageFactoryTestBase.java
index 6db84868de..a7103c48db 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/util/PackageFactoryTestBase.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/util/PackageFactoryTestBase.java
@@ -14,10 +14,7 @@
package com.google.devtools.build.lib.packages.util;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -65,7 +62,7 @@ public abstract class PackageFactoryTestBase {
throws InterruptedException, IOException {
Path file = scratch.file("/pkg/BUILD", content);
Package pkg = packages.eval("pkg", file);
- assertFalse(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isFalse();
return pkg;
}
@@ -73,7 +70,9 @@ public abstract class PackageFactoryTestBase {
events.setFailFast(false);
Path file = scratch.file("/pkg/BUILD", content);
Package pkg = packages.eval("pkg", file);
- assertTrue("Expected evaluation error, but none was not reported", pkg.containsErrors());
+ assertWithMessage("Expected evaluation error, but none was not reported")
+ .that(pkg.containsErrors())
+ .isTrue();
events.assertContainsError(expectedError);
}
@@ -90,9 +89,9 @@ public abstract class PackageFactoryTestBase {
for (String outName : outNames) {
OutputFile out = (OutputFile) pkg.getTarget(outName);
assertThat(rule.getOutputFiles()).contains(out);
- assertSame(rule, out.getGeneratingRule());
- assertEquals(outName, out.getName());
- assertEquals("generated file", out.getTargetKind());
+ assertThat(out.getGeneratingRule()).isSameAs(rule);
+ assertThat(out.getName()).isEqualTo(outName);
+ assertThat(out.getTargetKind()).isEqualTo("generated file");
}
assertThat(rule.getOutputFiles()).hasSize(outNames.size());
}
@@ -161,7 +160,7 @@ public abstract class PackageFactoryTestBase {
Package pkg = buildPackageWithGlob(globCallExpression);
events.assertContainsError(expectedError);
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
}
private Package buildPackageWithGlob(String globCallExpression) throws Exception {
@@ -208,9 +207,11 @@ public abstract class PackageFactoryTestBase {
GlobCache globCache = evaluated.second;
// Ensure all of the patterns are recorded against this package:
- assertTrue(globCache.getKeySet().containsAll(createGlobCacheKeys(includes, excludeDirs)));
- assertTrue(globCache.getKeySet().containsAll(createGlobCacheKeys(excludes, excludeDirs)));
- assertFalse(pkg.containsErrors());
+ assertThat(globCache.getKeySet().containsAll(createGlobCacheKeys(includes, excludeDirs)))
+ .isTrue();
+ assertThat(globCache.getKeySet().containsAll(createGlobCacheKeys(excludes, excludeDirs)))
+ .isTrue();
+ assertThat(pkg.containsErrors()).isFalse();
}
/**
@@ -246,7 +247,7 @@ public abstract class PackageFactoryTestBase {
events.setFailFast(false);
Package pkg =
evaluateGlob(ImmutableList.of(pattern), Collections.<String>emptyList(), false, "").first;
- assertEquals(errorExpected, pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isEqualTo(errorExpected);
boolean foundError = false;
for (Event event : events.collector()) {
if (event.getMessage().contains("glob")) {
@@ -258,7 +259,7 @@ public abstract class PackageFactoryTestBase {
break;
}
}
- assertEquals(errorExpected, foundError);
+ assertThat(foundError).isEqualTo(errorExpected);
}
/** Runnable that asks for parsing of build file and synchronizes it with
diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/IncrementalLoadingTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/IncrementalLoadingTest.java
index def12d9fc0..2ff9fa19ed 100644
--- a/src/test/java/com/google/devtools/build/lib/pkgcache/IncrementalLoadingTest.java
+++ b/src/test/java/com/google/devtools/build/lib/pkgcache/IncrementalLoadingTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.pkgcache;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
@@ -118,11 +115,11 @@ public class IncrementalLoadingTest {
"filegroup(name = 'hello', srcs = ['foo.txt'])");
tester.sync();
Target oldTarget = tester.getTarget("//base:hello");
- assertNotNull(oldTarget);
+ assertThat(oldTarget).isNotNull();
tester.sync();
Target newTarget = tester.getTarget("//base:hello");
- assertSame(oldTarget, newTarget);
+ assertThat(newTarget).isSameAs(oldTarget);
}
@Test
@@ -134,7 +131,7 @@ public class IncrementalLoadingTest {
tester.modifyFile("base/BUILD", "filegroup(name = 'hello', srcs = ['bar.txt'])");
tester.sync();
Target newTarget = tester.getTarget("//base:hello");
- assertNotSame(oldTarget, newTarget);
+ assertThat(newTarget).isNotSameAs(oldTarget);
}
@Test
@@ -147,7 +144,7 @@ public class IncrementalLoadingTest {
tester.modifyFile("base/foo.txt", "other");
tester.sync();
Target newTarget = tester.getTarget("//base:hello");
- assertSame(oldTarget, newTarget);
+ assertThat(newTarget).isSameAs(oldTarget);
}
@Test
@@ -160,7 +157,7 @@ public class IncrementalLoadingTest {
tester.removeFile("base/foo.txt");
tester.sync();
Target newTarget = tester.getTarget("//base:hello");
- assertSame(oldTarget, newTarget);
+ assertThat(newTarget).isSameAs(oldTarget);
}
@Test
@@ -172,7 +169,7 @@ public class IncrementalLoadingTest {
tester.modifyFile("base/mybuild", "filegroup(name = 'hello', srcs = ['bar.txt'])");
tester.sync();
Target newTarget = tester.getTarget("//base:hello");
- assertNotSame(oldTarget, newTarget);
+ assertThat(newTarget).isNotSameAs(oldTarget);
}
@Test
@@ -185,7 +182,7 @@ public class IncrementalLoadingTest {
tester.modifyFile("other/BUILD", "filegroup(name = 'hello', srcs = ['bar.txt'])");
tester.sync();
Target newTarget = tester.getTarget("//base:hello");
- assertNotSame(oldTarget, newTarget);
+ assertThat(newTarget).isNotSameAs(oldTarget);
}
@Test
@@ -212,7 +209,7 @@ public class IncrementalLoadingTest {
tester.sync();
Target a3 = tester.getTarget("//a:a");
- assertNotSame(a1, a3);
+ assertThat(a3).isNotSameAs(a1);
}
@Test
@@ -228,7 +225,7 @@ public class IncrementalLoadingTest {
Target a2 = tester.getTarget("//a:a");
tester.sync();
- assertNotSame(a1, a2);
+ assertThat(a2).isNotSameAs(a1);
}
@Test
@@ -242,7 +239,7 @@ public class IncrementalLoadingTest {
tester.sync();
Target fg2 = tester.getTarget("//a:fg");
- assertSame(fg1, fg2);
+ assertThat(fg2).isSameAs(fg1);
}
@Test
@@ -255,7 +252,7 @@ public class IncrementalLoadingTest {
tester.addFile("base/bar.txt", "also nothing");
tester.sync();
Target newTarget = tester.getTarget("//base:hello");
- assertNotSame(oldTarget, newTarget);
+ assertThat(newTarget).isNotSameAs(oldTarget);
}
@Test
@@ -269,7 +266,7 @@ public class IncrementalLoadingTest {
tester.removeFile("base/bar.txt");
tester.sync();
Target newTarget = tester.getTarget("//base:hello");
- assertNotSame(oldTarget, newTarget);
+ assertThat(newTarget).isNotSameAs(oldTarget);
}
@Test
@@ -285,7 +282,7 @@ public class IncrementalLoadingTest {
tester.sync();
Target a2 = tester.getTarget("//a:a");
- assertNotSame(a1, a2);
+ assertThat(a2).isNotSameAs(a1);
}
@Test
@@ -301,7 +298,7 @@ public class IncrementalLoadingTest {
tester.addFile("c");
tester.sync();
Target a3 = tester.getTarget("//a:a");
- assertNotSame(a1, a3);
+ assertThat(a3).isNotSameAs(a1);
}
@Test
@@ -365,7 +362,7 @@ public class IncrementalLoadingTest {
// Write file in directory to force reload of top-level glob.
tester.addFile("pkg/irrelevant_file");
tester.addFile("pkg/bar/irrelevant_file"); // Subglob is also reloaded.
- assertSame(pkg, tester.getTarget("//pkg:pkg").getPackage());
+ assertThat(tester.getTarget("//pkg:pkg").getPackage()).isSameAs(pkg);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java
index eb114ea224..fba9919d54 100644
--- a/src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.lib.pkgcache;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Functions;
@@ -111,7 +107,7 @@ public class LoadingPhaseRunnerTest {
"filegroup(name = 'hello', srcs = ['foo.txt'])");
LoadingResult loadingResult = assertNoErrors(tester.load("//base:hello"));
assertThat(loadingResult.getTargets()).containsExactlyElementsIn(getTargets("//base:hello"));
- assertNull(loadingResult.getTestsToRun());
+ assertThat(loadingResult.getTestsToRun()).isNull();
}
@Test
@@ -156,10 +152,10 @@ public class LoadingPhaseRunnerTest {
public void testBadTargetPatternWithTest() throws Exception {
tester.addFile("base/BUILD");
LoadingResult loadingResult = tester.loadTestsKeepGoing("//base:missing");
- assertTrue(loadingResult.hasTargetPatternError());
- assertFalse(loadingResult.hasLoadingError());
- assertThat(loadingResult.getTargets()).containsExactlyElementsIn(ImmutableList.<Target>of());
- assertThat(loadingResult.getTestsToRun()).containsExactlyElementsIn(ImmutableList.<Target>of());
+ assertThat(loadingResult.hasTargetPatternError()).isTrue();
+ assertThat(loadingResult.hasLoadingError()).isFalse();
+ assertThat(loadingResult.getTargets()).isEmpty();
+ assertThat(loadingResult.getTestsToRun()).isEmpty();
tester.assertContainsError("Skipping '//base:missing': no such target '//base:missing'");
tester.assertContainsWarning("Target pattern parsing failed.");
}
@@ -313,8 +309,8 @@ public class LoadingPhaseRunnerTest {
"test_suite(name = 'tests', tests = ['//nonexistent:my_test'])");
tester.useLoadingOptions("--build_tests_only");
LoadingResult loadingResult = tester.loadTestsKeepGoing("//ts:tests");
- assertTrue(loadingResult.hasTargetPatternError());
- assertFalse(loadingResult.hasLoadingError());
+ assertThat(loadingResult.hasTargetPatternError()).isTrue();
+ assertThat(loadingResult.hasLoadingError()).isFalse();
tester.assertContainsError("no such package 'nonexistent'");
}
@@ -323,8 +319,8 @@ public class LoadingPhaseRunnerTest {
tester.addFile("ts/BUILD",
"test_suite(name = 'tests', tests = [':nonexistent_test'])");
LoadingResult loadingResult = tester.loadKeepGoing("//ts:tests");
- assertFalse(loadingResult.hasTargetPatternError());
- assertTrue(loadingResult.hasLoadingError());
+ assertThat(loadingResult.hasTargetPatternError()).isFalse();
+ assertThat(loadingResult.hasLoadingError()).isTrue();
tester.assertContainsError(
"expecting a test or a test_suite rule but '//ts:nonexistent_test' is not one");
}
@@ -335,8 +331,8 @@ public class LoadingPhaseRunnerTest {
tester.addFile("ts/BUILD",
"test_suite(name = 'tests', tests = ['//other:no_such_test'])");
LoadingResult loadingResult = tester.loadTestsKeepGoing("//ts:tests");
- assertTrue(loadingResult.hasTargetPatternError());
- assertTrue(loadingResult.hasLoadingError());
+ assertThat(loadingResult.hasTargetPatternError()).isTrue();
+ assertThat(loadingResult.hasLoadingError()).isTrue();
tester.assertContainsError("no such target '//other:no_such_test'");
}
@@ -347,8 +343,8 @@ public class LoadingPhaseRunnerTest {
"test_suite(name = 'a', tests = ['//other:no_such_test'])",
"test_suite(name = 'b', tests = [])");
LoadingResult loadingResult = tester.loadTestsKeepGoing("//ts:all");
- assertTrue(loadingResult.hasTargetPatternError());
- assertTrue(loadingResult.hasLoadingError());
+ assertThat(loadingResult.hasTargetPatternError()).isTrue();
+ assertThat(loadingResult.hasLoadingError()).isTrue();
tester.assertContainsError("no such target '//other:no_such_test'");
}
@@ -421,8 +417,8 @@ public class LoadingPhaseRunnerTest {
"filegroup(name = 'hello', srcs = ['foo.txt'])");
LoadingResult firstResult = assertNoErrors(tester.load("//base:hello"));
LoadingResult secondResult = assertNoErrors(tester.load("//base:hello"));
- assertEquals(firstResult.getTargets(), secondResult.getTargets());
- assertEquals(firstResult.getTestsToRun(), secondResult.getTestsToRun());
+ assertThat(secondResult.getTargets()).isEqualTo(firstResult.getTargets());
+ assertThat(secondResult.getTestsToRun()).isEqualTo(firstResult.getTestsToRun());
}
/**
@@ -554,7 +550,7 @@ public class LoadingPhaseRunnerTest {
"cc_library(name = 'hello', srcs = ['hello.cc', '//bad:bad.cc'])");
tester.useLoadingOptions("--compile_one_dependency");
LoadingResult loadingResult = tester.loadKeepGoing("base/hello.cc");
- assertFalse(loadingResult.hasLoadingError());
+ assertThat(loadingResult.hasLoadingError()).isFalse();
}
private void assertCircularSymlinksDuringTargetParsing(String targetPattern) throws Exception {
@@ -568,8 +564,8 @@ public class LoadingPhaseRunnerTest {
}
private LoadingResult assertNoErrors(LoadingResult loadingResult) {
- assertFalse(loadingResult.hasTargetPatternError());
- assertFalse(loadingResult.hasLoadingError());
+ assertThat(loadingResult.hasTargetPatternError()).isFalse();
+ assertThat(loadingResult.hasLoadingError()).isFalse();
tester.assertNoEvents();
return loadingResult;
}
@@ -699,7 +695,7 @@ public class LoadingPhaseRunnerTest {
throw e;
}
if (!keepGoing) {
- assertFalse(storedErrors.hasErrors());
+ assertThat(storedErrors.hasErrors()).isFalse();
}
return result;
}
@@ -755,7 +751,7 @@ public class LoadingPhaseRunnerTest {
StoredEventHandler eventHandler = new StoredEventHandler();
Target target = getPkgManager().getTarget(
eventHandler, Label.parseAbsoluteUnchecked(targetName));
- assertFalse(eventHandler.hasErrors());
+ assertThat(eventHandler.hasErrors()).isFalse();
return target;
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/AbstractCommandTest.java b/src/test/java/com/google/devtools/build/lib/runtime/AbstractCommandTest.java
index 529200f5c6..6f90f033b2 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/AbstractCommandTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/AbstractCommandTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.runtime;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
@@ -24,14 +23,14 @@ import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsProvider;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
/**
* Tests {@link BlazeCommand}.
*/
@@ -70,8 +69,8 @@ public class AbstractCommandTest {
@Test
public void testGetNameYieldsAnnotatedName() {
- assertEquals("test_name",
- new TestCommand().getClass().getAnnotation(Command.class).name());
+ assertThat(new TestCommand().getClass().getAnnotation(Command.class).name())
+ .isEqualTo("test_name");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/AllIncompatibleChangesExpansionTest.java b/src/test/java/com/google/devtools/build/lib/runtime/AllIncompatibleChangesExpansionTest.java
index 7f32df9ba1..0048e0905b 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/AllIncompatibleChangesExpansionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/AllIncompatibleChangesExpansionTest.java
@@ -186,7 +186,7 @@ public class AllIncompatibleChangesExpansionTest {
OptionsParser.newOptionsParser(ExampleOptions.class, optionsBaseClass);
fail("Should have failed with message \"" + message + "\"");
} catch (OptionsParser.ConstructionException e) {
- assertThat(e.getMessage()).contains(message);
+ assertThat(e).hasMessageThat().contains(message);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcherRcoptionsTest.java b/src/test/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcherRcoptionsTest.java
index 2b550ea2a1..105d2b8eae 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcherRcoptionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/BlazeCommandDispatcherRcoptionsTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.runtime;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
@@ -38,20 +38,16 @@ import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsProvider;
-
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Tests the handling of rc-options in {@link BlazeCommandDispatcher}.
- */
+/** Tests the handling of rc-options in {@link BlazeCommandDispatcher}. */
@RunWith(JUnit4.class)
public class BlazeCommandDispatcherRcoptionsTest {
@@ -170,7 +166,7 @@ public class BlazeCommandDispatcherRcoptionsTest {
dispatch.exec(cmdLine, LockingMode.ERROR_OUT, "test", outErr);
String out = outErr.outAsLatin1();
- assertEquals("Common options should be used", "99", out);
+ assertWithMessage("Common options should be used").that(out).isEqualTo("99");
}
@Test
@@ -187,7 +183,7 @@ public class BlazeCommandDispatcherRcoptionsTest {
dispatch.exec(cmdLine, LockingMode.ERROR_OUT, "test", outErr);
String out = outErr.outAsLatin1();
- assertEquals("Specific options should dominate common options", "42", out);
+ assertWithMessage("Specific options should dominate common options").that(out).isEqualTo("42");
}
@Test
@@ -204,7 +200,7 @@ public class BlazeCommandDispatcherRcoptionsTest {
dispatch.exec(cmdLine, LockingMode.ERROR_OUT, "test", outErr);
String out = outErr.outAsLatin1();
- assertEquals("Specific options should dominate common options", "42", out);
+ assertWithMessage("Specific options should dominate common options").that(out).isEqualTo("42");
}
@Test
@@ -222,7 +218,9 @@ public class BlazeCommandDispatcherRcoptionsTest {
dispatch.exec(cmdLine, LockingMode.ERROR_OUT, "test", outErr);
String out = outErr.outAsLatin1();
- assertEquals("Options should get accumulated over different rc files", "99 foo", out);
+ assertWithMessage("Options should get accumulated over different rc files")
+ .that(out)
+ .isEqualTo("99 foo");
}
@Test
@@ -241,7 +239,7 @@ public class BlazeCommandDispatcherRcoptionsTest {
dispatch.exec(cmdLine, LockingMode.ERROR_OUT, "test", outErr);
String out = outErr.outAsLatin1();
- assertEquals("The more specific rc-file should override", "99 foo", out);
+ assertWithMessage("The more specific rc-file should override").that(out).isEqualTo("99 foo");
}
@Test
@@ -260,7 +258,9 @@ public class BlazeCommandDispatcherRcoptionsTest {
dispatch.exec(cmdLine, LockingMode.ERROR_OUT, "test", outErr);
String out = outErr.outAsLatin1();
- assertEquals("The more specific rc-file should override irrespective of name", "99 foo", out);
+ assertWithMessage("The more specific rc-file should override irrespective of name")
+ .that(out)
+ .isEqualTo("99 foo");
}
@Test
@@ -288,12 +288,11 @@ public class BlazeCommandDispatcherRcoptionsTest {
dispatch.exec(cmdLine, LockingMode.ERROR_OUT, "test", outErr);
String out = outErr.outAsLatin1();
- assertEquals(
- String.format(
+ assertWithMessage(String.format(
"The more specific option should override, irrespective of source file or order. %s",
- orderedOpts),
- "42 reportallinherited",
- out);
+ orderedOpts))
+ .that(out)
+ .isEqualTo("42 reportallinherited");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptionsTest.java b/src/test/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptionsTest.java
index 44f48a1b55..239de8f68f 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptionsTest.java
@@ -13,17 +13,14 @@
// limitations under the License.
package com.google.devtools.build.lib.runtime;
-import com.google.devtools.common.options.OptionsParser;
+import static com.google.common.truth.Truth.assertThat;
+import com.google.devtools.common.options.OptionsParser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import static org.junit.Assert.assertNull;
-
-/**
- * A regression test for {@link BlazeServerStartupOptions}.
- */
+/** A regression test for {@link BlazeServerStartupOptions}. */
@RunWith(JUnit4.class)
public class BlazeServerStartupOptionsTest {
@@ -34,6 +31,6 @@ public class BlazeServerStartupOptionsTest {
OptionsParser parser = OptionsParser.newOptionsParser(BlazeServerStartupOptions.class);
parser.parse();
BlazeServerStartupOptions result = parser.getOptions(BlazeServerStartupOptions.class);
- assertNull(result.outputBase);
+ assertThat(result.outputBase).isNull();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/BlazeVersionInfoTest.java b/src/test/java/com/google/devtools/build/lib/runtime/BlazeVersionInfoTest.java
index 3f3c5ca099..67b29c4326 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/BlazeVersionInfoTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/BlazeVersionInfoTest.java
@@ -13,22 +13,18 @@
// limitations under the License.
package com.google.devtools.build.lib.runtime;
+import static com.google.common.truth.Truth.assertThat;
import static java.util.Collections.singletonMap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
import com.google.devtools.build.lib.analysis.BlazeVersionInfo;
import com.google.devtools.build.lib.util.StringUtilities;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests {@link BlazeVersionInfo}.
@@ -39,23 +35,23 @@ public class BlazeVersionInfoTest {
@Test
public void testEmptyVersionInfoMeansNotAvailable() {
BlazeVersionInfo info = new BlazeVersionInfo(Collections.<String, String>emptyMap());
- assertFalse(info.isAvailable());
- assertNull(info.getSummary());
- assertEquals("development version", info.getReleaseName());
+ assertThat(info.isAvailable()).isFalse();
+ assertThat(info.getSummary()).isNull();
+ assertThat(info.getReleaseName()).isEqualTo("development version");
}
@Test
public void testReleaseNameIsDevelopmentIfBuildLabelIsNull() {
Map<String, String> data = singletonMap("Build label", "");
BlazeVersionInfo info = new BlazeVersionInfo(data);
- assertEquals("development version", info.getReleaseName());
+ assertThat(info.getReleaseName()).isEqualTo("development version");
}
@Test
public void testReleaseNameIfBuildLabelIsPresent() {
Map<String, String> data = singletonMap("Build label", "3/4/2009 (gold)");
BlazeVersionInfo info = new BlazeVersionInfo(data);
- assertEquals("release 3/4/2009 (gold)", info.getReleaseName());
+ assertThat(info.getReleaseName()).isEqualTo("release 3/4/2009 (gold)");
}
@Test
@@ -66,6 +62,6 @@ public class BlazeVersionInfoTest {
data.put("And a third entry", "baz");
BlazeVersionInfo info = new BlazeVersionInfo(data);
Map<String, String> sortedData = new TreeMap<>(data);
- assertEquals(StringUtilities.layoutTable(sortedData), info.getSummary());
+ assertThat(info.getSummary()).isEqualTo(StringUtilities.layoutTable(sortedData));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerModuleTest.java b/src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerModuleTest.java
index ad5a87c745..7421f69ed6 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerModuleTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerModuleTest.java
@@ -131,6 +131,6 @@ public class BuildEventStreamerModuleTest {
BuildEventStreamerModule module = new BuildEventStreamerModule();
Optional<BuildEventStreamer> buildEventStreamer =
module.tryCreateStreamer(optionsProvider, moduleEnvironment);
- assertThat(buildEventStreamer.isPresent()).isFalse();
+ assertThat(buildEventStreamer).isAbsent();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerTest.java b/src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerTest.java
index 96dd01276f..76272294fa 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/BuildEventStreamerTest.java
@@ -14,9 +14,7 @@
package com.google.devtools.build.lib.runtime;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -275,7 +273,7 @@ public class BuildEventStreamerTest extends FoundationTestCase {
EventBusHandler handler = new EventBusHandler();
eventBus.register(handler);
- assertNull(handler.transportSet);
+ assertThat(handler.transportSet).isNull();
RecordingBuildEventTransport transport = new RecordingBuildEventTransport();
BuildEventStreamer streamer =
@@ -290,15 +288,15 @@ public class BuildEventStreamerTest extends FoundationTestCase {
List<BuildEvent> afterFirstEvent = transport.getEvents();
assertThat(afterFirstEvent).hasSize(1);
- assertEquals(startEvent.getEventId(), afterFirstEvent.get(0).getEventId());
- assertEquals(1, handler.transportSet.size());
+ assertThat(afterFirstEvent.get(0).getEventId()).isEqualTo(startEvent.getEventId());
+ assertThat(handler.transportSet).hasSize(1);
streamer.buildEvent(new BuildCompleteEvent(new BuildResult(0)));
List<BuildEvent> finalStream = transport.getEvents();
assertThat(finalStream).hasSize(3);
- assertEquals(BuildEventId.buildFinished(), finalStream.get(1).getEventId());
- assertEquals(ProgressEvent.INITIAL_PROGRESS_UPDATE, finalStream.get(2).getEventId());
+ assertThat(finalStream.get(1).getEventId()).isEqualTo(BuildEventId.buildFinished());
+ assertThat(finalStream.get(2).getEventId()).isEqualTo(ProgressEvent.INITIAL_PROGRESS_UPDATE);
while (!handler.transportSet.isEmpty()) {
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
@@ -325,13 +323,13 @@ public class BuildEventStreamerTest extends FoundationTestCase {
List<BuildEvent> eventsSeen = transport.getEvents();
assertThat(eventsSeen).hasSize(3);
- assertEquals(startEvent.getEventId(), eventsSeen.get(0).getEventId());
- assertEquals(unexpectedEvent.getEventId(), eventsSeen.get(2).getEventId());
+ assertThat(eventsSeen.get(0).getEventId()).isEqualTo(startEvent.getEventId());
+ assertThat(eventsSeen.get(2).getEventId()).isEqualTo(unexpectedEvent.getEventId());
BuildEvent linkEvent = eventsSeen.get(1);
- assertEquals(ProgressEvent.INITIAL_PROGRESS_UPDATE, linkEvent.getEventId());
- assertTrue(
- "Unexpected events should be linked",
- linkEvent.getChildrenEvents().contains(unexpectedEvent.getEventId()));
+ assertThat(linkEvent.getEventId()).isEqualTo(ProgressEvent.INITIAL_PROGRESS_UPDATE);
+ assertWithMessage("Unexpected events should be linked")
+ .that(linkEvent.getChildrenEvents().contains(unexpectedEvent.getEventId()))
+ .isTrue();
}
@Test
@@ -351,12 +349,12 @@ public class BuildEventStreamerTest extends FoundationTestCase {
List<BuildEvent> eventsSeen = transport.getEvents();
assertThat(eventsSeen).hasSize(2);
- assertEquals(unexpectedStartEvent.getEventId(), eventsSeen.get(1).getEventId());
+ assertThat(eventsSeen.get(1).getEventId()).isEqualTo(unexpectedStartEvent.getEventId());
BuildEvent initial = eventsSeen.get(0);
- assertEquals(ProgressEvent.INITIAL_PROGRESS_UPDATE, initial.getEventId());
- assertTrue(
- "Event should be linked",
- initial.getChildrenEvents().contains(unexpectedStartEvent.getEventId()));
+ assertThat(initial.getEventId()).isEqualTo(ProgressEvent.INITIAL_PROGRESS_UPDATE);
+ assertWithMessage("Event should be linked")
+ .that(initial.getChildrenEvents().contains(unexpectedStartEvent.getEventId()))
+ .isTrue();
// The initial event should also announce a new progress event; we test this
// by streaming another unannounced event.
@@ -367,14 +365,14 @@ public class BuildEventStreamerTest extends FoundationTestCase {
streamer.buildEvent(unexpectedEvent);
List<BuildEvent> allEventsSeen = transport.getEvents();
assertThat(allEventsSeen).hasSize(4);
- assertEquals(unexpectedEvent.getEventId(), allEventsSeen.get(3).getEventId());
+ assertThat(allEventsSeen.get(3).getEventId()).isEqualTo(unexpectedEvent.getEventId());
BuildEvent secondLinkEvent = allEventsSeen.get(2);
- assertTrue(
- "Progress should have been announced",
- initial.getChildrenEvents().contains(secondLinkEvent.getEventId()));
- assertTrue(
- "Second event should be linked",
- secondLinkEvent.getChildrenEvents().contains(unexpectedEvent.getEventId()));
+ assertWithMessage("Progress should have been announced")
+ .that(initial.getChildrenEvents().contains(secondLinkEvent.getEventId()))
+ .isTrue();
+ assertWithMessage("Second event should be linked")
+ .that(secondLinkEvent.getChildrenEvents().contains(unexpectedEvent.getEventId()))
+ .isTrue();
}
@Test
@@ -408,7 +406,7 @@ public class BuildEventStreamerTest extends FoundationTestCase {
}
}
// The early event should be reported precisely once.
- assertEquals(1, earlyEventCount);
+ assertThat(earlyEventCount).isEqualTo(1);
}
@Test
@@ -435,11 +433,11 @@ public class BuildEventStreamerTest extends FoundationTestCase {
List<BuildEvent> allEventsSeen = transport.getEvents();
assertThat(allEventsSeen).hasSize(4);
- assertEquals(startEvent.getEventId(), allEventsSeen.get(0).getEventId());
+ assertThat(allEventsSeen.get(0).getEventId()).isEqualTo(startEvent.getEventId());
BuildEvent linkEvent = allEventsSeen.get(1);
- assertEquals(ProgressEvent.INITIAL_PROGRESS_UPDATE, linkEvent.getEventId());
- assertEquals(rootCause.getEventId(), allEventsSeen.get(2).getEventId());
- assertEquals(failedTarget.getEventId(), allEventsSeen.get(3).getEventId());
+ assertThat(linkEvent.getEventId()).isEqualTo(ProgressEvent.INITIAL_PROGRESS_UPDATE);
+ assertThat(allEventsSeen.get(2).getEventId()).isEqualTo(rootCause.getEventId());
+ assertThat(allEventsSeen.get(3).getEventId()).isEqualTo(failedTarget.getEventId());
}
@Test
@@ -467,12 +465,12 @@ public class BuildEventStreamerTest extends FoundationTestCase {
List<BuildEvent> allEventsSeen = transport.getEvents();
assertThat(allEventsSeen).hasSize(6);
- assertEquals(startEvent.getEventId(), allEventsSeen.get(0).getEventId());
- assertEquals(BuildEventId.buildFinished(), allEventsSeen.get(1).getEventId());
+ assertThat(allEventsSeen.get(0).getEventId()).isEqualTo(startEvent.getEventId());
+ assertThat(allEventsSeen.get(1).getEventId()).isEqualTo(BuildEventId.buildFinished());
BuildEvent linkEvent = allEventsSeen.get(2);
- assertEquals(ProgressEvent.INITIAL_PROGRESS_UPDATE, linkEvent.getEventId());
- assertEquals(rootCauseId, allEventsSeen.get(3).getEventId());
- assertEquals(failedTarget.getEventId(), allEventsSeen.get(4).getEventId());
+ assertThat(linkEvent.getEventId()).isEqualTo(ProgressEvent.INITIAL_PROGRESS_UPDATE);
+ assertThat(allEventsSeen.get(3).getEventId()).isEqualTo(rootCauseId);
+ assertThat(allEventsSeen.get(4).getEventId()).isEqualTo(failedTarget.getEventId());
}
@Test
@@ -496,8 +494,8 @@ public class BuildEventStreamerTest extends FoundationTestCase {
List<BuildEvent> allEventsSeen = transport.getEvents();
assertThat(allEventsSeen).hasSize(2);
- assertEquals(startEvent.getEventId(), allEventsSeen.get(0).getEventId());
- assertEquals(waitingForStart.getEventId(), allEventsSeen.get(1).getEventId());
+ assertThat(allEventsSeen.get(0).getEventId()).isEqualTo(startEvent.getEventId());
+ assertThat(allEventsSeen.get(1).getEventId()).isEqualTo(waitingForStart.getEventId());
}
private Artifact makeArtifact(String pathString) {
@@ -531,23 +529,22 @@ public class BuildEventStreamerTest extends FoundationTestCase {
List<BuildEvent> allEventsSeen = transport.getEvents();
List<BuildEventStreamProtos.BuildEvent> eventProtos = transport.getEventProtos();
- assertEquals(7, allEventsSeen.size());
- assertEquals(startEvent.getEventId(), allEventsSeen.get(0).getEventId());
- assertEquals(ProgressEvent.INITIAL_PROGRESS_UPDATE, allEventsSeen.get(1).getEventId());
+ assertThat(allEventsSeen).hasSize(7);
+ assertThat(allEventsSeen.get(0).getEventId()).isEqualTo(startEvent.getEventId());
+ assertThat(allEventsSeen.get(1).getEventId()).isEqualTo(ProgressEvent.INITIAL_PROGRESS_UPDATE);
List<BuildEventStreamProtos.File> firstSetDirects =
eventProtos.get(2).getNamedSetOfFiles().getFilesList();
- assertEquals(2, firstSetDirects.size());
- assertEquals(
- ImmutableSet.of(a.getPath().toString(), b.getPath().toString()),
- ImmutableSet.of(firstSetDirects.get(0).getUri(), firstSetDirects.get(1).getUri()));
+ assertThat(firstSetDirects).hasSize(2);
+ assertThat(ImmutableSet.of(firstSetDirects.get(0).getUri(), firstSetDirects.get(1).getUri()))
+ .isEqualTo(ImmutableSet.of(a.getPath().toString(), b.getPath().toString()));
List<NamedSetOfFilesId> secondSetTransitives =
eventProtos.get(4).getNamedSetOfFiles().getFileSetsList();
- assertEquals(1, secondSetTransitives.size());
- assertEquals(eventProtos.get(2).getId().getNamedSet(), secondSetTransitives.get(0));
+ assertThat(secondSetTransitives).hasSize(1);
+ assertThat(secondSetTransitives.get(0)).isEqualTo(eventProtos.get(2).getId().getNamedSet());
List<NamedSetOfFilesId> reportedArtifactSets =
eventProtos.get(6).getNamedSetOfFiles().getFileSetsList();
- assertEquals(1, reportedArtifactSets.size());
- assertEquals(eventProtos.get(4).getId().getNamedSet(), reportedArtifactSets.get(0));
+ assertThat(reportedArtifactSets).hasSize(1);
+ assertThat(reportedArtifactSets.get(0)).isEqualTo(eventProtos.get(4).getId().getNamedSet());
}
@Test
@@ -576,16 +573,16 @@ public class BuildEventStreamerTest extends FoundationTestCase {
List<BuildEvent> eventsSeen = transport.getEvents();
assertThat(eventsSeen).hasSize(3);
- assertEquals(startEvent.getEventId(), eventsSeen.get(0).getEventId());
- assertEquals(unexpectedEvent.getEventId(), eventsSeen.get(2).getEventId());
+ assertThat(eventsSeen.get(0).getEventId()).isEqualTo(startEvent.getEventId());
+ assertThat(eventsSeen.get(2).getEventId()).isEqualTo(unexpectedEvent.getEventId());
BuildEvent linkEvent = eventsSeen.get(1);
BuildEventStreamProtos.BuildEvent linkEventProto = transport.getEventProtos().get(1);
- assertEquals(ProgressEvent.INITIAL_PROGRESS_UPDATE, linkEvent.getEventId());
- assertTrue(
- "Unexpected events should be linked",
- linkEvent.getChildrenEvents().contains(unexpectedEvent.getEventId()));
- assertEquals(stdoutMsg, linkEventProto.getProgress().getStdout());
- assertEquals(stderrMsg, linkEventProto.getProgress().getStderr());
+ assertThat(linkEvent.getEventId()).isEqualTo(ProgressEvent.INITIAL_PROGRESS_UPDATE);
+ assertWithMessage("Unexpected events should be linked")
+ .that(linkEvent.getChildrenEvents().contains(unexpectedEvent.getEventId()))
+ .isTrue();
+ assertThat(linkEventProto.getProgress().getStdout()).isEqualTo(stdoutMsg);
+ assertThat(linkEventProto.getProgress().getStderr()).isEqualTo(stderrMsg);
// As there is only one progress event, the OutErrProvider should be queried
// only once for stdout and stderr.
@@ -622,13 +619,13 @@ public class BuildEventStreamerTest extends FoundationTestCase {
streamer.buildEvent(secondWithConfiguration);
List<BuildEvent> allEventsSeen = transport.getEvents();
- assertEquals(7, allEventsSeen.size());
- assertEquals(startEvent.getEventId(), allEventsSeen.get(0).getEventId());
- assertEquals(ProgressEvent.INITIAL_PROGRESS_UPDATE, allEventsSeen.get(1).getEventId());
- assertEquals(configuration, allEventsSeen.get(2));
- assertEquals(BuildEventId.progressId(1), allEventsSeen.get(3).getEventId());
- assertEquals(firstWithConfiguration, allEventsSeen.get(4));
- assertEquals(BuildEventId.progressId(2), allEventsSeen.get(5).getEventId());
- assertEquals(secondWithConfiguration, allEventsSeen.get(6));
+ assertThat(allEventsSeen).hasSize(7);
+ assertThat(allEventsSeen.get(0).getEventId()).isEqualTo(startEvent.getEventId());
+ assertThat(allEventsSeen.get(1).getEventId()).isEqualTo(ProgressEvent.INITIAL_PROGRESS_UPDATE);
+ assertThat(allEventsSeen.get(2)).isEqualTo(configuration);
+ assertThat(allEventsSeen.get(3).getEventId()).isEqualTo(BuildEventId.progressId(1));
+ assertThat(allEventsSeen.get(4)).isEqualTo(firstWithConfiguration);
+ assertThat(allEventsSeen.get(5).getEventId()).isEqualTo(BuildEventId.progressId(2));
+ assertThat(allEventsSeen.get(6)).isEqualTo(secondWithConfiguration);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/ExperimentalStateTrackerTest.java b/src/test/java/com/google/devtools/build/lib/runtime/ExperimentalStateTrackerTest.java
index f17abd8f61..6212a7f7e4 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/ExperimentalStateTrackerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/ExperimentalStateTrackerTest.java
@@ -13,12 +13,11 @@
// limitations under the License.
package com.google.devtools.build.lib.runtime;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import com.google.common.base.Strings;
@@ -103,15 +102,16 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Output should indicate that we are in the loading phase, but was:\n" + output,
- output.contains("Loading"));
- assertTrue(
- "Output should contain loading state '" + state + "', but was:\n" + output,
- output.contains(state));
- assertTrue(
- "Output should contain loading state '" + activity + "', but was:\n" + output,
- output.contains(activity));
+ assertWithMessage(
+ "Output should indicate that we are in the loading phase, but was:\n" + output)
+ .that(output.contains("Loading"))
+ .isTrue();
+ assertWithMessage("Output should contain loading state '" + state + "', but was:\n" + output)
+ .that(output.contains(state))
+ .isTrue();
+ assertWithMessage("Output should contain loading state '" + activity + "', but was:\n" + output)
+ .that(output.contains(activity))
+ .isTrue();
}
@Test
@@ -129,16 +129,17 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Action message '" + message + "' should be present in output: " + output,
- output.contains(message));
+ assertWithMessage("Action message '" + message + "' should be present in output: " + output)
+ .that(output.contains(message))
+ .isTrue();
terminalWriter = new LoggingTerminalWriter();
stateTracker.writeProgressBar(terminalWriter, /* shortVersion=*/ true);
output = terminalWriter.getTranscript();
- assertTrue(
- "Action message '" + message + "' should be present in short output: " + output,
- output.contains(message));
+ assertWithMessage(
+ "Action message '" + message + "' should be present in short output: " + output)
+ .that(output.contains(message))
+ .isTrue();
}
@Test
@@ -162,22 +163,32 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertFalse(
- "Completed action '" + messageFast + "' should not be present in output: " + output,
- output.contains(messageFast));
- assertTrue(
- "Only running action '" + messageSlow + "' should be present in output: " + output,
- output.contains(messageSlow));
+ assertWithMessage(
+ "Completed action '" + messageFast + "' should not be present in output: " + output)
+ .that(output.contains(messageFast))
+ .isFalse();
+ assertWithMessage(
+ "Only running action '" + messageSlow + "' should be present in output: " + output)
+ .that(output.contains(messageSlow))
+ .isTrue();
terminalWriter = new LoggingTerminalWriter();
stateTracker.writeProgressBar(terminalWriter, /* shortVersion=*/ true);
output = terminalWriter.getTranscript();
- assertFalse(
- "Completed action '" + messageFast + "' should not be present in short output: " + output,
- output.contains(messageFast));
- assertTrue(
- "Only running action '" + messageSlow + "' should be present in short output: " + output,
- output.contains(messageSlow));
+ assertWithMessage(
+ "Completed action '"
+ + messageFast
+ + "' should not be present in short output: "
+ + output)
+ .that(output.contains(messageFast))
+ .isFalse();
+ assertWithMessage(
+ "Only running action '"
+ + messageSlow
+ + "' should be present in short output: "
+ + output)
+ .that(output.contains(messageSlow))
+ .isTrue();
}
@Test
@@ -201,16 +212,21 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Longest running action '" + messageOld + "' should be visible in output: " + output,
- output.contains(messageOld));
+ assertWithMessage(
+ "Longest running action '" + messageOld + "' should be visible in output: " + output)
+ .that(output.contains(messageOld))
+ .isTrue();
terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter, /* shortVersion=*/ true);
output = terminalWriter.getTranscript();
- assertTrue(
- "Longest running action '" + messageOld + "' should be visible in short output: " + output,
- output.contains(messageOld));
+ assertWithMessage(
+ "Longest running action '"
+ + messageOld
+ + "' should be visible in short output: "
+ + output)
+ .that(output.contains(messageOld))
+ .isTrue();
}
@Test
@@ -234,17 +250,20 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Action " + (i - 1) + " should still be shown in the output: '" + output,
- output.contains("A" + (i - 1) + "."));
- assertFalse(
- "Action " + i + " should not be shown in the output: " + output,
- output.contains("A" + i + "."));
+ assertWithMessage("Action " + (i - 1) + " should still be shown in the output: '" + output)
+ .that(output.contains("A" + (i - 1) + "."))
+ .isTrue();
+ assertWithMessage("Action " + i + " should not be shown in the output: " + output)
+ .that(output.contains("A" + i + "."))
+ .isFalse();
if (i < 10) {
- assertTrue("Ellipsis symbol should be shown in output: " + output, output.contains("..."));
+ assertWithMessage("Ellipsis symbol should be shown in output: " + output)
+ .that(output.contains("..."))
+ .isTrue();
} else {
- assertFalse(
- "Ellipsis symbol should not be shown in output: " + output, output.contains("..."));
+ assertWithMessage("Ellipsis symbol should not be shown in output: " + output)
+ .that(output.contains("..."))
+ .isFalse();
}
}
}
@@ -269,17 +288,19 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Runtime of first action should be visible in output: " + output, output.contains("27s"));
- assertTrue(
- "Runtime of second action should be visible in output: " + output, output.contains("20s"));
+ assertWithMessage("Runtime of first action should be visible in output: " + output)
+ .that(output.contains("27s"))
+ .isTrue();
+ assertWithMessage("Runtime of second action should be visible in output: " + output)
+ .that(output.contains("20s"))
+ .isTrue();
terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter, /* shortVersion=*/ true);
output = terminalWriter.getTranscript();
- assertTrue(
- "Runtime of first action should be visible in short output: " + output,
- output.contains("27s"));
+ assertWithMessage("Runtime of first action should be visible in short output: " + output)
+ .that(output.contains("27s"))
+ .isTrue();
}
@Test
@@ -288,9 +309,9 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
clock.advanceMillis(TimeUnit.SECONDS.toMillis(123));
ExperimentalStateTracker stateTracker = new ExperimentalStateTracker(clock);
- assertFalse(
- "Initial progress status should be time independent",
- stateTracker.progressBarTimeDependent());
+ assertWithMessage("Initial progress status should be time independent")
+ .that(stateTracker.progressBarTimeDependent())
+ .isFalse();
}
@Test
@@ -302,9 +323,9 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.actionStarted(
new ActionStartedEvent(mockAction("Some action", "foo"), clock.nanoTime()));
- assertTrue(
- "Progress bar showing a running action should be time dependent",
- stateTracker.progressBarTimeDependent());
+ assertWithMessage("Progress bar showing a running action should be time dependent")
+ .that(stateTracker.progressBarTimeDependent())
+ .isTrue();
}
@Test
@@ -327,14 +348,16 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
LoggingTerminalWriter terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Test count should be visible in output: " + output, output.contains(" 1 / 2 tests"));
+ assertWithMessage("Test count should be visible in output: " + output)
+ .that(output.contains(" 1 / 2 tests"))
+ .isTrue();
terminalWriter = new LoggingTerminalWriter(/*discardHighlight=*/ true);
stateTracker.writeProgressBar(terminalWriter, /* shortVersion=*/ true);
output = terminalWriter.getTranscript();
- assertTrue(
- "Test count should be visible in short output: " + output, output.contains(" 1 / 2 tests"));
+ assertWithMessage("Test count should be visible in short output: " + output)
+ .that(output.contains(" 1 / 2 tests"))
+ .isTrue();
}
@Test
@@ -360,9 +383,10 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
String output = terminalWriter.getTranscript();
String expected = LoggingTerminalWriter.OK + labelA;
- assertTrue(
- "Sequence '" + expected + "' should be present in colored progress bar: " + output,
- output.contains(expected));
+ assertWithMessage(
+ "Sequence '" + expected + "' should be present in colored progress bar: " + output)
+ .that(output.contains(expected))
+ .isTrue();
}
@Test
@@ -389,9 +413,10 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
String output = terminalWriter.getTranscript();
String expected = LoggingTerminalWriter.FAIL + labelA;
- assertTrue(
- "Sequence '" + expected + "' should be present in colored progress bar: " + output,
- output.contains(expected));
+ assertWithMessage(
+ "Sequence '" + expected + "' should be present in colored progress bar: " + output)
+ .that(output.contains(expected))
+ .isTrue();
}
@Test
@@ -418,12 +443,13 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Progress bar should contain 'Building ', but was:\n" + output,
- output.contains("Building "));
- assertTrue(
- "Progress bar should contain 'foo.jar (42 source files)', but was:\n" + output,
- output.contains("foo.jar (42 source files)"));
+ assertWithMessage("Progress bar should contain 'Building ', but was:\n" + output)
+ .that(output.contains("Building "))
+ .isTrue();
+ assertWithMessage(
+ "Progress bar should contain 'foo.jar (42 source files)', but was:\n" + output)
+ .that(output.contains("foo.jar (42 source files)"))
+ .isTrue();
}
@Test
@@ -449,9 +475,9 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Output should mention strategy '" + strategy + "', but was: " + output,
- output.contains(strategy));
+ assertWithMessage("Output should mention strategy '" + strategy + "', but was: " + output)
+ .that(output.contains(strategy))
+ .isTrue();
}
private void doTestOutputLength(boolean withTest, int actions) throws Exception {
@@ -496,23 +522,24 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Only lines with at most 70 chars should be present in the output:\n" + output,
- longestLine(output) <= 70);
+ assertWithMessage(
+ "Only lines with at most 70 chars should be present in the output:\n" + output)
+ .that(longestLine(output) <= 70)
+ .isTrue();
if (actions >= 1) {
- assertTrue(
- "Running action 'foobuild' should be mentioned in output:\n" + output,
- output.contains("foobuild"));
+ assertWithMessage("Running action 'foobuild' should be mentioned in output:\n" + output)
+ .that(output.contains("foobuild"))
+ .isTrue();
}
if (actions >= 2) {
- assertTrue(
- "Running action 'bazbuild' should be mentioned in output:\n" + output,
- output.contains("bazbuild"));
+ assertWithMessage("Running action 'bazbuild' should be mentioned in output:\n" + output)
+ .that(output.contains("bazbuild"))
+ .isTrue();
}
if (withTest) {
- assertTrue(
- "Passed test ':bartest' should be mentioned in output:\n" + output,
- output.contains(":bartest"));
+ assertWithMessage("Passed test ':bartest' should be mentioned in output:\n" + output)
+ .that(output.contains(":bartest"))
+ .isTrue();
}
}
@@ -575,21 +602,23 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Progress bar should contain ':footest', but was:\n" + output, output.contains(":footest"));
- assertTrue(
- "Progress bar should contain ':bartest', but was:\n" + output, output.contains(":bartest"));
- assertTrue(
- "Progress bar should contain 'Other action', but was:\n" + output,
- output.contains("Other action"));
+ assertWithMessage("Progress bar should contain ':footest', but was:\n" + output)
+ .that(output.contains(":footest"))
+ .isTrue();
+ assertWithMessage("Progress bar should contain ':bartest', but was:\n" + output)
+ .that(output.contains(":bartest"))
+ .isTrue();
+ assertWithMessage("Progress bar should contain 'Other action', but was:\n" + output)
+ .that(output.contains("Other action"))
+ .isTrue();
}
@Test
public void testSuffix() throws Exception {
- assertEquals("bar", ExperimentalStateTracker.suffix("foobar", 3));
- assertEquals("", ExperimentalStateTracker.suffix("foo", -2));
- assertEquals("foobar", ExperimentalStateTracker.suffix("foobar", 200));
+ assertThat(ExperimentalStateTracker.suffix("foobar", 3)).isEqualTo("bar");
+ assertThat(ExperimentalStateTracker.suffix("foo", -2)).isEmpty();
+ assertThat(ExperimentalStateTracker.suffix("foobar", 200)).isEqualTo("foobar");
}
@Test
@@ -610,10 +639,12 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Progress bar should contain '" + url.toString() + "', but was:\n" + output,
- output.contains(url.toString()));
- assertTrue("Progress bar should contain '6s', but was:\n" + output, output.contains("6s"));
+ assertWithMessage("Progress bar should contain '" + url.toString() + "', but was:\n" + output)
+ .that(output.contains(url.toString()))
+ .isTrue();
+ assertWithMessage("Progress bar should contain '6s', but was:\n" + output)
+ .that(output.contains("6s"))
+ .isTrue();
// Progress on the pending download should be reported appropriately
clock.advanceMillis(TimeUnit.SECONDS.toMillis(1));
@@ -623,11 +654,15 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
output = terminalWriter.getTranscript();
- assertTrue(
- "Progress bar should contain '" + url.toString() + "', but was:\n" + output,
- output.contains(url.toString()));
- assertTrue("Progress bar should contain '7s', but was:\n" + output, output.contains("7s"));
- assertTrue("Progress bar should contain '256', but was:\n" + output, output.contains("256"));
+ assertWithMessage("Progress bar should contain '" + url.toString() + "', but was:\n" + output)
+ .that(output.contains(url.toString()))
+ .isTrue();
+ assertWithMessage("Progress bar should contain '7s', but was:\n" + output)
+ .that(output.contains("7s"))
+ .isTrue();
+ assertWithMessage("Progress bar should contain '256', but was:\n" + output)
+ .that(output.contains("256"))
+ .isTrue();
// After finishing the download, it should no longer be reported.
clock.advanceMillis(TimeUnit.SECONDS.toMillis(1));
@@ -637,8 +672,9 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
output = terminalWriter.getTranscript();
- assertFalse(
- "Progress bar should not contain url, but was:\n" + output, output.contains("example.org"));
+ assertWithMessage("Progress bar should not contain url, but was:\n" + output)
+ .that(output.contains("example.org"))
+ .isFalse();
}
@Test
@@ -667,15 +703,16 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(
- "Only lines with at most 60 chars should be present in the output:\n" + output,
- longestLine(output) <= 60);
- assertTrue(
- "Output still should contain the filename, but was:\n" + output,
- output.contains("filename.tar.gz"));
- assertTrue(
- "Output still should contain the host name, but was:\n" + output,
- output.contains("example.org"));
+ assertWithMessage(
+ "Only lines with at most 60 chars should be present in the output:\n" + output)
+ .that(longestLine(output) <= 60)
+ .isTrue();
+ assertWithMessage("Output still should contain the filename, but was:\n" + output)
+ .that(output.contains("filename.tar.gz"))
+ .isTrue();
+ assertWithMessage("Output still should contain the host name, but was:\n" + output)
+ .that(output.contains("example.org"))
+ .isTrue();
}
@Test
@@ -749,7 +786,7 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
assertThat(output, not(containsString("BuildEventTransport3")));
assertThat(output, containsString("success"));
assertThat(output, containsString("complete"));
- assertEquals(1, output.split("\\n").length);
+ assertThat(output.split("\\n")).hasLength(1);
}
@Test
@@ -771,7 +808,7 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
clock.advanceMillis(TimeUnit.SECONDS.toMillis(1));
stateTracker.writeProgressBar(terminalWriter);
String output = terminalWriter.getTranscript();
- assertTrue(longestLine(output) <= 60);
+ assertThat(longestLine(output)).isAtMost(60);
assertThat(output, containsString("1s"));
assertThat(output, containsString(Strings.repeat("A", 30) + "..."));
assertThat(output, containsString("BuildEventTransport"));
@@ -783,13 +820,13 @@ public class ExperimentalStateTrackerTest extends FoundationTestCase {
terminalWriter = new LoggingTerminalWriter(true);
stateTracker.writeProgressBar(terminalWriter);
output = terminalWriter.getTranscript();
- assertTrue(longestLine(output) <= 60);
+ assertThat(longestLine(output)).isAtMost(60);
assertThat(output, containsString("2s"));
assertThat(output, containsString(Strings.repeat("A", 30) + "..."));
assertThat(output, not(containsString("BuildEventTransport")));
assertThat(output, containsString("success"));
assertThat(output, containsString("complete"));
- assertEquals(2, output.split("\\n").length);
+ assertThat(output.split("\\n")).hasLength(2);
}
private BuildEventTransport newBepTransport(String name) {
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyAllowValuesTest.java b/src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyAllowValuesTest.java
index 86e269d742..01556172b4 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyAllowValuesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyAllowValuesTest.java
@@ -265,7 +265,8 @@ public class InvocationPolicyAllowValuesTest extends InvocationPolicyEnforcerTes
enforcer.enforce(parser, BUILD_COMMAND);
fail();
} catch (OptionsParsingException e) {
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.contains(
"Flag value 'b' for flag 'test_list_converters' is not allowed by invocation policy");
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyDisallowValuesTest.java b/src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyDisallowValuesTest.java
index 1f81d83ab2..c7f751dada 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyDisallowValuesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/InvocationPolicyDisallowValuesTest.java
@@ -197,7 +197,7 @@ public class InvocationPolicyDisallowValuesTest extends InvocationPolicyEnforcer
enforcer.enforce(parser, BUILD_COMMAND);
fail();
} catch (OptionsParsingException e) {
- assertThat(e.getMessage()).contains("but also specifies to use the default value");
+ assertThat(e).hasMessageThat().contains("but also specifies to use the default value");
}
}
@@ -267,7 +267,8 @@ public class InvocationPolicyDisallowValuesTest extends InvocationPolicyEnforcer
enforcer.enforce(parser, BUILD_COMMAND);
fail();
} catch (OptionsParsingException e) {
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.contains(
"Flag value 'a' for flag 'test_list_converters' is not allowed by invocation policy");
}
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/TestResultAnalyzerTest.java b/src/test/java/com/google/devtools/build/lib/runtime/TestResultAnalyzerTest.java
index c1a104d599..f2b690fe38 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/TestResultAnalyzerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/TestResultAnalyzerTest.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.runtime;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -58,8 +57,8 @@ public class TestResultAnalyzerTest {
@Test
public void testIncrementalAnalyzeSetsActionRanTrueWhenThereAreNonCachedResults() {
TestSummary.Builder summaryBuilder = makeTestSummaryBuilder();
- assertFalse(summaryBuilder.peek().actionRan());
-
+ assertThat(summaryBuilder.peek().actionRan()).isFalse();
+
TestResultData testResultData = TestResultData.newBuilder().setRemotelyCached(false).build();
TestResult result = new TestResult(
mock(TestRunnerAction.class),
@@ -67,14 +66,14 @@ public class TestResultAnalyzerTest {
/*cached=*/false);
TestSummary.Builder newSummaryBuilder = underTest.incrementalAnalyze(summaryBuilder, result);
- assertTrue(newSummaryBuilder.peek().actionRan());
+ assertThat(newSummaryBuilder.peek().actionRan()).isTrue();
}
@Test
public void testIncrementalAnalyzeSetsActionRanFalseForLocallyCachedTests() {
TestSummary.Builder summaryBuilder = makeTestSummaryBuilder();
- assertFalse(summaryBuilder.peek().actionRan());
-
+ assertThat(summaryBuilder.peek().actionRan()).isFalse();
+
TestResultData testResultData = TestResultData.newBuilder().setRemotelyCached(false).build();
TestResult result = new TestResult(
mock(TestRunnerAction.class),
@@ -82,14 +81,14 @@ public class TestResultAnalyzerTest {
/*cached=*/true);
TestSummary.Builder newSummaryBuilder = underTest.incrementalAnalyze(summaryBuilder, result);
- assertFalse(newSummaryBuilder.peek().actionRan());
+ assertThat(newSummaryBuilder.peek().actionRan()).isFalse();
}
@Test
public void testIncrementalAnalyzeSetsActionRanFalseForRemotelyCachedTests() {
TestSummary.Builder summaryBuilder = makeTestSummaryBuilder();
- assertFalse(summaryBuilder.peek().actionRan());
-
+ assertThat(summaryBuilder.peek().actionRan()).isFalse();
+
TestResultData testResultData = TestResultData.newBuilder().setRemotelyCached(true).build();
TestResult result = new TestResult(
mock(TestRunnerAction.class),
@@ -97,7 +96,7 @@ public class TestResultAnalyzerTest {
/*cached=*/false);
TestSummary.Builder newSummaryBuilder = underTest.incrementalAnalyze(summaryBuilder, result);
- assertFalse(newSummaryBuilder.peek().actionRan());
+ assertThat(newSummaryBuilder.peek().actionRan()).isFalse();
}
@Test
@@ -111,7 +110,7 @@ public class TestResultAnalyzerTest {
/*cached=*/true);
TestSummary.Builder newSummaryBuilder = underTest.incrementalAnalyze(summaryBuilder, result);
- assertTrue(newSummaryBuilder.peek().actionRan());
+ assertThat(newSummaryBuilder.peek().actionRan()).isTrue();
}
private TestSummary.Builder makeTestSummaryBuilder() {
diff --git a/src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java b/src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java
index 6619d1f3d5..7ea22b3d65 100644
--- a/src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/runtime/TestSummaryTest.java
@@ -14,10 +14,7 @@
package com.google.devtools.build.lib.runtime;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.mockito.AdditionalMatchers.find;
import static org.mockito.AdditionalMatchers.not;
import static org.mockito.Matchers.anyString;
@@ -193,36 +190,36 @@ public class TestSummaryTest {
// No need to copy if built twice in a row; no direct setters on the object.
TestSummary summary = basicBuilder.build();
TestSummary sameSummary = basicBuilder.build();
- assertSame(summary, sameSummary);
+ assertThat(sameSummary).isSameAs(summary);
basicBuilder.addTestTimes(ImmutableList.of(40L));
TestSummary summaryCopy = basicBuilder.build();
- assertEquals(summary.getTarget(), summaryCopy.getTarget());
- assertEquals(summary.getStatus(), summaryCopy.getStatus());
- assertEquals(summary.numCached(), summaryCopy.numCached());
- assertNotSame(summary, summaryCopy);
- assertEquals(0, summary.totalRuns());
- assertEquals(1, summaryCopy.totalRuns());
+ assertThat(summaryCopy.getTarget()).isEqualTo(summary.getTarget());
+ assertThat(summaryCopy.getStatus()).isEqualTo(summary.getStatus());
+ assertThat(summaryCopy.numCached()).isEqualTo(summary.numCached());
+ assertThat(summaryCopy).isNotSameAs(summary);
+ assertThat(summary.totalRuns()).isEqualTo(0);
+ assertThat(summaryCopy.totalRuns()).isEqualTo(1);
// Check that the builder can add a new warning to the copy,
// despite the immutability of the original.
basicBuilder.addTestTimes(ImmutableList.of(60L));
TestSummary fiftyCached = basicBuilder.setNumCached(50).build();
- assertEquals(summary.getStatus(), fiftyCached.getStatus());
- assertEquals(50, fiftyCached.numCached());
- assertEquals(2, fiftyCached.totalRuns());
+ assertThat(fiftyCached.getStatus()).isEqualTo(summary.getStatus());
+ assertThat(fiftyCached.numCached()).isEqualTo(50);
+ assertThat(fiftyCached.totalRuns()).isEqualTo(2);
TestSummary sixtyCached = basicBuilder.setNumCached(60).build();
- assertEquals(60, sixtyCached.numCached());
- assertEquals(50, fiftyCached.numCached());
+ assertThat(sixtyCached.numCached()).isEqualTo(60);
+ assertThat(fiftyCached.numCached()).isEqualTo(50);
TestSummary failedCacheTemplate = TestSummary.newBuilderFromExisting(fiftyCached)
.setStatus(BlazeTestStatus.FAILED)
.build();
- assertEquals(50, failedCacheTemplate.numCached());
- assertEquals(BlazeTestStatus.FAILED, failedCacheTemplate.getStatus());
+ assertThat(failedCacheTemplate.numCached()).isEqualTo(50);
+ assertThat(failedCacheTemplate.getStatus()).isEqualTo(BlazeTestStatus.FAILED);
}
@Test
@@ -367,7 +364,7 @@ public class TestSummaryTest {
TestSummary summaryFailed = createTestSummaryWithDetails(
BlazeTestStatus.FAILED, Arrays.asList(detailPassed, detailFailed));
- assertEquals(BlazeTestStatus.FAILED, summaryFailed.getStatus());
+ assertThat(summaryFailed.getStatus()).isEqualTo(BlazeTestStatus.FAILED);
AnsiTerminalPrinter printerPassed = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summaryPassed, printerPassed, true, true);
@@ -428,8 +425,8 @@ public class TestSummaryTest {
// This way we can make the test independent from the sort order of FAILEd
// and PASSED.
- assertTrue(summaryFailedCached.compareTo(summaryPassedNotCached) < 0);
- assertTrue(summaryPassedCached.compareTo(summaryFailedNotCached) < 0);
+ assertThat(summaryFailedCached.compareTo(summaryPassedNotCached)).isLessThan(0);
+ assertThat(summaryPassedCached.compareTo(summaryFailedNotCached)).isLessThan(0);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/sandbox/SandboxOptionsTest.java b/src/test/java/com/google/devtools/build/lib/sandbox/SandboxOptionsTest.java
index 2792372b02..7e0b058e1e 100644
--- a/src/test/java/com/google/devtools/build/lib/sandbox/SandboxOptionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/sandbox/SandboxOptionsTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.sandbox;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableMap;
@@ -72,10 +72,11 @@ public final class SandboxOptionsTest extends SandboxTestCase {
pathPair = new SandboxOptions.MountPairConverter().convert(input);
fail();
} catch (OptionsParsingException e) {
- assertEquals(
- "Input must be a single path to mount inside the sandbox or "
- + "a mounting pair in the form of 'source:target'",
- e.getMessage());
+ assertThat(e)
+ .hasMessageThat()
+ .isEqualTo(
+ "Input must be a single path to mount inside the sandbox or "
+ + "a mounting pair in the form of 'source:target'");
}
}
@@ -86,19 +87,19 @@ public final class SandboxOptionsTest extends SandboxTestCase {
pathPair = new SandboxOptions.MountPairConverter().convert(input);
fail();
} catch (OptionsParsingException e) {
- assertEquals(
- e.getMessage(),
- "Input "
- + input
- + " contains one or more empty paths. "
- + "Input must be a single path to mount inside the sandbox or "
- + "a mounting pair in the form of 'source:target'");
+ assertThat(
+ "Input "
+ + input
+ + " contains one or more empty paths. "
+ + "Input must be a single path to mount inside the sandbox or "
+ + "a mounting pair in the form of 'source:target'")
+ .isEqualTo(e.getMessage());
}
}
private static void assertMountPair(
ImmutableMap.Entry<String, String> pathPair, String source, String target) {
- assertEquals(pathPair.getKey(), source);
- assertEquals(pathPair.getValue(), target);
+ assertThat(source).isEqualTo(pathPair.getKey());
+ assertThat(target).isEqualTo(pathPair.getValue());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/shell/CommandLargeInputsTest.java b/src/test/java/com/google/devtools/build/lib/shell/CommandLargeInputsTest.java
index 54aef7afeb..f62e01b71d 100644
--- a/src/test/java/com/google/devtools/build/lib/shell/CommandLargeInputsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/shell/CommandLargeInputsTest.java
@@ -13,19 +13,18 @@
// limitations under the License.
package com.google.devtools.build.lib.shell;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests the command class with large inputs
@@ -62,9 +61,9 @@ public class CommandLargeInputsTest {
final Command command = new Command(new String[] {"cat"});
byte[] randomBytes = getRandomBytes();
final CommandResult result = command.execute(randomBytes);
- assertEquals(0, result.getTerminationStatus().getRawExitCode());
+ assertThat(result.getTerminationStatus().getRawExitCode()).isEqualTo(0);
TestUtil.assertArrayEquals(randomBytes, result.getStdout());
- assertEquals(0, result.getStderr().length);
+ assertThat(result.getStderr()).isEmpty();
}
@Test
@@ -75,9 +74,9 @@ public class CommandLargeInputsTest {
byte[] randomBytes = getRandomBytes();
final CommandResult result = command.execute(randomBytes,
Command.NO_OBSERVER, out, err);
- assertEquals(0, result.getTerminationStatus().getRawExitCode());
+ assertThat(result.getTerminationStatus().getRawExitCode()).isEqualTo(0);
TestUtil.assertArrayEquals(randomBytes, out.toByteArray());
- assertEquals(0, err.toByteArray().length);
+ assertThat(err.toByteArray()).isEmpty();
assertOutAndErrNotAvailable(result);
}
@@ -89,8 +88,8 @@ public class CommandLargeInputsTest {
byte[] randomBytes = getRandomBytes();
final CommandResult result = command.execute(randomBytes,
Command.NO_OBSERVER, out, err);
- assertEquals(0, result.getTerminationStatus().getRawExitCode());
- assertEquals(0, out.toByteArray().length);
+ assertThat(result.getTerminationStatus().getRawExitCode()).isEqualTo(0);
+ assertThat(out.toByteArray()).isEmpty();
TestUtil.assertArrayEquals(randomBytes, err.toByteArray());
assertOutAndErrNotAvailable(result);
}
@@ -106,8 +105,8 @@ public class CommandLargeInputsTest {
final CommandResult result = command.execute(in,
Command.NO_OBSERVER, out, err);
- assertEquals(0, result.getTerminationStatus().getRawExitCode());
- assertEquals(0, out.toByteArray().length);
+ assertThat(result.getTerminationStatus().getRawExitCode()).isEqualTo(0);
+ assertThat(out.toByteArray()).isEmpty();
TestUtil.assertArrayEquals(randomBytes, err.toByteArray());
assertOutAndErrNotAvailable(result);
}
@@ -126,8 +125,8 @@ public class CommandLargeInputsTest {
expectedOut.append("OUT").append(i).append("\n");
expectedErr.append("ERR").append(i).append("\n");
}
- assertEquals(expectedOut.toString(), out.toString("UTF-8"));
- assertEquals(expectedErr.toString(), err.toString("UTF-8"));
+ assertThat(out.toString("UTF-8")).isEqualTo(expectedOut.toString());
+ assertThat(err.toString("UTF-8")).isEqualTo(expectedErr.toString());
}
private void assertOutAndErrNotAvailable(final CommandResult result) {
@@ -146,8 +145,8 @@ public class CommandLargeInputsTest {
final Command command = new Command(new String[] {"cat"});
byte[] allByteValues = getAllByteValues();
final CommandResult result = command.execute(allByteValues);
- assertEquals(0, result.getTerminationStatus().getRawExitCode());
- assertEquals(0, result.getStderr().length);
+ assertThat(result.getTerminationStatus().getRawExitCode()).isEqualTo(0);
+ assertThat(result.getStderr()).isEmpty();
TestUtil.assertArrayEquals(allByteValues, result.getStdout());
}
diff --git a/src/test/java/com/google/devtools/build/lib/shell/CommandTest.java b/src/test/java/com/google/devtools/build/lib/shell/CommandTest.java
index 5908da1666..caa4b42cd1 100644
--- a/src/test/java/com/google/devtools/build/lib/shell/CommandTest.java
+++ b/src/test/java/com/google/devtools/build/lib/shell/CommandTest.java
@@ -14,21 +14,14 @@
package com.google.devtools.build.lib.shell;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.shell.TestUtil.assertArrayEquals;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.testutil.BlazeTestUtils;
import com.google.devtools.build.lib.testutil.TestConstants;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -39,6 +32,10 @@ import java.util.Collections;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Unit tests for {@link Command}. This test will only succeed on Linux,
@@ -95,7 +92,7 @@ public class CommandTest {
for (final String key : env.keySet()) {
assertThat(command.getEnvironmentVariables()).containsEntry(key, env.get(key));
}
- assertEquals(workingDir, command.getWorkingDirectory());
+ assertThat(command.getWorkingDirectory()).isEqualTo(workingDir);
}
// Platform-dependent tests ------------------------------------------------
@@ -104,8 +101,8 @@ public class CommandTest {
public void testSimpleCommand() throws Exception {
final Command command = new Command(new String[] {"ls"});
final CommandResult result = command.execute();
- assertTrue(result.getTerminationStatus().success());
- assertEquals(0, result.getStderr().length);
+ assertThat(result.getTerminationStatus().success()).isTrue();
+ assertThat(result.getStderr()).isEmpty();
assertThat(result.getStdout().length).isGreaterThan(0);
}
@@ -141,8 +138,8 @@ public class CommandTest {
"-e",
"print 'a'x100000" });
final CommandResult result = command.execute();
- assertTrue(result.getTerminationStatus().success());
- assertEquals(0, result.getStderr().length);
+ assertThat(result.getTerminationStatus().success()).isTrue();
+ assertThat(result.getStderr()).isEmpty();
assertThat(result.getStdout().length).isGreaterThan(0);
}
@@ -159,16 +156,16 @@ public class CommandTest {
public void testHugeOutput() throws Exception {
final Command command = new Command(new String[] {"perl", "-e", "print 'a'x100000"});
final CommandResult result = command.execute();
- assertTrue(result.getTerminationStatus().success());
- assertEquals(0, result.getStderr().length);
- assertEquals(100000, result.getStdout().length);
+ assertThat(result.getTerminationStatus().success()).isTrue();
+ assertThat(result.getStderr()).isEmpty();
+ assertThat(result.getStdout()).hasLength(100000);
}
@Test
public void testIgnoreOutput() throws Exception {
final Command command = new Command(new String[] {"perl", "-e", "print 'a'x100000"});
final CommandResult result = command.execute(Command.NO_INPUT, null, true);
- assertTrue(result.getTerminationStatus().success());
+ assertThat(result.getTerminationStatus().success()).isTrue();
try {
result.getStdout();
fail("Should have thrown IllegalStateException");
@@ -191,7 +188,7 @@ public class CommandTest {
ByteArrayOutputStream err = new ByteArrayOutputStream();
CommandResult result = command.execute(emptyInput,
Command.NO_OBSERVER, out, err);
- assertTrue(result.getTerminationStatus().success());
+ assertThat(result.getTerminationStatus().success()).isTrue();
assertThat(out.toString("UTF-8")).isEmpty();
assertThat(err.toString("UTF-8")).isEmpty();
}
@@ -200,7 +197,7 @@ public class CommandTest {
public void testNoInputForCat() throws Exception {
final Command command = new Command(new String[]{"/bin/cat"});
CommandResult result = command.execute();
- assertTrue(result.getTerminationStatus().success());
+ assertThat(result.getTerminationStatus().success()).isTrue();
assertThat(new String(result.getStdout(), "UTF-8")).isEmpty();
assertThat(new String(result.getStderr(), "UTF-8")).isEmpty();
}
@@ -212,8 +209,8 @@ public class CommandTest {
ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
ByteArrayOutputStream stdErr = new ByteArrayOutputStream();
command.execute(Command.NO_INPUT, Command.NO_OBSERVER, stdOut, stdErr);
- assertEquals(helloWorld + "\n", stdOut.toString("UTF-8"));
- assertEquals(0, stdErr.toByteArray().length);
+ assertThat(stdOut.toString("UTF-8")).isEqualTo(helloWorld + "\n");
+ assertThat(stdErr.toByteArray()).isEmpty();
}
@Test
@@ -225,8 +222,8 @@ public class CommandTest {
FutureCommandResult result =
command.executeAsynchronously(Command.NO_INPUT);
result.get();
- assertTrue(tempFile.exists());
- assertTrue(result.isDone());
+ assertThat(tempFile.exists()).isTrue();
+ assertThat(result.isDone()).isTrue();
tempFile.delete();
}
@@ -236,14 +233,14 @@ public class CommandTest {
final SimpleKillableObserver observer = new SimpleKillableObserver();
FutureCommandResult result =
command.executeAsynchronously(Command.NO_INPUT, observer);
- assertFalse(result.isDone());
+ assertThat(result.isDone()).isFalse();
observer.kill();
try {
result.get();
} catch (AbnormalTerminationException e) {
// Expects, but does not insist on termination with a signal.
}
- assertTrue(result.isDone());
+ assertThat(result.isDone()).isTrue();
}
@Test
@@ -260,8 +257,8 @@ public class CommandTest {
stdOut,
stdErr);
result.get(); // Make sure the process actually finished
- assertEquals(helloWorld + "\n", stdOut.toString("UTF-8"));
- assertEquals(0, stdErr.toByteArray().length);
+ assertThat(stdOut.toString("UTF-8")).isEqualTo(helloWorld + "\n");
+ assertThat(stdErr.toByteArray()).isEmpty();
}
@Test
@@ -336,9 +333,9 @@ public class CommandTest {
String args[] = { "/bin/sh", "-c", "exit 0" };
CommandResult result = new Command(args).execute();
TerminationStatus status = result.getTerminationStatus();
- assertTrue(status.success());
- assertTrue(status.exited());
- assertEquals(0, status.getExitCode());
+ assertThat(status.success()).isTrue();
+ assertThat(status.exited()).isTrue();
+ assertThat(status.getExitCode()).isEqualTo(0);
}
// Every exit value in range [1-255] is reported as such (except [129-191],
@@ -352,10 +349,10 @@ public class CommandTest {
assertThat(e).hasMessage("Process exited with status " + exit);
checkCommandElements(e, "/bin/sh", "-c", "exit " + exit);
TerminationStatus status = e.getResult().getTerminationStatus();
- assertFalse(status.success());
- assertTrue(status.exited());
- assertEquals(exit, status.getExitCode());
- assertEquals("Exit " + exit , status.toShortString());
+ assertThat(status.success()).isFalse();
+ assertThat(status.exited()).isTrue();
+ assertThat(status.getExitCode()).isEqualTo(exit);
+ assertThat(status.toShortString()).isEqualTo("Exit " + exit);
}
}
@@ -370,10 +367,10 @@ public class CommandTest {
assertThat(e).hasMessage("Process exited with status " + expected);
checkCommandElements(e, "/bin/bash", "-c", "exit " + exit);
TerminationStatus status = e.getResult().getTerminationStatus();
- assertFalse(status.success());
- assertTrue(status.exited());
- assertEquals(expected, status.getExitCode());
- assertEquals("Exit " + expected, status.toShortString());
+ assertThat(status.success()).isFalse();
+ assertThat(status.exited()).isTrue();
+ assertThat(status.getExitCode()).isEqualTo(expected);
+ assertThat(status.toShortString()).isEqualTo("Exit " + expected);
}
}
}
@@ -395,9 +392,9 @@ public class CommandTest {
assertThat(e).hasMessage("Process terminated by signal " + signal);
checkCommandElements(e, killmyself, "" + signal);
TerminationStatus status = e.getResult().getTerminationStatus();
- assertFalse(status.success());
- assertFalse(status.exited());
- assertEquals(signal, status.getTerminatingSignal());
+ assertThat(status.success()).isFalse();
+ assertThat(status.exited()).isFalse();
+ assertThat(status.getTerminatingSignal()).isEqualTo(signal);
switch (signal) {
case 1: assertEquals("Hangup", status.toShortString()); break;
@@ -464,7 +461,7 @@ public class CommandTest {
CommandResult result = command.execute(in, Command.NO_OBSERVER, out, out);
TerminationStatus status = result.getTerminationStatus();
- assertTrue(status.success());
+ assertThat(status.success()).isTrue();
}
@Test
@@ -489,14 +486,14 @@ public class CommandTest {
}
};
command.execute(Command.NO_INPUT, Command.NO_OBSERVER, out, System.err);
- assertFalse(flushed[0]);
- assertFalse(flushed[1]); // 'F'
- assertFalse(flushed[2]); // 'o'
- assertTrue(flushed[3]); // 'o' <- expect flush here.
- assertFalse(flushed[4]); // 'B'
- assertFalse(flushed[5]); // 'a'
- assertFalse(flushed[6]); // 'r'
- assertTrue(flushed[7]); // '\n'
+ assertThat(flushed[0]).isFalse();
+ assertThat(flushed[1]).isFalse(); // 'F'
+ assertThat(flushed[2]).isFalse(); // 'o'
+ assertThat(flushed[3]).isTrue(); // 'o' <- expect flush here.
+ assertThat(flushed[4]).isFalse(); // 'B'
+ assertThat(flushed[5]).isFalse(); // 'a'
+ assertThat(flushed[6]).isFalse(); // 'r'
+ assertThat(flushed[7]).isTrue(); // '\n'
}
// See also InterruptibleTest.
@@ -528,9 +525,9 @@ public class CommandTest {
commandThread.join();
final CommandResult result = resultContainer[0];
- assertTrue(result.getTerminationStatus().success());
- assertEquals(0, result.getStderr().length);
- assertEquals(0, result.getStdout().length);
+ assertThat(result.getTerminationStatus().success()).isTrue();
+ assertThat(result.getStderr()).isEmpty();
+ assertThat(result.getStdout()).isEmpty();
}
@Test
@@ -570,12 +567,13 @@ public class CommandTest {
TerminationStatus status = e.getResult().getTerminationStatus();
// Subprocess either gets a SIGPIPE trying to write to our output stream,
// or it exits with failure. Both are observed, nondetermistically.
- assertTrue(status.exited()
- ? status.getExitCode() == 1
- : status.getTerminatingSignal() == 13);
- assertTrue(e.getMessage(),
- e.getMessage().endsWith("also encountered an error while attempting "
- + "to retrieve output"));
+ assertThat(status.exited() ? status.getExitCode() == 1 : status.getTerminatingSignal() == 13)
+ .isTrue();
+ assertWithMessage(e.getMessage())
+ .that(
+ e.getMessage()
+ .endsWith("also encountered an error while attempting " + "to retrieve output"))
+ .isTrue();
}
}
@@ -622,8 +620,8 @@ public class CommandTest {
TimeoutKillableObserver observer = new TimeoutKillableObserver(LONG_TIME);
observer.startObserving(killable);
observer.stopObserving(killable);
- assertFalse(observer.hasTimedOut());
- assertFalse(killable.getIsKilled());
+ assertThat(observer.hasTimedOut()).isFalse();
+ assertThat(killable.getIsKilled()).isFalse();
}
@Test
@@ -633,8 +631,8 @@ public class CommandTest {
observer.startObserving(killable);
killable.sleepUntilKilled(SHORT_TIME);
observer.stopObserving(killable);
- assertFalse(observer.hasTimedOut());
- assertFalse(killable.getIsKilled());
+ assertThat(observer.hasTimedOut()).isFalse();
+ assertThat(killable.getIsKilled()).isFalse();
}
@Test
@@ -644,8 +642,8 @@ public class CommandTest {
observer.startObserving(killable);
killable.sleepUntilKilled(LONG_TIME);
observer.stopObserving(killable);
- assertTrue(observer.hasTimedOut());
- assertTrue(killable.getIsKilled());
+ assertThat(observer.hasTimedOut()).isTrue();
+ assertThat(killable.getIsKilled()).isTrue();
}
@Test
@@ -655,8 +653,8 @@ public class CommandTest {
observer.startObserving(killable);
killable.sleepUntilKilled(LONG_TIME);
observer.stopObserving(killable);
- assertTrue(observer.hasTimedOut());
- assertTrue(killable.getIsKilled());
+ assertThat(observer.hasTimedOut()).isTrue();
+ assertThat(killable.getIsKilled()).isTrue();
}
private static void checkCommandElements(CommandException e,
@@ -666,14 +664,14 @@ public class CommandTest {
private static void checkATE(final AbnormalTerminationException ate) {
final CommandResult result = ate.getResult();
- assertFalse(result.getTerminationStatus().success());
+ assertThat(result.getTerminationStatus().success()).isFalse();
}
private static void checkSuccess(final CommandResult result,
final String expectedOutput) {
- assertTrue(result.getTerminationStatus().success());
- assertEquals(0, result.getStderr().length);
- assertEquals(expectedOutput, new String(result.getStdout()));
+ assertThat(result.getTerminationStatus().success()).isTrue();
+ assertThat(result.getStderr()).isEmpty();
+ assertThat(new String(result.getStdout())).isEqualTo(expectedOutput);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/shell/ConsumersTest.java b/src/test/java/com/google/devtools/build/lib/shell/ConsumersTest.java
index 38b19463a6..479a8b6e53 100644
--- a/src/test/java/com/google/devtools/build/lib/shell/ConsumersTest.java
+++ b/src/test/java/com/google/devtools/build/lib/shell/ConsumersTest.java
@@ -14,22 +14,20 @@
package com.google.devtools.build.lib.shell;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertSame;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.shell.Consumers.OutErrConsumers;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ConsumersTest {
@@ -91,7 +89,7 @@ public class ConsumersTest {
} catch (IOException e) {
fail();
} catch (OutOfMemoryError e) {
- assertSame("OutOfMemoryError is not masked", error, e);
+ assertWithMessage("OutOfMemoryError is not masked").that(e).isSameAs(error);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/shell/FutureConsumptionTest.java b/src/test/java/com/google/devtools/build/lib/shell/FutureConsumptionTest.java
index d03f193f21..60a16e36b5 100644
--- a/src/test/java/com/google/devtools/build/lib/shell/FutureConsumptionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/shell/FutureConsumptionTest.java
@@ -13,21 +13,19 @@
// limitations under the License.
package com.google.devtools.build.lib.shell;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.shell.Consumers.OutErrConsumers;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests that InterruptedExceptions can't derail FutureConsumption
@@ -96,6 +94,6 @@ public class FutureConsumptionTest {
// In addition to asserting that we were interrupted, this clears the interrupt bit of the
// current thread, since Junit doesn't do it for us. This avoids the next test to run starting
// in an interrupted state.
- assertTrue(Thread.interrupted());
+ assertThat(Thread.interrupted()).isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/shell/InterruptibleTest.java b/src/test/java/com/google/devtools/build/lib/shell/InterruptibleTest.java
index 6ef9915843..006f89113d 100644
--- a/src/test/java/com/google/devtools/build/lib/shell/InterruptibleTest.java
+++ b/src/test/java/com/google/devtools/build/lib/shell/InterruptibleTest.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.shell;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import org.junit.After;
import org.junit.Before;
@@ -56,7 +55,7 @@ public class InterruptibleTest {
@Before
public final void startInterrupter() throws Exception {
Thread.interrupted(); // side effect: clear interrupted status
- assertFalse("Unexpected interruption!", mainThread.isInterrupted());
+ assertWithMessage("Unexpected interruption!").that(mainThread.isInterrupted()).isFalse();
// We interrupt after 1 sec, so this gives us plenty of time for the library to notice the
// subprocess exit.
@@ -81,11 +80,11 @@ public class InterruptibleTest {
command.execute();
// The interrupter thread should have exited about 1000ms ago.
- assertFalse("Interrupter thread is still alive!",
- interrupter.isAlive());
+ assertWithMessage("Interrupter thread is still alive!").that(interrupter.isAlive()).isFalse();
// The interrupter thread should have set the main thread's interrupt flag.
- assertTrue("Main thread was not interrupted during command execution!",
- mainThread.isInterrupted());
+ assertWithMessage("Main thread was not interrupted during command execution!")
+ .that(mainThread.isInterrupted())
+ .isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/shell/ShellUtilsTest.java b/src/test/java/com/google/devtools/build/lib/shell/ShellUtilsTest.java
index 36d6086c82..22079fb173 100644
--- a/src/test/java/com/google/devtools/build/lib/shell/ShellUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/shell/ShellUtilsTest.java
@@ -17,47 +17,41 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.shell.ShellUtils.prettyPrintArgv;
import static com.google.devtools.build.lib.shell.ShellUtils.shellEscape;
import static com.google.devtools.build.lib.shell.ShellUtils.tokenize;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.common.collect.Lists;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
-/**
- * Tests for ShellUtils.
- */
+/** Tests for ShellUtils. */
@RunWith(JUnit4.class)
public class ShellUtilsTest {
@Test
public void testShellEscape() throws Exception {
- assertEquals("''", shellEscape(""));
- assertEquals("foo", shellEscape("foo"));
- assertEquals("'foo bar'", shellEscape("foo bar"));
- assertEquals("''\\''foo'\\'''", shellEscape("'foo'"));
- assertEquals("'\\'\\''foo\\'\\'''", shellEscape("\\'foo\\'"));
- assertEquals("'${filename%.c}.o'", shellEscape("${filename%.c}.o"));
- assertEquals("'<html!>'", shellEscape("<html!>"));
+ assertThat(shellEscape("")).isEqualTo("''");
+ assertThat(shellEscape("foo")).isEqualTo("foo");
+ assertThat(shellEscape("foo bar")).isEqualTo("'foo bar'");
+ assertThat(shellEscape("'foo'")).isEqualTo("''\\''foo'\\'''");
+ assertThat(shellEscape("\\'foo\\'")).isEqualTo("'\\'\\''foo\\'\\'''");
+ assertThat(shellEscape("${filename%.c}.o")).isEqualTo("'${filename%.c}.o'");
+ assertThat(shellEscape("<html!>")).isEqualTo("'<html!>'");
}
@Test
public void testPrettyPrintArgv() throws Exception {
- assertEquals("echo '$US' 100",
- prettyPrintArgv(Arrays.asList("echo", "$US", "100")));
+ assertThat(prettyPrintArgv(Arrays.asList("echo", "$US", "100"))).isEqualTo("echo '$US' 100");
}
private void assertTokenize(String copts, String... expectedTokens)
throws Exception {
List<String> actualTokens = new ArrayList<>();
tokenize(actualTokens, copts);
- assertEquals(Arrays.asList(expectedTokens), actualTokens);
+ assertThat(actualTokens).isEqualTo(Arrays.asList(expectedTokens));
}
@Test
@@ -167,7 +161,7 @@ public class ShellUtilsTest {
words.add(stdout.substring(0, index));
stdout = stdout.substring(index + 1);
}
- assertEquals(in, words);
+ assertThat(words).isEqualTo(in);
// Assert that tokenize is dual to pretty-print:
List<String> out = new ArrayList<>();
@@ -178,7 +172,7 @@ public class ShellUtilsTest {
System.err.println(in);
}
}
- assertEquals(in, out);
+ assertThat(out).isEqualTo(in);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/shell/ToTruncatedStringTest.java b/src/test/java/com/google/devtools/build/lib/shell/ToTruncatedStringTest.java
index a18819b679..ef19627816 100644
--- a/src/test/java/com/google/devtools/build/lib/shell/ToTruncatedStringTest.java
+++ b/src/test/java/com/google/devtools/build/lib/shell/ToTruncatedStringTest.java
@@ -14,19 +14,15 @@
package com.google.devtools.build.lib.shell;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Tests {@link LogUtil#toTruncatedString}.
- */
+/** Tests {@link LogUtil#toTruncatedString}. */
/*
* Note: The toTruncatedString method uses the platform encoding intentionally,
* so the unittest does to. Check out the comment in the implementation in
@@ -63,14 +59,13 @@ public class ToTruncatedStringTest {
"want to produce a useful log. A log is useful if it contains " +
"the interesting information (like what the c[... truncated. " +
"original size was 261 bytes.]";
- assertEquals(expectedOutput,
- LogUtil.toTruncatedString(sampleInput.getBytes()));
+ assertThat(LogUtil.toTruncatedString(sampleInput.getBytes())).isEqualTo(expectedOutput);
}
@Test
public void testTruncatingHelloWorldYieldsHelloWorld() {
String helloWorld = "Hello, world.";
- assertEquals(helloWorld, LogUtil.toTruncatedString(helloWorld.getBytes()));
+ assertThat(LogUtil.toTruncatedString(helloWorld.getBytes())).isEqualTo(helloWorld);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ASTFileLookupFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ASTFileLookupFunctionTest.java
index 36d2559b23..68437dbdb3 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ASTFileLookupFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ASTFileLookupFunctionTest.java
@@ -15,9 +15,6 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
@@ -81,8 +78,8 @@ public class ASTFileLookupFunctionTest extends BuildViewTestCase {
EvaluationResult<PackageValue> result =
SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter);
- assertFalse(result.hasError());
- assertFalse(result.get(skyKey).getPackage().containsErrors());
+ assertThat(result.hasError()).isFalse();
+ assertThat(result.get(skyKey).getPackage().containsErrors()).isFalse();
}
@Test
@@ -98,12 +95,12 @@ public class ASTFileLookupFunctionTest extends BuildViewTestCase {
EvaluationResult<PackageValue> result =
SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
Throwable e = errorInfo.getException();
- assertEquals(skyKey, errorInfo.getRootCauseOfException());
+ assertThat(errorInfo.getRootCauseOfException()).isEqualTo(skyKey);
assertThat(e).isInstanceOf(NoSuchPackageException.class);
- assertThat(e.getMessage()).contains("bork");
+ assertThat(e).hasMessageThat().contains("bork");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ActionDataTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ActionDataTest.java
index 7ef96779fd..68f423aa17 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ActionDataTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ActionDataTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
-import static org.junit.Assert.assertSame;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
@@ -83,13 +83,13 @@ public class ActionDataTest extends TimestampBuilderTestCase {
.buildArtifacts(
reporter, outputs, null, null, null, null, executor, null, /*explain=*/ false, null,
null);
- assertSame(executor, action.executor);
+ assertThat(action.executor).isSameAs(executor);
executor = new DummyExecutor(scratch.dir("/"));
amnesiacBuilder()
.buildArtifacts(
reporter, outputs, null, null, null, null, executor, null, /*explain=*/ false, null,
null);
- assertSame(executor, action.executor);
+ assertThat(action.executor).isSameAs(executor);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ActionExecutionInactivityWatchdogTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ActionExecutionInactivityWatchdogTest.java
index e6e912d7a2..ee6f419940 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ActionExecutionInactivityWatchdogTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ActionExecutionInactivityWatchdogTest.java
@@ -15,18 +15,15 @@ package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
-import static org.junit.Assert.assertEquals;
import com.google.devtools.build.lib.skyframe.ActionExecutionInactivityWatchdog.InactivityMonitor;
import com.google.devtools.build.lib.skyframe.ActionExecutionInactivityWatchdog.InactivityReporter;
-
+import java.util.ArrayList;
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.ArrayList;
-import java.util.List;
-
/** Tests for ActionExecutionInactivityWatchdog. */
@RunWith(JUnit4.class)
public class ActionExecutionInactivityWatchdogTest {
@@ -144,7 +141,7 @@ public class ActionExecutionInactivityWatchdogTest {
watchdog.stop();
}
- assertEquals(shouldReport, didReportInactivity[0]);
+ assertThat(didReportInactivity[0]).isEqualTo(shouldReport);
assertThat(sleepsAndWaits)
.containsExactly(
"wait:5",
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ArtifactFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ArtifactFunctionTest.java
index 21afd0a256..26d7565320 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ArtifactFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ArtifactFunctionTest.java
@@ -15,11 +15,7 @@ package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.skyframe.FileArtifactValue.create;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import com.google.common.base.Predicate;
@@ -201,7 +197,7 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
create(createDerivedArtifact("no-read"));
fail();
} catch (IOException e) {
- assertSame(exception, e);
+ assertThat(e).isSameAs(exception);
}
}
@@ -226,7 +222,7 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
evaluateArtifactValue(createSourceArtifact("bad"));
fail();
} catch (MissingInputFileException e) {
- assertThat(e.getMessage()).contains(exception.getMessage());
+ assertThat(e).hasMessageThat().contains(exception.getMessage());
}
}
@@ -236,7 +232,7 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
Path path = artifact.getPath();
writeFile(path, "hello"); //Non-empty file.
FileArtifactValue value = create(artifact);
- assertArrayEquals(path.getMD5Digest(), value.getDigest());
+ assertThat(value.getDigest()).isEqualTo(path.getMD5Digest());
try {
value.getModifiedTime();
fail("mtime for non-empty file should not be stored.");
@@ -252,8 +248,8 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
FileSystemUtils.createDirectoryAndParents(path);
path.setLastModifiedTime(1L);
FileArtifactValue value = create(artifact);
- assertNull(value.getDigest());
- assertEquals(1L, value.getModifiedTime());
+ assertThat(value.getDigest()).isNull();
+ assertThat(value.getModifiedTime()).isEqualTo(1L);
}
// Empty files are the same as normal files -- mtime is not stored.
@@ -264,8 +260,8 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
writeFile(path, "");
path.setLastModifiedTime(1L);
FileArtifactValue value = create(artifact);
- assertArrayEquals(path.getMD5Digest(), value.getDigest());
- assertEquals(0L, value.getSize());
+ assertThat(value.getDigest()).isEqualTo(path.getMD5Digest());
+ assertThat(value.getSize()).isEqualTo(0L);
}
@Test
@@ -326,10 +322,10 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
TreeFileArtifact treeFileArtifact2 = createFakeTreeFileArtifact(artifact, "child2", "hello2");
TreeArtifactValue value = (TreeArtifactValue) evaluateArtifactValue(artifact);
- assertNotNull(value.getChildValues().get(treeFileArtifact1));
- assertNotNull(value.getChildValues().get(treeFileArtifact2));
- assertNotNull(value.getChildValues().get(treeFileArtifact1).getDigest());
- assertNotNull(value.getChildValues().get(treeFileArtifact2).getDigest());
+ assertThat(value.getChildValues().get(treeFileArtifact1)).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact2)).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact1).getDigest()).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact2).getDigest()).isNotNull();
}
@Test
@@ -349,10 +345,10 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
ActionsTestUtil.createDummySpawnActionTemplate(artifact1, artifact2));
TreeArtifactValue value = (TreeArtifactValue) evaluateArtifactValue(artifact2);
- assertNotNull(value.getChildValues().get(treeFileArtifact1));
- assertNotNull(value.getChildValues().get(treeFileArtifact2));
- assertNotNull(value.getChildValues().get(treeFileArtifact1).getDigest());
- assertNotNull(value.getChildValues().get(treeFileArtifact2).getDigest());
+ assertThat(value.getChildValues().get(treeFileArtifact1)).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact2)).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact1).getDigest()).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact2).getDigest()).isNotNull();
}
@Test
@@ -377,10 +373,10 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
ActionsTestUtil.createDummySpawnActionTemplate(artifact2, artifact3));
TreeArtifactValue value = (TreeArtifactValue) evaluateArtifactValue(artifact3);
- assertNotNull(value.getChildValues().get(treeFileArtifact1));
- assertNotNull(value.getChildValues().get(treeFileArtifact2));
- assertNotNull(value.getChildValues().get(treeFileArtifact1).getDigest());
- assertNotNull(value.getChildValues().get(treeFileArtifact2).getDigest());
+ assertThat(value.getChildValues().get(treeFileArtifact1)).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact2)).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact1).getDigest()).isNotNull();
+ assertThat(value.getChildValues().get(treeFileArtifact2).getDigest()).isNotNull();
}
private void file(Path path, String contents) throws Exception {
@@ -438,12 +434,12 @@ public class ArtifactFunctionTest extends ArtifactFunctionTestCase {
private void assertValueMatches(FileStatus file, byte[] digest, FileArtifactValue value)
throws IOException {
- assertEquals(file.getSize(), value.getSize());
+ assertThat(value.getSize()).isEqualTo(file.getSize());
if (digest == null) {
- assertNull(value.getDigest());
- assertEquals(file.getLastModifiedTime(), value.getModifiedTime());
+ assertThat(value.getDigest()).isNull();
+ assertThat(value.getModifiedTime()).isEqualTo(file.getLastModifiedTime());
} else {
- assertArrayEquals(digest, value.getDigest());
+ assertThat(value.getDigest()).isEqualTo(digest);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ConfigurationsForTargetsWithDynamicConfigurationsTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ConfigurationsForTargetsWithDynamicConfigurationsTest.java
index 9612febb38..9ee1f9dc36 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ConfigurationsForTargetsWithDynamicConfigurationsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ConfigurationsForTargetsWithDynamicConfigurationsTest.java
@@ -330,7 +330,7 @@ public class ConfigurationsForTargetsWithDynamicConfigurationsTest
applier.split(newSplitTransition("disallowed second split"));
fail("expected failure: deps cannot apply more than one split transition each");
} catch (IllegalStateException e) {
- assertThat(e.getMessage()).contains("dependency edges may apply at most one split");
+ assertThat(e).hasMessageThat().contains("dependency edges may apply at most one split");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ContainingPackageLookupFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ContainingPackageLookupFunctionTest.java
index 1260439a7d..d65779f372 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ContainingPackageLookupFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ContainingPackageLookupFunctionTest.java
@@ -13,9 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@@ -111,25 +109,26 @@ public class ContainingPackageLookupFunctionTest extends FoundationTestCase {
@Test
public void testNoContainingPackage() throws Exception {
ContainingPackageLookupValue value = lookupContainingPackage("a/b");
- assertFalse(value.hasContainingPackage());
+ assertThat(value.hasContainingPackage()).isFalse();
}
@Test
public void testContainingPackageIsParent() throws Exception {
scratch.file("a/BUILD");
ContainingPackageLookupValue value = lookupContainingPackage("a/b");
- assertTrue(value.hasContainingPackage());
- assertEquals(PackageIdentifier.createInMainRepo("a"), value.getContainingPackageName());
- assertEquals(rootDirectory, value.getContainingPackageRoot());
+ assertThat(value.hasContainingPackage()).isTrue();
+ assertThat(value.getContainingPackageName()).isEqualTo(PackageIdentifier.createInMainRepo("a"));
+ assertThat(value.getContainingPackageRoot()).isEqualTo(rootDirectory);
}
@Test
public void testContainingPackageIsSelf() throws Exception {
scratch.file("a/b/BUILD");
ContainingPackageLookupValue value = lookupContainingPackage("a/b");
- assertTrue(value.hasContainingPackage());
- assertEquals(PackageIdentifier.createInMainRepo("a/b"), value.getContainingPackageName());
- assertEquals(rootDirectory, value.getContainingPackageRoot());
+ assertThat(value.hasContainingPackage()).isTrue();
+ assertThat(value.getContainingPackageName())
+ .isEqualTo(PackageIdentifier.createInMainRepo("a/b"));
+ assertThat(value.getContainingPackageRoot()).isEqualTo(rootDirectory);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/DiffAwarenessManagerTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/DiffAwarenessManagerTest.java
index 2a6f85eb05..16873d3f2a 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/DiffAwarenessManagerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/DiffAwarenessManagerTest.java
@@ -14,9 +14,7 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
@@ -64,11 +62,12 @@ public class DiffAwarenessManagerTest {
Path pathEntry = root.getRelative("pathEntry");
DiffAwarenessFactoryStub factory = new DiffAwarenessFactoryStub();
DiffAwarenessManager manager = new DiffAwarenessManager(ImmutableList.of(factory));
- assertEquals(
- "Expected EVERYTHING_MODIFIED since there are no factories",
- ModifiedFileSet.EVERYTHING_MODIFIED,
- manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY)
- .getModifiedFileSet());
+ assertWithMessage("Expected EVERYTHING_MODIFIED since there are no factories")
+ .that(
+ manager
+ .getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY)
+ .getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.EVERYTHING_MODIFIED);
events.assertNoWarningsOrErrors();
}
@@ -82,12 +81,18 @@ public class DiffAwarenessManagerTest {
factory.inject(pathEntry, diffAwareness1);
DiffAwarenessManager manager = new DiffAwarenessManager(ImmutableList.of(factory));
manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertFalse("diffAwareness1 shouldn't have been closed yet", diffAwareness1.closed());
+ assertWithMessage("diffAwareness1 shouldn't have been closed yet")
+ .that(diffAwareness1.closed())
+ .isFalse();
manager.reset();
- assertTrue("diffAwareness1 should have been closed by reset", diffAwareness1.closed());
+ assertWithMessage("diffAwareness1 should have been closed by reset")
+ .that(diffAwareness1.closed())
+ .isTrue();
factory.inject(pathEntry, diffAwareness2);
manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertFalse("diffAwareness2 shouldn't have been closed yet", diffAwareness2.closed());
+ assertWithMessage("diffAwareness2 shouldn't have been closed yet")
+ .that(diffAwareness2.closed())
+ .isFalse();
events.assertNoWarningsOrErrors();
}
@@ -104,25 +109,26 @@ public class DiffAwarenessManagerTest {
DiffAwarenessManager manager = new DiffAwarenessManager(ImmutableList.of(factory));
ProcessableModifiedFileSet firstProcessableDiff =
manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(
- "Expected EVERYTHING_MODIFIED on first call to getDiff",
- ModifiedFileSet.EVERYTHING_MODIFIED,
- firstProcessableDiff.getModifiedFileSet());
+ assertWithMessage("Expected EVERYTHING_MODIFIED on first call to getDiff")
+ .that(firstProcessableDiff.getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.EVERYTHING_MODIFIED);
firstProcessableDiff.markProcessed();
ProcessableModifiedFileSet processableDiff1 =
manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(diff1, processableDiff1.getModifiedFileSet());
+ assertThat(processableDiff1.getModifiedFileSet()).isEqualTo(diff1);
ProcessableModifiedFileSet processableDiff2 =
manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(ModifiedFileSet.union(diff1, diff2), processableDiff2.getModifiedFileSet());
+ assertThat(processableDiff2.getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.union(diff1, diff2));
processableDiff2.markProcessed();
ProcessableModifiedFileSet processableDiff3 =
manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(diff3, processableDiff3.getModifiedFileSet());
+ assertThat(processableDiff3.getModifiedFileSet()).isEqualTo(diff3);
events.assertNoWarningsOrErrors();
ProcessableModifiedFileSet processableDiff4 =
manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(ModifiedFileSet.EVERYTHING_MODIFIED, processableDiff4.getModifiedFileSet());
+ assertThat(processableDiff4.getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.EVERYTHING_MODIFIED);
events.assertContainsWarning("error");
}
@@ -148,50 +154,45 @@ public class DiffAwarenessManagerTest {
ProcessableModifiedFileSet processableDiff =
manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
events.assertNoWarningsOrErrors();
- assertEquals(
- "Expected EVERYTHING_MODIFIED on first call to getDiff for diffAwareness1",
- ModifiedFileSet.EVERYTHING_MODIFIED,
- processableDiff.getModifiedFileSet());
+ assertWithMessage("Expected EVERYTHING_MODIFIED on first call to getDiff for diffAwareness1")
+ .that(processableDiff.getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.EVERYTHING_MODIFIED);
processableDiff.markProcessed();
processableDiff = manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
events.assertContainsEventWithFrequency("error in getCurrentView", 1);
- assertEquals(
- "Expected EVERYTHING_MODIFIED because of broken getCurrentView",
- ModifiedFileSet.EVERYTHING_MODIFIED,
- processableDiff.getModifiedFileSet());
+ assertWithMessage("Expected EVERYTHING_MODIFIED because of broken getCurrentView")
+ .that(processableDiff.getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.EVERYTHING_MODIFIED);
processableDiff.markProcessed();
factory1.remove(pathEntry);
processableDiff = manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(
- "Expected EVERYTHING_MODIFIED on first call to getDiff for diffAwareness2",
- ModifiedFileSet.EVERYTHING_MODIFIED,
- processableDiff.getModifiedFileSet());
+ assertWithMessage("Expected EVERYTHING_MODIFIED on first call to getDiff for diffAwareness2")
+ .that(processableDiff.getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.EVERYTHING_MODIFIED);
processableDiff.markProcessed();
processableDiff = manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(diff2, processableDiff.getModifiedFileSet());
+ assertThat(processableDiff.getModifiedFileSet()).isEqualTo(diff2);
processableDiff.markProcessed();
processableDiff = manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
events.assertContainsEventWithFrequency("error in getDiff", 1);
- assertEquals(
- "Expected EVERYTHING_MODIFIED because of broken getDiff",
- ModifiedFileSet.EVERYTHING_MODIFIED,
- processableDiff.getModifiedFileSet());
+ assertWithMessage("Expected EVERYTHING_MODIFIED because of broken getDiff")
+ .that(processableDiff.getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.EVERYTHING_MODIFIED);
processableDiff.markProcessed();
factory2.remove(pathEntry);
processableDiff = manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(
- "Expected EVERYTHING_MODIFIED on first call to getDiff for diffAwareness3",
- ModifiedFileSet.EVERYTHING_MODIFIED,
- processableDiff.getModifiedFileSet());
+ assertWithMessage("Expected EVERYTHING_MODIFIED on first call to getDiff for diffAwareness3")
+ .that(processableDiff.getModifiedFileSet())
+ .isEqualTo(ModifiedFileSet.EVERYTHING_MODIFIED);
processableDiff.markProcessed();
processableDiff = manager.getDiff(events.reporter(), pathEntry, OptionsClassProvider.EMPTY);
- assertEquals(diff3, processableDiff.getModifiedFileSet());
+ assertThat(processableDiff.getModifiedFileSet()).isEqualTo(diff3);
processableDiff.markProcessed();
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/FileFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/FileFunctionTest.java
index 8be17f2064..43d0353a1a 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/FileFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/FileFunctionTest.java
@@ -14,14 +14,9 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.skyframe.SkyframeExecutor.DEFAULT_THREAD_COUNT;
import static com.google.devtools.build.skyframe.EvaluationResultSubjectFactory.assertThatEvaluationResult;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
@@ -187,7 +182,7 @@ public class FileFunctionTest {
EvaluationResult<FileValue> result =
driver.evaluate(
ImmutableList.of(key), false, DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
return result.get(key);
}
@@ -207,26 +202,26 @@ public class FileFunctionTest {
@Test
public void testIsDirectory() throws Exception {
- assertFalse(valueForPath(file("a")).isDirectory());
- assertFalse(valueForPath(path("nonexistent")).isDirectory());
- assertTrue(valueForPath(directory("dir")).isDirectory());
+ assertThat(valueForPath(file("a")).isDirectory()).isFalse();
+ assertThat(valueForPath(path("nonexistent")).isDirectory()).isFalse();
+ assertThat(valueForPath(directory("dir")).isDirectory()).isTrue();
- assertFalse(valueForPath(symlink("sa", "a")).isDirectory());
- assertFalse(valueForPath(symlink("smissing", "missing")).isDirectory());
- assertTrue(valueForPath(symlink("sdir", "dir")).isDirectory());
- assertTrue(valueForPath(symlink("ssdir", "sdir")).isDirectory());
+ assertThat(valueForPath(symlink("sa", "a")).isDirectory()).isFalse();
+ assertThat(valueForPath(symlink("smissing", "missing")).isDirectory()).isFalse();
+ assertThat(valueForPath(symlink("sdir", "dir")).isDirectory()).isTrue();
+ assertThat(valueForPath(symlink("ssdir", "sdir")).isDirectory()).isTrue();
}
@Test
public void testIsFile() throws Exception {
- assertTrue(valueForPath(file("a")).isFile());
- assertFalse(valueForPath(path("nonexistent")).isFile());
- assertFalse(valueForPath(directory("dir")).isFile());
+ assertThat(valueForPath(file("a")).isFile()).isTrue();
+ assertThat(valueForPath(path("nonexistent")).isFile()).isFalse();
+ assertThat(valueForPath(directory("dir")).isFile()).isFalse();
- assertTrue(valueForPath(symlink("sa", "a")).isFile());
- assertFalse(valueForPath(symlink("smissing", "missing")).isFile());
- assertFalse(valueForPath(symlink("sdir", "dir")).isFile());
- assertTrue(valueForPath(symlink("ssfile", "sa")).isFile());
+ assertThat(valueForPath(symlink("sa", "a")).isFile()).isTrue();
+ assertThat(valueForPath(symlink("smissing", "missing")).isFile()).isFalse();
+ assertThat(valueForPath(symlink("sdir", "dir")).isFile()).isFalse();
+ assertThat(valueForPath(symlink("ssfile", "sa")).isFile()).isTrue();
}
@Test
@@ -428,7 +423,7 @@ public class FileFunctionTest {
FileValue a = valueForPath(path("file"));
Path p = file("file");
FileValue b = valueForPath(p);
- assertFalse(a.equals(b));
+ assertThat(a.equals(b)).isFalse();
}
@Test
@@ -447,7 +442,7 @@ public class FileFunctionTest {
p.setLastModifiedTime(1L);
assertThat(valueForPath(p)).isNotEqualTo(a);
p.setLastModifiedTime(0L);
- assertEquals(a, valueForPath(p));
+ assertThat(valueForPath(p)).isEqualTo(a);
FileSystemUtils.writeContentAsLatin1(p, "content");
// Same digest, but now non-empty.
assertThat(valueForPath(p)).isNotEqualTo(a);
@@ -460,7 +455,7 @@ public class FileFunctionTest {
p.setLastModifiedTime(0L);
FileValue value = valueForPath(p);
- assertTrue(value.exists());
+ assertThat(value.exists()).isTrue();
assertThat(value.getDigest()).isNull();
p.setLastModifiedTime(10L);
@@ -498,7 +493,7 @@ public class FileFunctionTest {
FileValue a = valueForPath(p);
p.setLastModifiedTime(42);
FileValue b = valueForPath(p);
- assertFalse(a.equals(b));
+ assertThat(a.equals(b)).isFalse();
}
@Test
@@ -508,7 +503,7 @@ public class FileFunctionTest {
FileValue a = valueForPath(p);
FileSystemUtils.writeContentAsLatin1(p, "goop");
FileValue b = valueForPath(p);
- assertFalse(a.equals(b));
+ assertThat(a.equals(b)).isFalse();
}
@Test
@@ -529,7 +524,7 @@ public class FileFunctionTest {
FileValue a = valueForPath(p);
p.delete();
FileValue b = valueForPath(p);
- assertFalse(a.equals(b));
+ assertThat(a.equals(b)).isFalse();
}
@Test
@@ -542,9 +537,9 @@ public class FileFunctionTest {
p.delete();
FileSystemUtils.createDirectoryAndParents(pkgRoot.getRelative("file"));
FileValue c = valueForPath(p);
- assertFalse(a.equals(b));
- assertFalse(b.equals(c));
- assertFalse(a.equals(c));
+ assertThat(a.equals(b)).isFalse();
+ assertThat(b.equals(c)).isFalse();
+ assertThat(a.equals(c)).isFalse();
}
@Test
@@ -646,7 +641,7 @@ public class FileFunctionTest {
fail(String.format("Evaluation error for %s: %s", key, result.getError()));
}
FileValue oldValue = (FileValue) result.get(key);
- assertTrue(oldValue.exists());
+ assertThat(oldValue.exists()).isTrue();
file.delete();
differencer.invalidate(ImmutableList.of(fileStateSkyKey("/outsideroot")));
@@ -657,8 +652,8 @@ public class FileFunctionTest {
fail(String.format("Evaluation error for %s: %s", key, result.getError()));
}
FileValue newValue = (FileValue) result.get(key);
- assertNotSame(oldValue, newValue);
- assertFalse(newValue.exists());
+ assertThat(newValue).isNotSameAs(oldValue);
+ assertThat(newValue.exists()).isFalse();
}
@Test
@@ -675,7 +670,7 @@ public class FileFunctionTest {
assertThatEvaluationResult(result).hasNoError();
FileValue value = (FileValue) result.get(key);
assertThat(value).isNotNull();
- assertFalse(value.exists());
+ assertThat(value.exists()).isFalse();
}
@Test
@@ -694,7 +689,7 @@ public class FileFunctionTest {
assertThatEvaluationResult(result).hasNoError();
FileValue value = (FileValue) result.get(key);
assertThat(value).isNotNull();
- assertFalse(value.exists());
+ assertThat(value.exists()).isFalse();
}
@Test
@@ -713,7 +708,7 @@ public class FileFunctionTest {
assertThatEvaluationResult(result).hasNoError();
FileValue value = (FileValue) result.get(key);
assertThat(value).isNotNull();
- assertFalse(value.exists());
+ assertThat(value.exists()).isFalse();
}
@Test
@@ -731,7 +726,7 @@ public class FileFunctionTest {
assertThatEvaluationResult(result).hasNoError();
FileValue value = (FileValue) result.get(key);
assertThat(value).isNotNull();
- assertFalse(value.exists());
+ assertThat(value.exists()).isFalse();
}
@Test
@@ -749,7 +744,7 @@ public class FileFunctionTest {
assertThatEvaluationResult(result).hasNoError();
FileValue value = (FileValue) result.get(key);
assertThat(value).isNotNull();
- assertTrue(value.exists());
+ assertThat(value.exists()).isTrue();
assertThat(value.realRootedPath().getRelativePath().getPathString()).isEqualTo("insideroot");
}
@@ -775,7 +770,7 @@ public class FileFunctionTest {
Path file = file("file");
int fileSize = 20;
FileSystemUtils.writeContentAsLatin1(file, Strings.repeat("a", fileSize));
- assertEquals(fileSize, valueForPath(file).getSize());
+ assertThat(valueForPath(file).getSize()).isEqualTo(fileSize);
Path dir = directory("directory");
file(dir.getChild("child").getPathString());
try {
@@ -793,8 +788,8 @@ public class FileFunctionTest {
}
Path symlink = symlink("link", "/root/file");
// Symlink stores size of target, not link.
- assertEquals(fileSize, valueForPath(symlink).getSize());
- assertTrue(symlink.delete());
+ assertThat(valueForPath(symlink).getSize()).isEqualTo(fileSize);
+ assertThat(symlink.delete()).isTrue();
symlink = symlink("link", "/root/directory");
try {
valueForPath(symlink).getSize();
@@ -802,7 +797,7 @@ public class FileFunctionTest {
} catch (IllegalStateException e) {
// Expected.
}
- assertTrue(symlink.delete());
+ assertThat(symlink.delete()).isTrue();
symlink = symlink("link", "/root/noexist");
try {
valueForPath(symlink).getSize();
@@ -829,54 +824,54 @@ public class FileFunctionTest {
FileSystemUtils.writeContentAsLatin1(file, Strings.repeat("a", 20));
byte[] digest = file.getMD5Digest();
expectedCalls++;
- assertEquals(expectedCalls, digestCalls.get());
+ assertThat(digestCalls.get()).isEqualTo(expectedCalls);
FileValue value = valueForPath(file);
expectedCalls++;
- assertEquals(expectedCalls, digestCalls.get());
- assertArrayEquals(digest, value.getDigest());
+ assertThat(digestCalls.get()).isEqualTo(expectedCalls);
+ assertThat(value.getDigest()).isEqualTo(digest);
// Digest is cached -- no filesystem access.
- assertEquals(expectedCalls, digestCalls.get());
+ assertThat(digestCalls.get()).isEqualTo(expectedCalls);
fastDigest = false;
digestCalls.set(0);
value = valueForPath(file);
// No new digest calls.
- assertEquals(0, digestCalls.get());
- assertNull(value.getDigest());
- assertEquals(0, digestCalls.get());
+ assertThat(digestCalls.get()).isEqualTo(0);
+ assertThat(value.getDigest()).isNull();
+ assertThat(digestCalls.get()).isEqualTo(0);
fastDigest = true;
Path dir = directory("directory");
try {
- assertNull(valueForPath(dir).getDigest());
+ assertThat(valueForPath(dir).getDigest()).isNull();
fail();
} catch (IllegalStateException e) {
// Expected.
}
- assertEquals(0, digestCalls.get()); // No digest calls made for directory.
+ assertThat(digestCalls.get()).isEqualTo(0); // No digest calls made for directory.
Path nonexistent = fs.getPath("/root/noexist");
try {
- assertNull(valueForPath(nonexistent).getDigest());
+ assertThat(valueForPath(nonexistent).getDigest()).isNull();
fail();
} catch (IllegalStateException e) {
// Expected.
}
- assertEquals(0, digestCalls.get()); // No digest calls made for nonexistent file.
+ assertThat(digestCalls.get()).isEqualTo(0); // No digest calls made for nonexistent file.
Path symlink = symlink("link", "/root/file");
value = valueForPath(symlink);
- assertEquals(1, digestCalls.get());
+ assertThat(digestCalls.get()).isEqualTo(1);
// Symlink stores digest of target, not link.
- assertArrayEquals(digest, value.getDigest());
- assertEquals(1, digestCalls.get());
+ assertThat(value.getDigest()).isEqualTo(digest);
+ assertThat(digestCalls.get()).isEqualTo(1);
digestCalls.set(0);
- assertTrue(symlink.delete());
+ assertThat(symlink.delete()).isTrue();
symlink = symlink("link", "/root/directory");
// Symlink stores digest of target, not link, for directories too.
try {
- assertNull(valueForPath(symlink).getDigest());
+ assertThat(valueForPath(symlink).getDigest()).isNull();
fail();
} catch (IllegalStateException e) {
// Expected.
}
- assertEquals(0, digestCalls.get());
+ assertThat(digestCalls.get()).isEqualTo(0);
}
@Test
@@ -944,10 +939,11 @@ public class FileFunctionTest {
EvaluationResult<FileValue> result =
driver.evaluate(
ImmutableList.of(skyKey), false, DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
assertThat(errorInfo.getException()).isInstanceOf(InconsistentFilesystemException.class);
- assertThat(errorInfo.getException().getMessage())
+ assertThat(errorInfo.getException())
+ .hasMessageThat()
.contains("file /root/a/b exists but its parent path /root/a isn't an existing directory");
}
@@ -961,11 +957,11 @@ public class FileFunctionTest {
EvaluationResult<FileValue> result =
driver.evaluate(
ImmutableList.of(skyKey), false, DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
assertThat(errorInfo.getException()).isInstanceOf(InconsistentFilesystemException.class);
- assertThat(errorInfo.getException().getMessage()).contains("encountered error 'nope'");
- assertThat(errorInfo.getException().getMessage()).contains("/root/a is no longer a file");
+ assertThat(errorInfo.getException()).hasMessageThat().contains("encountered error 'nope'");
+ assertThat(errorInfo.getException()).hasMessageThat().contains("/root/a is no longer a file");
}
@Test
@@ -989,12 +985,14 @@ public class FileFunctionTest {
EvaluationResult<FileValue> result =
driver.evaluate(
ImmutableList.of(skyKey), false, DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
assertThat(errorInfo.getException()).isInstanceOf(InconsistentFilesystemException.class);
- assertThat(errorInfo.getException().getMessage())
+ assertThat(errorInfo.getException())
+ .hasMessageThat()
.contains("encountered error 'isReadable failed'");
- assertThat(errorInfo.getException().getMessage())
+ assertThat(errorInfo.getException())
+ .hasMessageThat()
.contains("/root/unreadable is no longer a file");
}
@@ -1058,7 +1056,7 @@ public class FileFunctionTest {
SequentialBuildDriver driver = makeDriver();
EvaluationResult<FileValue> result =
driver.evaluate(keys, /*keepGoing=*/ true, DEFAULT_THREAD_COUNT, eventHandler);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
for (SkyKey key : keys) {
ErrorInfo errorInfo = result.getError(key);
// FileFunction detects symlink cycles explicitly.
@@ -1128,10 +1126,10 @@ public class FileFunctionTest {
FileValue b2 = (FileValue) ois.readObject();
FileValue c2 = (FileValue) ois.readObject();
- assertEquals(a, a2);
- assertEquals(b, b2);
- assertEquals(c, c2);
- assertFalse(a2.equals(b2));
+ assertThat(a2).isEqualTo(a);
+ assertThat(b2).isEqualTo(b);
+ assertThat(c2).isEqualTo(c);
+ assertThat(a2.equals(b2)).isFalse();
} finally {
Path.setFileSystemForSerialization(oldFileSystem);
}
@@ -1228,14 +1226,14 @@ public class FileFunctionTest {
}
EvaluationResult<FileValue> result =
driver.evaluate(keys, /*keepGoing=*/ true, DEFAULT_THREAD_COUNT, eventHandler);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
for (SkyKey key : errorKeys) {
ErrorInfo errorInfo = result.getError(key);
// FileFunction detects infinite symlink expansion explicitly.
assertThat(errorInfo.getCycleInfo()).isEmpty();
FileSymlinkInfiniteExpansionException fsiee =
(FileSymlinkInfiniteExpansionException) errorInfo.getException();
- assertThat(fsiee.getMessage()).contains("Infinite symlink expansion");
+ assertThat(fsiee).hasMessageThat().contains("Infinite symlink expansion");
assertThat(fsiee.getChain()).containsExactlyElementsIn(expectedChain).inOrder();
}
// Check that the unique symlink expansion error was reported exactly once.
@@ -1269,8 +1267,8 @@ public class FileFunctionTest {
Path ancestor = directory("this/is/an/ancestor");
Path parent = ancestor.getChild("parent");
Path child = parent.getChild("child");
- assertFalse(valueForPath(parent).exists());
- assertFalse(valueForPath(child).exists());
+ assertThat(valueForPath(parent).exists()).isFalse();
+ assertThat(valueForPath(child).exists()).isFalse();
}
private void checkRealPath(String pathString) throws Exception {
@@ -1288,9 +1286,8 @@ public class FileFunctionTest {
fail(String.format("Evaluation error for %s: %s", key, result.getError()));
}
FileValue fileValue = (FileValue) result.get(key);
- assertEquals(
- pkgRoot.getRelative(expectedRealPathString).toString(),
- fileValue.realRootedPath().asPath().toString());
+ assertThat(fileValue.realRootedPath().asPath().toString())
+ .isEqualTo(pkgRoot.getRelative(expectedRealPathString).toString());
}
/**
@@ -1523,11 +1520,15 @@ public class FileFunctionTest {
}
SkyValue newValue = result.get(key);
- assertTrue(
- String.format(
- "Changing the contents of %s %s should%s change the value for file %s.",
- isFile ? "file" : "directory", changedPathString, changes ? "" : " not", pathString),
- changes != newValue.equals(oldValue));
+ assertWithMessage(
+ String.format(
+ "Changing the contents of %s %s should%s change the value for file %s.",
+ isFile ? "file" : "directory",
+ changedPathString,
+ changes ? "" : " not",
+ pathString))
+ .that(changes != newValue.equals(oldValue))
+ .isTrue();
// Restore the original file.
undoCallback.run();
@@ -1545,9 +1546,10 @@ public class FileFunctionTest {
result =
driver.evaluate(
ImmutableList.of(key), false, DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertFalse(
- "Did not expect error while evaluating " + pathString + ", got " + result.get(key),
- result.hasError());
+ assertWithMessage(
+ "Did not expect error while evaluating " + pathString + ", got " + result.get(key))
+ .that(result.hasError())
+ .isFalse();
return filesSeen(driver.getGraphForTesting());
}
@@ -1562,12 +1564,13 @@ public class FileFunctionTest {
result =
driver.evaluate(
ImmutableList.of(key), false, DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertTrue(
- "Expected error while evaluating " + pathString + ", got " + result.get(key),
- result.hasError());
- assertTrue(
- !Iterables.isEmpty(result.getError().getCycleInfo())
- || result.getError().getException() != null);
+ assertWithMessage("Expected error while evaluating " + pathString + ", got " + result.get(key))
+ .that(result.hasError())
+ .isTrue();
+ assertThat(
+ !Iterables.isEmpty(result.getError().getCycleInfo())
+ || result.getError().getException() != null)
+ .isTrue();
return filesSeen(driver.getGraphForTesting());
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/FilesetEntryFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/FilesetEntryFunctionTest.java
index 949f09b168..91b1a65144 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/FilesetEntryFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/FilesetEntryFunctionTest.java
@@ -352,7 +352,8 @@ public final class FilesetEntryFunctionTest extends FoundationTestCase {
SkyKey key = FilesetEntryValue.key(params);
EvaluationResult<SkyValue> result = eval(key);
assertThat(result.hasError()).isTrue();
- assertThat(result.getError(key).getException().getMessage())
+ assertThat(result.getError(key).getException())
+ .hasMessageThat()
.contains("'foo/dir' crosses package boundary into package rooted at foo/dir/subpkg");
break;
default:
@@ -438,7 +439,8 @@ public final class FilesetEntryFunctionTest extends FoundationTestCase {
SkyKey key = FilesetEntryValue.key(params);
EvaluationResult<SkyValue> result = eval(key);
assertThat(result.hasError()).isTrue();
- assertThat(result.getError(key).getException().getMessage())
+ assertThat(result.getError(key).getException())
+ .hasMessageThat()
.contains(
"'foo/dir_sym' crosses package boundary into package rooted at foo/dir_sym/subpkg");
break;
@@ -530,7 +532,8 @@ public final class FilesetEntryFunctionTest extends FoundationTestCase {
SkyKey key = FilesetEntryValue.key(params);
EvaluationResult<SkyValue> result = eval(key);
assertThat(result.hasError()).isTrue();
- assertThat(result.getError(key).getException().getMessage())
+ assertThat(result.getError(key).getException())
+ .hasMessageThat()
.contains("'foo' crosses package boundary into package rooted at foo/subpkg");
break;
default:
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/FilesystemValueCheckerTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/FilesystemValueCheckerTest.java
index 74e7c776e5..515096105b 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/FilesystemValueCheckerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/FilesystemValueCheckerTest.java
@@ -14,10 +14,8 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.actions.ActionInputHelper.treeFileArtifact;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -162,7 +160,7 @@ public class FilesystemValueCheckerTest {
false,
SkyframeExecutor.DEFAULT_THREAD_COUNT,
NullEventHandler.INSTANCE);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
assertEmptyDiff(getDirtyFilesystemKeys(evaluator, checker));
@@ -179,7 +177,7 @@ public class FilesystemValueCheckerTest {
false,
SkyframeExecutor.DEFAULT_THREAD_COUNT,
NullEventHandler.INSTANCE);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
assertEmptyDiff(getDirtyFilesystemKeys(evaluator, checker));
}
@@ -220,16 +218,16 @@ public class FilesystemValueCheckerTest {
EvaluationResult<FileValue> result =
driver.evaluate(
allKeys, false, SkyframeExecutor.DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
FileValue symlinkValue = result.get(symlinkKey);
FileValue fooValue = result.get(fooKey);
- assertTrue(symlinkValue.toString(), symlinkValue.isSymlink());
+ assertWithMessage(symlinkValue.toString()).that(symlinkValue.isSymlink()).isTrue();
// Digest is not always available, so use size as a proxy for contents.
- assertEquals(fooValue.getSize(), symlinkValue.getSize());
+ assertThat(symlinkValue.getSize()).isEqualTo(fooValue.getSize());
assertEmptyDiff(getDirtyFilesystemKeys(evaluator, checker));
// Before second build, move sym1 to point to sym2.
- assertTrue(sym1.delete());
+ assertThat(sym1.delete()).isTrue();
FileSystemUtils.ensureSymbolicLink(sym1, sym2);
assertDiffWithNewValues(getDirtyFilesystemKeys(evaluator, checker), sym1FileStateKey);
@@ -240,24 +238,24 @@ public class FilesystemValueCheckerTest {
false,
SkyframeExecutor.DEFAULT_THREAD_COUNT,
NullEventHandler.INSTANCE);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
assertDiffWithNewValues(getDirtyFilesystemKeys(evaluator, checker), sym1FileStateKey);
// Before third build, move sym1 back to original (so change pruning will prevent signaling of
// its parents, but change symlink for real.
- assertTrue(sym1.delete());
+ assertThat(sym1.delete()).isTrue();
FileSystemUtils.ensureSymbolicLink(sym1, path);
- assertTrue(symlink.delete());
+ assertThat(symlink.delete()).isTrue();
FileSystemUtils.writeContentAsLatin1(symlink, "new symlink contents");
assertDiffWithNewValues(getDirtyFilesystemKeys(evaluator, checker), symlinkFileStateKey);
differencer.invalidate(ImmutableList.of(symlinkFileStateKey));
result =
driver.evaluate(
allKeys, false, SkyframeExecutor.DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
symlinkValue = result.get(symlinkKey);
- assertFalse(symlinkValue.toString(), symlinkValue.isSymlink());
- assertEquals(fooValue, result.get(fooKey));
+ assertWithMessage(symlinkValue.toString()).that(symlinkValue.isSymlink()).isFalse();
+ assertThat(result.get(fooKey)).isEqualTo(fooValue);
assertThat(symlinkValue.getSize()).isNotEqualTo(fooValue.getSize());
assertEmptyDiff(getDirtyFilesystemKeys(evaluator, checker));
}
@@ -282,7 +280,7 @@ public class FilesystemValueCheckerTest {
EvaluationResult<SkyValue> result =
driver.evaluate(
skyKeys, false, SkyframeExecutor.DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
assertEmptyDiff(getDirtyFilesystemKeys(evaluator, checker));
@@ -296,7 +294,7 @@ public class FilesystemValueCheckerTest {
result =
driver.evaluate(
skyKeys, false, SkyframeExecutor.DEFAULT_THREAD_COUNT, NullEventHandler.INSTANCE);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
assertEmptyDiff(getDirtyFilesystemKeys(evaluator, checker));
}
@@ -315,7 +313,7 @@ public class FilesystemValueCheckerTest {
false,
SkyframeExecutor.DEFAULT_THREAD_COUNT,
NullEventHandler.INSTANCE);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
fs.readlinkThrowsIoException = false;
FilesystemValueChecker checker = new FilesystemValueChecker(null, null);
@@ -340,7 +338,7 @@ public class FilesystemValueCheckerTest {
false,
SkyframeExecutor.DEFAULT_THREAD_COUNT,
NullEventHandler.INSTANCE);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
FilesystemValueChecker checker = new FilesystemValueChecker(null, null);
Diff diff = getDirtyFilesystemKeys(evaluator, checker);
@@ -377,10 +375,11 @@ public class FilesystemValueCheckerTest {
new TestAction(
Runnables.doNothing(), ImmutableSet.<Artifact>of(), ImmutableSet.of(out2)),
forceDigests)));
- assertFalse(
- driver
- .evaluate(ImmutableList.<SkyKey>of(), false, 1, NullEventHandler.INSTANCE)
- .hasError());
+ assertThat(
+ driver
+ .evaluate(ImmutableList.<SkyKey>of(), false, 1, NullEventHandler.INSTANCE)
+ .hasError())
+ .isFalse();
assertThat(new FilesystemValueChecker(null, null).getDirtyActionValues(evaluator.getValues(),
batchStatter, ModifiedFileSet.EVERYTHING_MODIFIED)).isEmpty();
@@ -460,10 +459,11 @@ public class FilesystemValueCheckerTest {
actionKeyLast,
actionValueWithEmptyDirectory(last)));
- assertFalse(
- driver
- .evaluate(ImmutableList.<SkyKey>of(), false, 1, NullEventHandler.INSTANCE)
- .hasError());
+ assertThat(
+ driver
+ .evaluate(ImmutableList.<SkyKey>of(), false, 1, NullEventHandler.INSTANCE)
+ .hasError())
+ .isFalse();
assertThat(new FilesystemValueChecker(null, null).getDirtyActionValues(evaluator.getValues(),
batchStatter, ModifiedFileSet.EVERYTHING_MODIFIED)).isEmpty();
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/GlobFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/GlobFunctionTest.java
index ef865acbff..27086159d6 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/GlobFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/GlobFunctionTest.java
@@ -14,8 +14,6 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Functions;
@@ -333,21 +331,9 @@ public abstract class GlobFunctionTest {
private void assertGlobsEqual(String pattern1, String pattern2) throws Exception {
GlobValue value1 = runGlob(false, pattern1);
GlobValue value2 = runGlob(false, pattern2);
- assertEquals(
- "GlobValues "
- + value1.getMatches()
- + " and "
- + value2.getMatches()
- + " should be equal. "
- + "Patterns: "
- + pattern1
- + ","
- + pattern2,
- value1,
- value2);
- // Just to be paranoid:
- assertEquals(value1, value1);
- assertEquals(value2, value2);
+ new EqualsTester()
+ .addEqualityGroup(value1, value2)
+ .testEquals();
}
private GlobValue runGlob(boolean excludeDirs, String pattern) throws Exception {
@@ -457,7 +443,7 @@ public abstract class GlobFunctionTest {
@Test
public void testMatchesCallWithNoCache() {
- assertTrue(UnixGlob.matches("*a*b", "CaCb", null));
+ assertThat(UnixGlob.matches("*a*b", "CaCb", null)).isTrue();
}
@Test
@@ -585,10 +571,10 @@ public abstract class GlobFunctionTest {
false,
SkyframeExecutor.DEFAULT_THREAD_COUNT,
NullEventHandler.INSTANCE);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
assertThat(errorInfo.getException()).isInstanceOf(InconsistentFilesystemException.class);
- assertThat(errorInfo.getException().getMessage()).contains(expectedMessage);
+ assertThat(errorInfo.getException()).hasMessageThat().contains(expectedMessage);
}
@Test
@@ -612,10 +598,10 @@ public abstract class GlobFunctionTest {
false,
SkyframeExecutor.DEFAULT_THREAD_COUNT,
NullEventHandler.INSTANCE);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
assertThat(errorInfo.getException()).isInstanceOf(InconsistentFilesystemException.class);
- assertThat(errorInfo.getException().getMessage()).contains(expectedMessage);
+ assertThat(errorInfo.getException()).hasMessageThat().contains(expectedMessage);
}
@Test
@@ -685,10 +671,10 @@ public abstract class GlobFunctionTest {
false,
SkyframeExecutor.DEFAULT_THREAD_COUNT,
NullEventHandler.INSTANCE);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
assertThat(errorInfo.getException()).isInstanceOf(InconsistentFilesystemException.class);
- assertThat(errorInfo.getException().getMessage()).contains(expectedMessage);
+ assertThat(errorInfo.getException()).hasMessageThat().contains(expectedMessage);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java
index ebb609d54a..da738d6220 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java
@@ -15,9 +15,6 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Predicates;
@@ -102,7 +99,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
fail(result.getError(skyKey).getException().getMessage());
}
PackageValue value = result.get(skyKey);
- assertFalse(value.getPackage().containsErrors());
+ assertThat(value.getPackage().containsErrors()).isFalse();
return value;
}
@@ -171,7 +168,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
+ "an existing directory";
EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
String errorMessage = errorInfo.getException().getMessage();
assertThat(errorMessage).contains("Inconsistent filesystem operations");
@@ -207,7 +204,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
String expectedMessage = "/workspace/foo/bar/baz is no longer an existing directory";
EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
String errorMessage = errorInfo.getException().getMessage();
assertThat(errorMessage).contains("Inconsistent filesystem operations");
@@ -229,7 +226,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
String expectedMessage = "Encountered error 'Directory is not readable'";
EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
String errorMessage = errorInfo.getException().getMessage();
assertThat(errorMessage).contains("Inconsistent filesystem operations");
@@ -468,7 +465,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//test/skylark"));
EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
String expectedMsg = "error loading package 'test/skylark': "
+ "Extension file not found. Unable to load file '//test/skylark:bad_extension.bzl': "
@@ -493,7 +490,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//test/skylark"));
EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
assertThat(errorInfo.getException())
.hasMessage("error loading package 'test/skylark': Extension file not found. "
@@ -516,9 +513,9 @@ public class PackageFunctionTest extends BuildViewTestCase {
SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//test/skylark"));
EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skyKey);
- assertEquals(skyKey, errorInfo.getRootCauseOfException());
+ assertThat(errorInfo.getRootCauseOfException()).isEqualTo(skyKey);
assertThat(errorInfo.getException())
.hasMessage(
"error loading package 'test/skylark': Encountered error while reading extension "
@@ -535,7 +532,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
assertContainsEvent("nope");
}
@@ -571,8 +568,8 @@ public class PackageFunctionTest extends BuildViewTestCase {
EvaluationResult<PackageValue> result =
SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter);
- assertFalse(result.hasError());
- assertTrue(result.get(skyKey).getPackage().containsErrors());
+ assertThat(result.hasError()).isFalse();
+ assertThat(result.get(skyKey).getPackage().containsErrors()).isTrue();
}
// Regression test for the two ugly consequences of a bug where GlobFunction incorrectly matched
@@ -588,7 +585,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
PackageValue value = validPackage(skyKey);
- assertFalse(value.getPackage().containsErrors());
+ assertThat(value.getPackage().containsErrors()).isFalse();
assertThat(value.getPackage().getTarget("existing.txt").getName()).isEqualTo("existing.txt");
try {
value.getPackage().getTarget("dangling.txt");
@@ -604,7 +601,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), rootDirectory);
value = validPackage(skyKey);
- assertFalse(value.getPackage().containsErrors());
+ assertThat(value.getPackage().containsErrors()).isFalse();
assertThat(value.getPackage().getTarget("existing.txt").getName()).isEqualTo("existing.txt");
try {
value.getPackage().getTarget("dangling.txt");
@@ -620,7 +617,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
ModifiedFileSet.builder().modify(PathFragment.create("foo/nope")).build(), rootDirectory);
PackageValue newValue = validPackage(skyKey);
- assertFalse(newValue.getPackage().containsErrors());
+ assertThat(newValue.getPackage().containsErrors()).isFalse();
assertThat(newValue.getPackage().getTarget("existing.txt").getName()).isEqualTo("existing.txt");
// Another consequence of the bug is that change pruning would incorrectly cut off changes that
// caused a dangling symlink potentially matched by a glob to come into existence.
@@ -641,7 +638,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
PackageValue value = validPackage(skyKey);
- assertFalse(value.getPackage().containsErrors());
+ assertThat(value.getPackage().containsErrors()).isFalse();
assertThat(value.getPackage().getTarget("bar-matched").getName()).isEqualTo("bar-matched");
try {
value.getPackage().getTarget("-matched");
@@ -656,7 +653,7 @@ public class PackageFunctionTest extends BuildViewTestCase {
ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), rootDirectory);
value = validPackage(skyKey);
- assertFalse(value.getPackage().containsErrors());
+ assertThat(value.getPackage().containsErrors()).isFalse();
assertThat(value.getPackage().getTarget("bar-matched").getName()).isEqualTo("bar-matched");
try {
value.getPackage().getTarget("-matched");
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PackageLookupFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PackageLookupFunctionTest.java
index ff5b2bdeee..7e770ffe81 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PackageLookupFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PackageLookupFunctionTest.java
@@ -14,11 +14,8 @@
package com.google.devtools.build.lib.skyframe;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.skyframe.EvaluationResultSubjectFactory.assertThatEvaluationResult;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -174,18 +171,18 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
public void testNoBuildFile() throws Exception {
scratch.file("parentpackage/nobuildfile/foo.txt");
PackageLookupValue packageLookupValue = lookupPackage("parentpackage/nobuildfile");
- assertFalse(packageLookupValue.packageExists());
- assertEquals(ErrorReason.NO_BUILD_FILE, packageLookupValue.getErrorReason());
- assertNotNull(packageLookupValue.getErrorMsg());
+ assertThat(packageLookupValue.packageExists()).isFalse();
+ assertThat(packageLookupValue.getErrorReason()).isEqualTo(ErrorReason.NO_BUILD_FILE);
+ assertThat(packageLookupValue.getErrorMsg()).isNotNull();
}
@Test
public void testNoBuildFileAndNoParentPackage() throws Exception {
scratch.file("noparentpackage/foo.txt");
PackageLookupValue packageLookupValue = lookupPackage("noparentpackage");
- assertFalse(packageLookupValue.packageExists());
- assertEquals(ErrorReason.NO_BUILD_FILE, packageLookupValue.getErrorReason());
- assertNotNull(packageLookupValue.getErrorMsg());
+ assertThat(packageLookupValue.packageExists()).isFalse();
+ assertThat(packageLookupValue.getErrorReason()).isEqualTo(ErrorReason.NO_BUILD_FILE);
+ assertThat(packageLookupValue.getErrorMsg()).isNotNull();
}
@Test
@@ -194,9 +191,9 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
deletedPackages.set(ImmutableSet.of(
PackageIdentifier.createInMainRepo("parentpackage/deletedpackage")));
PackageLookupValue packageLookupValue = lookupPackage("parentpackage/deletedpackage");
- assertFalse(packageLookupValue.packageExists());
- assertEquals(ErrorReason.DELETED_PACKAGE, packageLookupValue.getErrorReason());
- assertNotNull(packageLookupValue.getErrorMsg());
+ assertThat(packageLookupValue.packageExists()).isFalse();
+ assertThat(packageLookupValue.getErrorReason()).isEqualTo(ErrorReason.DELETED_PACKAGE);
+ assertThat(packageLookupValue.getErrorMsg()).isNotNull();
}
@@ -211,9 +208,9 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
ImmutableSet<String> pkgs = ImmutableSet.of("blacklisted/subdir", "blacklisted");
for (String pkg : pkgs) {
PackageLookupValue packageLookupValue = lookupPackage(pkg);
- assertFalse(packageLookupValue.packageExists());
- assertEquals(ErrorReason.DELETED_PACKAGE, packageLookupValue.getErrorReason());
- assertNotNull(packageLookupValue.getErrorMsg());
+ assertThat(packageLookupValue.packageExists()).isFalse();
+ assertThat(packageLookupValue.getErrorReason()).isEqualTo(ErrorReason.DELETED_PACKAGE);
+ assertThat(packageLookupValue.getErrorMsg()).isNotNull();
}
scratch.overwriteFile("config/blacklisted.txt", "not_blacklisted");
@@ -223,7 +220,7 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
differencer.invalidate(ImmutableSet.of(FileStateValue.key(rootedBlacklist)));
for (String pkg : pkgs) {
PackageLookupValue packageLookupValue = lookupPackage(pkg);
- assertTrue(packageLookupValue.packageExists());
+ assertThat(packageLookupValue.packageExists()).isTrue();
}
}
@@ -231,38 +228,36 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
public void testInvalidPackageName() throws Exception {
scratch.file("parentpackage/invalidpackagename%42/BUILD");
PackageLookupValue packageLookupValue = lookupPackage("parentpackage/invalidpackagename%42");
- assertFalse(packageLookupValue.packageExists());
- assertEquals(ErrorReason.INVALID_PACKAGE_NAME,
- packageLookupValue.getErrorReason());
- assertNotNull(packageLookupValue.getErrorMsg());
+ assertThat(packageLookupValue.packageExists()).isFalse();
+ assertThat(packageLookupValue.getErrorReason()).isEqualTo(ErrorReason.INVALID_PACKAGE_NAME);
+ assertThat(packageLookupValue.getErrorMsg()).isNotNull();
}
@Test
public void testDirectoryNamedBuild() throws Exception {
scratch.dir("parentpackage/isdirectory/BUILD");
PackageLookupValue packageLookupValue = lookupPackage("parentpackage/isdirectory");
- assertFalse(packageLookupValue.packageExists());
- assertEquals(ErrorReason.NO_BUILD_FILE,
- packageLookupValue.getErrorReason());
- assertNotNull(packageLookupValue.getErrorMsg());
+ assertThat(packageLookupValue.packageExists()).isFalse();
+ assertThat(packageLookupValue.getErrorReason()).isEqualTo(ErrorReason.NO_BUILD_FILE);
+ assertThat(packageLookupValue.getErrorMsg()).isNotNull();
}
@Test
public void testEverythingIsGood_BUILD() throws Exception {
scratch.file("parentpackage/everythinggood/BUILD");
PackageLookupValue packageLookupValue = lookupPackage("parentpackage/everythinggood");
- assertTrue(packageLookupValue.packageExists());
- assertEquals(rootDirectory, packageLookupValue.getRoot());
- assertEquals(BuildFileName.BUILD, packageLookupValue.getBuildFileName());
+ assertThat(packageLookupValue.packageExists()).isTrue();
+ assertThat(packageLookupValue.getRoot()).isEqualTo(rootDirectory);
+ assertThat(packageLookupValue.getBuildFileName()).isEqualTo(BuildFileName.BUILD);
}
@Test
public void testEverythingIsGood_BUILD_bazel() throws Exception {
scratch.file("parentpackage/everythinggood/BUILD.bazel");
PackageLookupValue packageLookupValue = lookupPackage("parentpackage/everythinggood");
- assertTrue(packageLookupValue.packageExists());
- assertEquals(rootDirectory, packageLookupValue.getRoot());
- assertEquals(BuildFileName.BUILD_DOT_BAZEL, packageLookupValue.getBuildFileName());
+ assertThat(packageLookupValue.packageExists()).isTrue();
+ assertThat(packageLookupValue.getRoot()).isEqualTo(rootDirectory);
+ assertThat(packageLookupValue.getBuildFileName()).isEqualTo(BuildFileName.BUILD_DOT_BAZEL);
}
@Test
@@ -270,9 +265,9 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
scratch.file("parentpackage/everythinggood/BUILD");
scratch.file("parentpackage/everythinggood/BUILD.bazel");
PackageLookupValue packageLookupValue = lookupPackage("parentpackage/everythinggood");
- assertTrue(packageLookupValue.packageExists());
- assertEquals(rootDirectory, packageLookupValue.getRoot());
- assertEquals(BuildFileName.BUILD_DOT_BAZEL, packageLookupValue.getBuildFileName());
+ assertThat(packageLookupValue.packageExists()).isTrue();
+ assertThat(packageLookupValue.getRoot()).isEqualTo(rootDirectory);
+ assertThat(packageLookupValue.getBuildFileName()).isEqualTo(BuildFileName.BUILD_DOT_BAZEL);
}
@Test
@@ -282,18 +277,18 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
// BUILD file in the first package path should be preferred to BUILD.bazel in the second.
PackageLookupValue packageLookupValue = lookupPackage("foo");
- assertTrue(packageLookupValue.packageExists());
- assertEquals(emptyPackagePath, packageLookupValue.getRoot());
- assertEquals(BuildFileName.BUILD, packageLookupValue.getBuildFileName());
+ assertThat(packageLookupValue.packageExists()).isTrue();
+ assertThat(packageLookupValue.getRoot()).isEqualTo(emptyPackagePath);
+ assertThat(packageLookupValue.getBuildFileName()).isEqualTo(BuildFileName.BUILD);
}
@Test
public void testEmptyPackageName() throws Exception {
scratch.file("BUILD");
PackageLookupValue packageLookupValue = lookupPackage("");
- assertTrue(packageLookupValue.packageExists());
- assertEquals(rootDirectory, packageLookupValue.getRoot());
- assertEquals(BuildFileName.BUILD, packageLookupValue.getBuildFileName());
+ assertThat(packageLookupValue.packageExists()).isTrue();
+ assertThat(packageLookupValue.getRoot()).isEqualTo(rootDirectory);
+ assertThat(packageLookupValue.getBuildFileName()).isEqualTo(BuildFileName.BUILD);
}
@Test
@@ -301,8 +296,8 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
scratch.overwriteFile("WORKSPACE");
PackageLookupValue packageLookupValue = lookupPackage(
PackageIdentifier.createInMainRepo("external"));
- assertTrue(packageLookupValue.packageExists());
- assertEquals(rootDirectory, packageLookupValue.getRoot());
+ assertThat(packageLookupValue.packageExists()).isTrue();
+ assertThat(packageLookupValue.getRoot()).isEqualTo(rootDirectory);
}
@Test
@@ -340,11 +335,11 @@ public abstract class PackageLookupFunctionTest extends FoundationTestCase {
// First, use the correct label.
PackageLookupValue packageLookupValue =
lookupPackage(PackageIdentifier.create("@local", PathFragment.EMPTY_FRAGMENT));
- assertTrue(packageLookupValue.packageExists());
+ assertThat(packageLookupValue.packageExists()).isTrue();
// Then, use the incorrect label.
packageLookupValue = lookupPackage(PackageIdentifier.createInMainRepo("local/repo"));
- assertEquals(expectedPackageExists, packageLookupValue.packageExists());
+ assertThat(packageLookupValue.packageExists()).isEqualTo(expectedPackageExists);
}
/**
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PackageProgressReceiverTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PackageProgressReceiverTest.java
index df35718a42..7a732129f3 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PackageProgressReceiverTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PackageProgressReceiverTest.java
@@ -13,12 +13,10 @@
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -38,9 +36,9 @@ public class PackageProgressReceiverTest {
progress.startReadPackage(id);
String activity = progress.progressState().getSecond();
- assertTrue(
- "Unfinished package '" + id + "' should be visible in activity: " + activity,
- activity.contains(id.toString()));
+ assertWithMessage("Unfinished package '" + id + "' should be visible in activity: " + activity)
+ .that(activity.contains(id.toString()))
+ .isTrue();
}
@Test
@@ -54,11 +52,13 @@ public class PackageProgressReceiverTest {
String state = progress.progressState().getFirst();
String activity = progress.progressState().getSecond();
- assertFalse(
- "Finished package '" + id + "' should not be visible in activity: " + activity,
- activity.contains(id.toString()));
- assertTrue(
- "Number of completed packages should be visible in state", state.contains("1 package"));
+ assertWithMessage(
+ "Finished package '" + id + "' should not be visible in activity: " + activity)
+ .that(activity.contains(id.toString()))
+ .isFalse();
+ assertWithMessage("Number of completed packages should be visible in state")
+ .that(state.contains("1 package"))
+ .isTrue();
}
@Test
@@ -71,7 +71,7 @@ public class PackageProgressReceiverTest {
progress.startReadPackage(id);
progress.doneReadPackage(id);
progress.reset();
- assertEquals(defaultState, progress.progressState().getFirst());
- assertEquals(defaultActivity, progress.progressState().getSecond());
+ assertThat(progress.progressState().getFirst()).isEqualTo(defaultState);
+ assertThat(progress.progressState().getSecond()).isEqualTo(defaultActivity);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ParallelBuilderTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ParallelBuilderTest.java
index 97446fffbb..fe8c4037f3 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ParallelBuilderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ParallelBuilderTest.java
@@ -15,8 +15,7 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -194,7 +193,7 @@ public class ParallelBuilderTest extends TimestampBuilderTestCase {
buildArtifacts(createBuilder(DEFAULT_NUM_JOBS, true), pear);
assertThat(recorder.actionExecutedEvents).hasSize(1);
- assertEquals(action, recorder.actionExecutedEvents.get(0).getAction());
+ assertThat(recorder.actionExecutedEvents.get(0).getAction()).isEqualTo(action);
}
@Test
@@ -480,7 +479,7 @@ public class ParallelBuilderTest extends TimestampBuilderTestCase {
BuildKind kind) {
// Check that we really did build all the targets.
for (Artifact file : targets) {
- assertTrue(file.getPath().exists());
+ assertThat(file.getPath().exists()).isTrue();
}
// Check that each action was executed the right number of times
for (Counter counter : counters) {
@@ -554,12 +553,15 @@ public class ParallelBuilderTest extends TimestampBuilderTestCase {
buildArtifacts(foo, bar);
fail();
} catch (BuildFailedException e) {
- assertThat(e.getMessage()).contains("TestAction failed due to exception: foo action failed");
+ assertThat(e)
+ .hasMessageThat()
+ .contains("TestAction failed due to exception: foo action failed");
assertContainsEvent("TestAction failed due to exception: foo action failed");
}
- assertTrue("bar action not finished, yet buildArtifacts has completed.",
- finished[0]);
+ assertWithMessage("bar action not finished, yet buildArtifacts has completed.")
+ .that(finished[0])
+ .isTrue();
}
@Test
@@ -577,7 +579,7 @@ public class ParallelBuilderTest extends TimestampBuilderTestCase {
buildArtifacts(foo);
fail("Builder failed to detect cyclic action graph");
} catch (BuildFailedException e) {
- assertEquals(CYCLE_MSG, e.getMessage());
+ assertThat(e).hasMessageThat().isEqualTo(CYCLE_MSG);
}
}
@@ -590,7 +592,7 @@ public class ParallelBuilderTest extends TimestampBuilderTestCase {
buildArtifacts(foo);
fail("Builder failed to detect cyclic action graph");
} catch (BuildFailedException e) {
- assertEquals(CYCLE_MSG, e.getMessage());
+ assertThat(e).hasMessageThat().isEqualTo(CYCLE_MSG);
}
}
@@ -612,7 +614,7 @@ public class ParallelBuilderTest extends TimestampBuilderTestCase {
buildArtifacts(foo1, foo2);
fail("Builder failed to detect cyclic action graph");
} catch (BuildFailedException e) {
- assertEquals(CYCLE_MSG, e.getMessage());
+ assertThat(e).hasMessageThat().isEqualTo(CYCLE_MSG);
}
}
@@ -634,7 +636,7 @@ public class ParallelBuilderTest extends TimestampBuilderTestCase {
buildArtifacts(foo);
fail("Builder failed to detect cyclic action graph");
} catch (BuildFailedException e) {
- assertEquals(CYCLE_MSG, e.getMessage());
+ assertThat(e).hasMessageThat().isEqualTo(CYCLE_MSG);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java
index 8786b42af3..535d4dadb0 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java
@@ -15,8 +15,6 @@ package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.skyframe.WalkableGraphUtils.exists;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus;
@@ -61,11 +59,13 @@ public class PrepareDepsOfPatternsFunctionSmartNegationTest extends BuildViewTes
patternSequence, /*successExpected=*/ true, /*keepGoing=*/ true);
// Then the graph contains package values for "@//foo" and "@//foo/foo",
- assertTrue(exists(PackageValue.key(PackageIdentifier.parse("@//foo")), walkableGraph));
- assertTrue(exists(PackageValue.key(PackageIdentifier.parse("@//foo/foo")), walkableGraph));
+ assertThat(exists(PackageValue.key(PackageIdentifier.parse("@//foo")), walkableGraph)).isTrue();
+ assertThat(exists(PackageValue.key(PackageIdentifier.parse("@//foo/foo")), walkableGraph))
+ .isTrue();
// But the graph does not contain a value for the target "@//foo/foo:foofoo".
- assertFalse(exists(getKeyForLabel(Label.create("@//foo/foo", "foofoo")), walkableGraph));
+ assertThat(exists(getKeyForLabel(Label.create("@//foo/foo", "foofoo")), walkableGraph))
+ .isFalse();
}
@Test
@@ -105,14 +105,15 @@ public class PrepareDepsOfPatternsFunctionSmartNegationTest extends BuildViewTes
patternSequence, /*successExpected=*/ true, /*keepGoing=*/ true);
// Then the graph contains a package value for "@//foo",
- assertTrue(exists(PackageValue.key(PackageIdentifier.parse("@//foo")), walkableGraph));
+ assertThat(exists(PackageValue.key(PackageIdentifier.parse("@//foo")), walkableGraph)).isTrue();
// But no package value for "@//foo/foo",
- assertFalse(exists(PackageValue.key(PackageIdentifier.parse("@//foo/foo")), walkableGraph));
+ assertThat(exists(PackageValue.key(PackageIdentifier.parse("@//foo/foo")), walkableGraph))
+ .isFalse();
// And the graph does not contain a value for the target "@//foo/foo:foofoo".
Label label = Label.create("@//foo/foo", "foofoo");
- assertFalse(exists(getKeyForLabel(label), walkableGraph));
+ assertThat(exists(getKeyForLabel(label), walkableGraph)).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionTest.java
index 0afcbed94f..13bae04250 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionTest.java
@@ -16,10 +16,6 @@ package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.skyframe.EvaluationResultSubjectFactory.assertThatEvaluationResult;
import static com.google.devtools.build.skyframe.WalkableGraphUtils.exists;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus;
@@ -64,7 +60,7 @@ public class PrepareDepsOfPatternsFunctionTest extends BuildViewTestCase {
assertValidValue(walkableGraph, getKeyForLabel(Label.create("@//foo", "foo")));
// And the graph does not contain a value for the target "@//foo:foo2".
- assertFalse(exists(getKeyForLabel(Label.create("@//foo", "foo2")), walkableGraph));
+ assertThat(exists(getKeyForLabel(Label.create("@//foo", "foo2")), walkableGraph)).isFalse();
}
@Test
@@ -109,7 +105,7 @@ public class PrepareDepsOfPatternsFunctionTest extends BuildViewTestCase {
WalkableGraph walkableGraph = getGraphFromPatternsEvaluation(patternSequence);
// Then the graph does not contain an entry for ":foo",
- assertFalse(exists(getKeyForLabel(Label.create("@//foo", "foo")), walkableGraph));
+ assertThat(exists(getKeyForLabel(Label.create("@//foo", "foo")), walkableGraph)).isFalse();
}
@Test
@@ -191,7 +187,7 @@ public class PrepareDepsOfPatternsFunctionTest extends BuildViewTestCase {
assertContainsEvent("Skipping '" + bogusPattern + "': ");
// And then the graph contains a value for the legit target pattern's target "@//foo:foo".
- assertTrue(exists(getKeyForLabel(Label.create("@//foo", "foo")), walkableGraph));
+ assertThat(exists(getKeyForLabel(Label.create("@//foo", "foo")), walkableGraph)).isTrue();
}
// Helpers:
@@ -267,19 +263,19 @@ public class PrepareDepsOfPatternsFunctionTest extends BuildViewTestCase {
private static void assertValidValue(
WalkableGraph graph, SkyKey key, boolean expectTransitiveException)
throws InterruptedException {
- assertNotNull(graph.getValue(key));
+ assertThat(graph.getValue(key)).isNotNull();
if (expectTransitiveException) {
- assertNotNull(graph.getException(key));
+ assertThat(graph.getException(key)).isNotNull();
} else {
- assertNull(graph.getException(key));
+ assertThat(graph.getException(key)).isNull();
}
}
private static Exception assertException(WalkableGraph graph, SkyKey key)
throws InterruptedException {
- assertNull(graph.getValue(key));
+ assertThat(graph.getValue(key)).isNull();
Exception exception = graph.getException(key);
- assertNotNull(exception);
+ assertThat(exception).isNotNull();
return exception;
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfTargetsUnderDirectoryFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfTargetsUnderDirectoryFunctionTest.java
index 1602f4a62a..69a46cc02c 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfTargetsUnderDirectoryFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfTargetsUnderDirectoryFunctionTest.java
@@ -16,8 +16,6 @@ package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.skyframe.WalkableGraphUtils.exists;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@@ -189,18 +187,21 @@ public class PrepareDepsOfTargetsUnderDirectoryFunctionTest extends BuildViewTes
// Also, the computation graph does not contain a cached value for "a/b".
WalkableGraph graph = Preconditions.checkNotNull(evaluationResult.getWalkableGraph());
- assertFalse(
- exists(
- createPrepDepsKey(rootDirectory, excludedPathFragment, ImmutableSet.<PathFragment>of()),
- graph));
+ assertThat(
+ exists(
+ createPrepDepsKey(
+ rootDirectory, excludedPathFragment, ImmutableSet.<PathFragment>of()),
+ graph))
+ .isFalse();
// And the computation graph does contain a cached value for "a/c" with the empty set excluded,
// because that key was evaluated.
- assertTrue(
- exists(
- createPrepDepsKey(
- rootDirectory, PathFragment.create("a/c"), ImmutableSet.<PathFragment>of()),
- graph));
+ assertThat(
+ exists(
+ createPrepDepsKey(
+ rootDirectory, PathFragment.create("a/c"), ImmutableSet.<PathFragment>of()),
+ graph))
+ .isTrue();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/RecursiveFilesystemTraversalFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/RecursiveFilesystemTraversalFunctionTest.java
index 2aa91f699d..2d121cbe1e 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/RecursiveFilesystemTraversalFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/RecursiveFilesystemTraversalFunctionTest.java
@@ -636,7 +636,8 @@ public final class RecursiveFilesystemTraversalFunctionTest extends FoundationTe
SkyKey key = rftvSkyKey(traversalRoot);
EvaluationResult<SkyValue> result = eval(key);
assertThat(result.hasError()).isTrue();
- assertThat(result.getError().getException().getMessage())
+ assertThat(result.getError().getException())
+ .hasMessageThat()
.contains("crosses package boundary into package rooted at");
break;
default:
@@ -811,7 +812,8 @@ public final class RecursiveFilesystemTraversalFunctionTest extends FoundationTe
assertThat(result.hasError()).isTrue();
ErrorInfo error = result.getError(key);
assertThat(error.isTransient()).isFalse();
- assertThat(error.getException().getMessage())
+ assertThat(error.getException())
+ .hasMessageThat()
.contains("Generated directory a/b/c conflicts with package under the same path.");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/RecursivePkgFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/RecursivePkgFunctionTest.java
index 6c7befe128..474ab93339 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/RecursivePkgFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/RecursivePkgFunctionTest.java
@@ -15,9 +15,6 @@ package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.skyframe.WalkableGraphUtils.exists;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@@ -93,7 +90,7 @@ public class RecursivePkgFunctionTest extends BuildViewTestCase {
scratch.file("a/b/c/BUILD");
RecursivePkgValue value =
buildRecursivePkgValue(rootDirectory, PathFragment.create("a/b/c/BUILD"));
- assertTrue(value.getPackages().isEmpty());
+ assertThat(value.getPackages().isEmpty()).isTrue();
}
@Test
@@ -108,11 +105,11 @@ public class RecursivePkgFunctionTest extends BuildViewTestCase {
RecursivePkgValue valueForRoot1 = buildRecursivePkgValue(root1, PathFragment.create("a"));
String root1Pkg = Iterables.getOnlyElement(valueForRoot1.getPackages());
- assertEquals("a", root1Pkg);
+ assertThat(root1Pkg).isEqualTo("a");
RecursivePkgValue valueForRoot2 = buildRecursivePkgValue(root2, PathFragment.create("a"));
String root2Pkg = Iterables.getOnlyElement(valueForRoot2.getPackages());
- assertEquals("a/b", root2Pkg);
+ assertThat(root2Pkg).isEqualTo("a/b");
}
@Test
@@ -139,19 +136,21 @@ public class RecursivePkgFunctionTest extends BuildViewTestCase {
// Also, the computation graph does not contain a cached value for "a/b".
WalkableGraph graph = Preconditions.checkNotNull(evaluationResult.getWalkableGraph());
- assertFalse(
- exists(
- buildRecursivePkgKey(
- rootDirectory, excludedPathFragment, ImmutableSet.<PathFragment>of()),
- graph));
+ assertThat(
+ exists(
+ buildRecursivePkgKey(
+ rootDirectory, excludedPathFragment, ImmutableSet.<PathFragment>of()),
+ graph))
+ .isFalse();
// And the computation graph does contain a cached value for "a/c" with the empty set excluded,
// because that key was evaluated.
- assertTrue(
- exists(
- buildRecursivePkgKey(
- rootDirectory, PathFragment.create("a/c"), ImmutableSet.<PathFragment>of()),
- graph));
+ assertThat(
+ exists(
+ buildRecursivePkgKey(
+ rootDirectory, PathFragment.create("a/c"), ImmutableSet.<PathFragment>of()),
+ graph))
+ .isTrue();
}
@Test
@@ -177,9 +176,10 @@ public class RecursivePkgFunctionTest extends BuildViewTestCase {
// Also, the computation graph contains a cached value for "a/b" with "a/b/c" excluded, because
// "a/b/c" does live underneath "a/b".
WalkableGraph graph = Preconditions.checkNotNull(evaluationResult.getWalkableGraph());
- assertTrue(
- exists(
- buildRecursivePkgKey(rootDirectory, PathFragment.create("a/b"), excludedPaths),
- graph));
+ assertThat(
+ exists(
+ buildRecursivePkgKey(rootDirectory, PathFragment.create("a/b"), excludedPaths),
+ graph))
+ .isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTest.java
index 89566b1b09..063c1dbc55 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -74,7 +73,7 @@ public class SkyframeLabelVisitorTest extends SkyframeLabelVisitorTestCase {
scratch.file("unrelated/BUILD", "sh_library(name = 'unrelated')");
assertLabelsVisited(
ImmutableSet.of("//bar:foo"), ImmutableSet.of("//bar:foo"), !EXPECT_ERROR, !KEEP_GOING);
- assertTrue(sym1.delete());
+ assertThat(sym1.delete()).isTrue();
FileSystemUtils.ensureSymbolicLink(sym1, sym2);
syncPackages();
assertLabelsVisited(
@@ -82,9 +81,9 @@ public class SkyframeLabelVisitorTest extends SkyframeLabelVisitorTestCase {
ImmutableSet.of("//unrelated:unrelated"),
!EXPECT_ERROR,
!KEEP_GOING);
- assertTrue(sym1.delete());
+ assertThat(sym1.delete()).isTrue();
FileSystemUtils.ensureSymbolicLink(sym1, path);
- assertTrue(symlink.delete());
+ assertThat(symlink.delete()).isTrue();
symlink = scratch.file("bar/BUILD", "sh_library(name = 'bar')");
syncPackages();
assertLabelsVisited(
@@ -349,7 +348,7 @@ public class SkyframeLabelVisitorTest extends SkyframeLabelVisitorTestCase {
// This is expected for legacy blaze.
} catch (RuntimeException re) {
// This is expected for Skyframe blaze.
- assertThat(re.getCause()).isInstanceOf(NullPointerException.class);
+ assertThat(re).hasCauseThat().isInstanceOf(NullPointerException.class);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTestCase.java b/src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTestCase.java
index 17f27ca56e..0b92f726ae 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/SkyframeLabelVisitorTestCase.java
@@ -15,7 +15,6 @@ package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.skyframe.WalkableGraphUtils.exists;
-import static org.junit.Assert.assertNotSame;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
@@ -135,7 +134,7 @@ abstract public class SkyframeLabelVisitorTestCase extends PackageLoadingTestCas
// Spawn a lot of threads to help uncover concurrency issues
boolean result = visitor.sync(reporter, startingLabels, keepGoing, /*parallelThreads=*/ 200);
- assertNotSame(expectError, result);
+ assertThat(result).isNotSameAs(expectError);
assertExpectedTargets(expectedLabels, startingLabels);
}
@@ -209,7 +208,7 @@ abstract public class SkyframeLabelVisitorTestCase extends PackageLoadingTestCas
// Spawn a lot of threads to help uncover concurrency issues
boolean result = visitor.sync(reporter, labels, keepGoing, 200);
- assertNotSame(expectError, result);
+ assertThat(result).isNotSameAs(expectError);
assertThat(getVisitedLabels(asLabelSet(startingLabels), skyframeExecutor))
.containsAllIn(asLabelSet(expectedLabels));
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/SkylarkFileContentHashTests.java b/src/test/java/com/google/devtools/build/lib/skyframe/SkylarkFileContentHashTests.java
index 59a68c50d7..7a548becad 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/SkylarkFileContentHashTests.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/SkylarkFileContentHashTests.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -80,7 +79,7 @@ public class SkylarkFileContentHashTests extends BuildViewTestCase {
@Test
public void testHashInvariance() throws Exception {
- assertEquals(getHash("pkg", "foo1"), getHash("pkg", "foo1"));
+ assertThat(getHash("pkg", "foo1")).isEqualTo(getHash("pkg", "foo1"));
}
@Test
@@ -92,12 +91,12 @@ public class SkylarkFileContentHashTests extends BuildViewTestCase {
"",
"bar1 = rule(implementation = rule_impl)");
invalidatePackages();
- assertEquals(bar1, getHash("pkg", "bar1"));
+ assertThat(getHash("pkg", "bar1")).isEqualTo(bar1);
}
@Test
public void testHashSameForRulesDefinedInSameFile() throws Exception {
- assertEquals(getHash("pkg", "foo1"), getHash("pkg", "foo2"));
+ assertThat(getHash("pkg", "foo2")).isEqualTo(getHash("pkg", "foo1"));
}
@Test
@@ -145,12 +144,12 @@ public class SkylarkFileContentHashTests extends BuildViewTestCase {
"",
"bar1 = rule(implementation = rule_impl)");
invalidatePackages();
- assertEquals(foo1, getHash("pkg", "foo1"));
- assertEquals(foo2, getHash("pkg", "foo2"));
+ assertThat(getHash("pkg", "foo1")).isEqualTo(foo1);
+ assertThat(getHash("pkg", "foo2")).isEqualTo(foo2);
}
private void assertNotEquals(String hash, String hash2) {
- assertFalse(hash.equals(hash2));
+ assertThat(hash.equals(hash2)).isFalse();
}
/**
@@ -176,7 +175,7 @@ public class SkylarkFileContentHashTests extends BuildViewTestCase {
EvaluationResult<PackageValue> result =
SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), pkgLookupKey, /*keepGoing=*/ false, reporter);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
Collection<Target> targets = result.get(pkgLookupKey).getPackage().getTargets().values();
for (Target target : targets) {
if (target.getName().equals(name)) {
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/SkylarkImportLookupFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/SkylarkImportLookupFunctionTest.java
index a386a8042c..602d097101 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/SkylarkImportLookupFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/SkylarkImportLookupFunctionTest.java
@@ -13,9 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -174,8 +172,8 @@ public class SkylarkImportLookupFunctionTest extends BuildViewTestCase {
private void checkSuccessfulLookup(String label) throws Exception {
SkyKey skylarkImportLookupKey = key(label);
EvaluationResult<SkylarkImportLookupValue> result = get(skylarkImportLookupKey);
- assertEquals(result.get(skylarkImportLookupKey).getDependency().getLabel().toString(),
- label);
+ assertThat(label)
+ .isEqualTo(result.get(skylarkImportLookupKey).getDependency().getLabel().toString());
}
@Test
@@ -186,11 +184,13 @@ public class SkylarkImportLookupFunctionTest extends BuildViewTestCase {
EvaluationResult<SkylarkImportLookupValue> result =
SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skylarkImportLookupKey, /*keepGoing=*/ false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skylarkImportLookupKey);
String errorMessage = errorInfo.getException().getMessage();
- assertEquals("Extension file not found. Unable to load package for '//pkg:ext.bzl': "
- + "BUILD file not found on package path", errorMessage);
+ assertThat(errorMessage)
+ .isEqualTo(
+ "Extension file not found. Unable to load package for '//pkg:ext.bzl': "
+ + "BUILD file not found on package path");
}
@Test
@@ -203,11 +203,13 @@ public class SkylarkImportLookupFunctionTest extends BuildViewTestCase {
EvaluationResult<SkylarkImportLookupValue> result =
SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skylarkImportLookupKey, /*keepGoing=*/ false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skylarkImportLookupKey);
String errorMessage = errorInfo.getException().getMessage();
- assertEquals("Extension file not found. Unable to load package for '//pkg:ext.bzl': "
- + "BUILD file not found on package path", errorMessage);
+ assertThat(errorMessage)
+ .isEqualTo(
+ "Extension file not found. Unable to load package for '//pkg:ext.bzl': "
+ + "BUILD file not found on package path");
}
@Test
@@ -219,11 +221,13 @@ public class SkylarkImportLookupFunctionTest extends BuildViewTestCase {
EvaluationResult<SkylarkImportLookupValue> result =
SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skylarkImportLookupKey, /*keepGoing=*/ false, reporter);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
ErrorInfo errorInfo = result.getError(skylarkImportLookupKey);
String errorMessage = errorInfo.getException().getMessage();
- assertEquals("invalid target name 'oops<?>.bzl': "
- + "target names may not contain non-printable characters: '\\x00'", errorMessage);
+ assertThat(errorMessage)
+ .isEqualTo(
+ "invalid target name 'oops<?>.bzl': "
+ + "target names may not contain non-printable characters: '\\x00'");
}
@Test
@@ -246,6 +250,6 @@ public class SkylarkImportLookupFunctionTest extends BuildViewTestCase {
SkyframeExecutorTestUtils.evaluate(
getSkyframeExecutor(), skylarkImportLookupKey, /*keepGoing=*/ false, reporter);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/TargetMarkerFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/TargetMarkerFunctionTest.java
index 5561adcf71..ce80ffc0a5 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/TargetMarkerFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/TargetMarkerFunctionTest.java
@@ -14,10 +14,7 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.cmdline.Label;
@@ -36,19 +33,17 @@ import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import com.google.devtools.build.skyframe.ErrorInfo;
import com.google.devtools.build.skyframe.EvaluationResult;
import com.google.devtools.build.skyframe.SkyKey;
-
+import java.io.IOException;
+import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.IOException;
-import java.util.Map;
-
/**
* Tests for {@link TargetMarkerFunction}. Unfortunately, we can't directly test
- * TargetMarkerFunction as it uses PackageValues, and PackageFunction uses legacy stuff
- * that isn't easily mockable. So our testing strategy is to make hacky calls to SkyframeExecutor.
+ * TargetMarkerFunction as it uses PackageValues, and PackageFunction uses legacy stuff that isn't
+ * easily mockable. So our testing strategy is to make hacky calls to SkyframeExecutor.
*/
@RunWith(JUnit4.class)
public class TargetMarkerFunctionTest extends BuildViewTestCase {
@@ -80,7 +75,7 @@ public class TargetMarkerFunctionTest extends BuildViewTestCase {
reporter.addHandler(failFastHandler);
ErrorInfo errorInfo = evaluationResult.getError(skyKey(labelName));
// Ensures that TargetFunction rethrows all transitive exceptions.
- assertEquals(targetKey, Iterables.getOnlyElement(errorInfo.getRootCauses()));
+ assertThat(errorInfo.getRootCauses()).containsExactly(targetKey);
return errorInfo.getException();
}
@@ -100,7 +95,8 @@ public class TargetMarkerFunctionTest extends BuildViewTestCase {
NoSuchTargetException exn = (NoSuchTargetException) getErrorFromTargetValue(labelName);
// In the presence of b/12545745, the error message is different and comes from the
// PackageFunction.
- assertThat(exn.getMessage())
+ assertThat(exn)
+ .hasMessageThat()
.contains("Label '//a:b/c/foo.sh' crosses boundary of subpackage 'a/b'");
}
@@ -109,7 +105,7 @@ public class TargetMarkerFunctionTest extends BuildViewTestCase {
String labelName = "//no/such/package:target/withslash";
BuildFileNotFoundException exn =
(BuildFileNotFoundException) getErrorFromTargetValue(labelName);
- assertEquals(PackageIdentifier.createInMainRepo("no/such/package"), exn.getPackageId());
+ assertThat(exn.getPackageId()).isEqualTo(PackageIdentifier.createInMainRepo("no/such/package"));
String expectedMessage =
"no such package 'no/such/package': BUILD file not found on "
+ "package path for 'no/such/package'";
@@ -124,10 +120,11 @@ public class TargetMarkerFunctionTest extends BuildViewTestCase {
"genrule(name = 'conflict1', cmd = '', srcs = [], outs = ['conflict'])",
"genrule(name = 'conflict2', cmd = '', srcs = [], outs = ['conflict'])");
NoSuchTargetException exn = (NoSuchTargetException) getErrorFromTargetValue("@//a:conflict1");
- assertThat(exn.getMessage())
+ assertThat(exn)
+ .hasMessageThat()
.contains("Target '//a:conflict1' contains an error and its package is in error");
- assertEquals("//a:conflict1", exn.getLabel().toString());
- assertTrue(exn.hasTarget());
+ assertThat(exn.getLabel().toString()).isEqualTo("//a:conflict1");
+ assertThat(exn.hasTarget()).isTrue();
}
@Test
@@ -138,7 +135,7 @@ public class TargetMarkerFunctionTest extends BuildViewTestCase {
fs.stubStatIOException(subpackageBuildFile, new IOException("nope"));
BuildFileNotFoundException exn =
(BuildFileNotFoundException) getErrorFromTargetValue("//a:b/c");
- assertThat(exn.getMessage()).contains("nope");
+ assertThat(exn).hasMessageThat().contains("nope");
}
private static class CustomInMemoryFs extends InMemoryFileSystem {
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderMediumTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderMediumTest.java
index 3c274f91c5..4334b3e407 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderMediumTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderMediumTest.java
@@ -14,8 +14,6 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -30,17 +28,15 @@ import com.google.devtools.build.lib.testutil.TestSpec;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.UnixGlob;
-
+import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.IOException;
-
/**
- * These tests belong to {@link TimestampBuilderTest}, but they're in a
- * separate class for now because they are a little slower.
+ * These tests belong to {@link TimestampBuilderTest}, but they're in a separate class for now
+ * because they are a little slower.
*/
@TestSpec(size = Suite.MEDIUM_TESTS)
@RunWith(JUnit4.class)
@@ -81,41 +77,41 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Creating a new persistent cache does not cause a rebuild
cache.save();
cache = createCache();
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
BlazeTestUtils.makeEmptyFile(optional.getPath());
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
optional.getPath().delete();
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
// Creating a new persistent cache does not cause a rebuild
cache.save();
cache = createCache();
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -128,27 +124,27 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
hello.getPath().setWritable(true);
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "new content");
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Creating a new persistent cache does not cause a rebuild
cache.save();
buildArtifacts(persistentBuilder(createCache()), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -162,30 +158,30 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // still not rebuilt
+ assertThat(button.pressed).isFalse(); // still not rebuilt
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "content2");
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Creating a new persistent cache does not cause a rebuild
cache.save();
buildArtifacts(persistentBuilder(createCache()), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -204,11 +200,11 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Now create duplicate graph, with swapped order.
clearActions();
@@ -219,7 +215,7 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button2.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button2.pressed); // still not rebuilt
+ assertThat(button2.pressed).isFalse(); // still not rebuilt
}
@Test
@@ -232,7 +228,7 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
// action1 is cached using the cache key /goodbye.
assertThat(cache.get(goodbye.getExecPathString())).isNotNull();
@@ -246,7 +242,7 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button2.pressed = false;
buildArtifacts(persistentBuilder(cache), hello, goodbye2);
- assertTrue(button2.pressed); // rebuilt
+ assertThat(button2.pressed).isTrue(); // rebuilt
// action2 is cached using the cache key /hello.
assertThat(cache.get(hello.getExecPathString())).isNotNull();
@@ -267,11 +263,11 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Now create duplicate graph, replacing "hello" with "hi".
clearActions();
@@ -283,7 +279,7 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button2.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye2);
- assertTrue(button2.pressed); // name changed. must rebuild.
+ assertThat(button2.pressed).isTrue(); // name changed. must rebuild.
}
@Test
@@ -299,26 +295,26 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "hello2");
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Creating a new persistent cache does not cause a rebuild
cache.save();
buildArtifacts(persistentBuilder(createCache()), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
/**
@@ -337,18 +333,18 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Creating a new persistent caches, including metadata cache does not cause
// a rebuild
cache.save();
Builder builder = persistentBuilder(createCache());
buildArtifacts(builder, goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -359,27 +355,27 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
hello.getPath().setWritable(true);
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "new content");
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Creating a new persistent cache does not cause a rebuild
cache.save();
buildArtifacts(persistentBuilder(createCache()), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -390,31 +386,32 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
hello.getPath().setWritable(true);
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "new content");
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Creating a new persistent cache does not cause a rebuild
cache.save();
// Remove filename index file.
- assertTrue(
- Iterables.getOnlyElement(
- UnixGlob.forPath(cacheRoot).addPattern("filename_index*").globInterruptible())
- .delete());
+ assertThat(
+ Iterables.getOnlyElement(
+ UnixGlob.forPath(cacheRoot).addPattern("filename_index*").globInterruptible())
+ .delete())
+ .isTrue();
// Now first cache creation attempt should cause IOException while renaming corrupted files.
// Second attempt will initialize empty cache, causing rebuild.
@@ -426,7 +423,7 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
}
buildArtifacts(persistentBuilder(createCache()), hello);
- assertTrue(button.pressed); // rebuilt due to the missing filename index
+ assertThat(button.pressed).isTrue(); // rebuilt due to the missing filename index
}
@Test
@@ -437,22 +434,22 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
hello.getPath().setWritable(true);
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "new content");
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(persistentBuilder(cache), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
cache.save();
@@ -467,14 +464,14 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
Artifact helloExtra = createDerivedArtifact("hello_extra");
Button buttonExtra = createActionButton(emptySet, Sets.newHashSet(helloExtra));
buildArtifacts(persistentBuilder(cache), helloExtra);
- assertTrue(buttonExtra.pressed); // built
+ assertThat(buttonExtra.pressed).isTrue(); // built
cache.save();
- assertTrue(indexPath.getFileSize() > indexCopy.getFileSize());
+ assertThat(indexPath.getFileSize()).isGreaterThan(indexCopy.getFileSize());
// Validate current cache.
buildArtifacts(persistentBuilder(createCache()), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Restore outdated file index.
FileSystemUtils.copyFile(indexCopy, indexPath);
@@ -485,11 +482,11 @@ public class TimestampBuilderMediumTest extends TimestampBuilderTestCase {
createCache();
fail("Expected IOException");
} catch (IOException e) {
- assertThat(e.getMessage()).contains("Failed action cache referential integrity check");
+ assertThat(e).hasMessageThat().contains("Failed action cache referential integrity check");
}
// Validate cache with incorrect (out-of-date) filename index.
buildArtifacts(persistentBuilder(createCache()), hello);
- assertTrue(button.pressed); // rebuilt due to the out-of-date index
+ assertThat(button.pressed).isTrue(); // rebuilt due to the out-of-date index
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderTest.java
index 439b57e2db..d7ecec6d8a 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/TimestampBuilderTest.java
@@ -15,9 +15,6 @@
package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.Sets;
@@ -47,11 +44,11 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(amnesiacBuilder(), hello);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(amnesiacBuilder(), hello);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
}
// If we re-use the same builder (even an "amnesiac" builder), it remembers
@@ -71,7 +68,7 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
counter.count = 0;
buildArtifacts(amnesiacBuilder, hello, hello);
- assertEquals(1, counter.count); // built only once
+ assertThat(counter.count).isEqualTo(1); // built only once
}
@Test
@@ -101,17 +98,17 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(cachingBuilder(), hello);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(cachingBuilder(), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
inMemoryCache.reset();
button.pressed = false;
buildArtifacts(cachingBuilder(), hello);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
}
@Test
@@ -124,31 +121,31 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
BlazeTestUtils.makeEmptyFile(optional.getPath());
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
optional.getPath().delete();
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -161,22 +158,22 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
hello.getPath().setWritable(true);
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "new content");
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -192,27 +189,27 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
FileSystemUtils.touchFile(hello.getPath());
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button.pressed); // still not rebuilt
+ assertThat(button.pressed).isFalse(); // still not rebuilt
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "content2");
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -223,11 +220,11 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(cachingBuilder(), hello);
- assertTrue(button.pressed); // built
+ assertThat(button.pressed).isTrue(); // built
button.pressed = false;
buildArtifacts(cachingBuilder(), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
// Changing the *output* file 'hello' causes 'action' to re-execute, to make things consistent
// again.
@@ -236,11 +233,11 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
button.pressed = false;
buildArtifacts(cachingBuilder(), hello);
- assertTrue(button.pressed); // rebuilt
+ assertThat(button.pressed).isTrue(); // rebuilt
button.pressed = false;
buildArtifacts(cachingBuilder(), hello);
- assertFalse(button.pressed); // not rebuilt
+ assertThat(button.pressed).isFalse(); // not rebuilt
}
@Test
@@ -256,31 +253,31 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
button1.pressed = button2.pressed = false;
buildArtifacts(cachingBuilder(), wazuup);
- assertTrue(button1.pressed); // built wazuup
- assertFalse(button2.pressed); // goodbye not built
+ assertThat(button1.pressed).isTrue(); // built wazuup
+ assertThat(button2.pressed).isFalse(); // goodbye not built
button1.pressed = button2.pressed = false;
buildArtifacts(cachingBuilder(), wazuup);
- assertFalse(button1.pressed); // wazuup not rebuilt
- assertFalse(button2.pressed); // goodbye not built
+ assertThat(button1.pressed).isFalse(); // wazuup not rebuilt
+ assertThat(button2.pressed).isFalse(); // goodbye not built
button1.pressed = button2.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button1.pressed); // wazuup not rebuilt
- assertTrue(button2.pressed); // built goodbye
+ assertThat(button1.pressed).isFalse(); // wazuup not rebuilt
+ assertThat(button2.pressed).isTrue(); // built goodbye
button1.pressed = button2.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertFalse(button1.pressed); // wazuup not rebuilt
- assertFalse(button2.pressed); // goodbye not rebuilt
+ assertThat(button1.pressed).isFalse(); // wazuup not rebuilt
+ assertThat(button2.pressed).isFalse(); // goodbye not rebuilt
hello.getPath().setWritable(true);
FileSystemUtils.writeContentAsLatin1(hello.getPath(), "new content");
button1.pressed = button2.pressed = false;
buildArtifacts(cachingBuilder(), goodbye);
- assertTrue(button1.pressed); // hello rebuilt
- assertTrue(button2.pressed); // goodbye rebuilt
+ assertThat(button1.pressed).isTrue(); // hello rebuilt
+ assertThat(button2.pressed).isTrue(); // goodbye rebuilt
}
@Test
@@ -297,15 +294,15 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
buildArtifacts(cachingBuilder(), anOutputFile, anotherOutputFile);
- assertTrue(aButton.pressed);
- assertTrue(anotherButton.pressed);
+ assertThat(aButton.pressed).isTrue();
+ assertThat(anotherButton.pressed).isTrue();
aButton.pressed = anotherButton.pressed = false;
buildArtifacts(cachingBuilder(), anOutputFile, anotherOutputFile);
- assertFalse(aButton.pressed);
- assertFalse(anotherButton.pressed);
+ assertThat(aButton.pressed).isFalse();
+ assertThat(anotherButton.pressed).isFalse();
}
@Test
@@ -331,7 +328,7 @@ public class TimestampBuilderTest extends TimestampBuilderTestCase {
buildArtifacts(amnesiacBuilder(), out); // fails with ActionExecutionException
fail();
} catch (BuildFailedException e) {
- assertThat(e.getMessage()).contains("1 input file(s) do not exist");
+ assertThat(e).hasMessageThat().contains("1 input file(s) do not exist");
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactBuildTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactBuildTest.java
index a3853e6540..75d840e31c 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactBuildTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactBuildTest.java
@@ -15,8 +15,6 @@ package com.google.devtools.build.lib.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.actions.ActionInputHelper.treeFileArtifact;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
@@ -121,8 +119,8 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
registerAction(action);
buildArtifact(action.getSoleOutput());
- assertTrue(outOneFileOne.getPath().exists());
- assertTrue(outOneFileTwo.getPath().exists());
+ assertThat(outOneFileOne.getPath().exists()).isTrue();
+ assertThat(outOneFileTwo.getPath().exists()).isTrue();
}
/** Simple test for the case with dependencies. */
@@ -138,10 +136,10 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buildArtifact(outTwo);
- assertTrue(outOneFileOne.getPath().exists());
- assertTrue(outOneFileTwo.getPath().exists());
- assertTrue(outTwoFileOne.getPath().exists());
- assertTrue(outTwoFileTwo.getPath().exists());
+ assertThat(outOneFileOne.getPath().exists()).isTrue();
+ assertThat(outOneFileTwo.getPath().exists()).isTrue();
+ assertThat(outTwoFileOne.getPath().exists()).isTrue();
+ assertThat(outTwoFileTwo.getPath().exists()).isTrue();
}
@Test
@@ -191,13 +189,13 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buttonOne.pressed = buttonTwo.pressed = false;
buildArtifact(outTwo);
- assertTrue(buttonOne.pressed); // built
- assertTrue(buttonTwo.pressed); // built
+ assertThat(buttonOne.pressed).isTrue(); // built
+ assertThat(buttonTwo.pressed).isTrue(); // built
buttonOne.pressed = buttonTwo.pressed = false;
buildArtifact(outTwo);
- assertFalse(buttonOne.pressed); // not built
- assertFalse(buttonTwo.pressed); // not built
+ assertThat(buttonOne.pressed).isFalse(); // not built
+ assertThat(buttonTwo.pressed).isFalse(); // not built
}
/**
@@ -220,26 +218,26 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buttonOne.pressed = buttonTwo.pressed = false;
buildArtifact(outTwo);
- assertTrue(buttonOne.pressed); // built
- assertTrue(buttonTwo.pressed); // built
+ assertThat(buttonOne.pressed).isTrue(); // built
+ assertThat(buttonTwo.pressed).isTrue(); // built
buttonOne.pressed = buttonTwo.pressed = false;
writeFile(in, "modified_input");
buildArtifact(outTwo);
- assertTrue(buttonOne.pressed); // built
- assertTrue(buttonTwo.pressed); // not built
+ assertThat(buttonOne.pressed).isTrue(); // built
+ assertThat(buttonTwo.pressed).isTrue(); // not built
buttonOne.pressed = buttonTwo.pressed = false;
writeFile(outOneFileOne, "modified_output");
buildArtifact(outTwo);
- assertTrue(buttonOne.pressed); // built
- assertFalse(buttonTwo.pressed); // should have been cached
+ assertThat(buttonOne.pressed).isTrue(); // built
+ assertThat(buttonTwo.pressed).isFalse(); // should have been cached
buttonOne.pressed = buttonTwo.pressed = false;
writeFile(outTwoFileOne, "more_modified_output");
buildArtifact(outTwo);
- assertFalse(buttonOne.pressed); // not built
- assertTrue(buttonTwo.pressed); // built
+ assertThat(buttonOne.pressed).isFalse(); // not built
+ assertThat(buttonTwo.pressed).isTrue(); // built
}
/** Tests that changing a TreeArtifact directory should cause reexeuction. */
@@ -260,8 +258,8 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buttonOne.pressed = buttonTwo.pressed = false;
buildArtifact(outTwo);
// just a smoke test--if these aren't built we have bigger problems!
- assertTrue(buttonOne.pressed);
- assertTrue(buttonTwo.pressed);
+ assertThat(buttonOne.pressed).isTrue();
+ assertThat(buttonTwo.pressed).isTrue();
// Adding a file to a directory should cause reexecution.
buttonOne.pressed = buttonTwo.pressed = false;
@@ -269,32 +267,32 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
touchFile(spuriousOutputOne);
buildArtifact(outTwo);
// Should re-execute, and delete spurious output
- assertFalse(spuriousOutputOne.exists());
- assertTrue(buttonOne.pressed);
- assertFalse(buttonTwo.pressed); // should have been cached
+ assertThat(spuriousOutputOne.exists()).isFalse();
+ assertThat(buttonOne.pressed).isTrue();
+ assertThat(buttonTwo.pressed).isFalse(); // should have been cached
buttonOne.pressed = buttonTwo.pressed = false;
Path spuriousOutputTwo = outTwo.getPath().getRelative("anotherSpuriousOutput");
touchFile(spuriousOutputTwo);
buildArtifact(outTwo);
- assertFalse(spuriousOutputTwo.exists());
- assertFalse(buttonOne.pressed);
- assertTrue(buttonTwo.pressed);
+ assertThat(spuriousOutputTwo.exists()).isFalse();
+ assertThat(buttonOne.pressed).isFalse();
+ assertThat(buttonTwo.pressed).isTrue();
// Deleting should cause reexecution.
buttonOne.pressed = buttonTwo.pressed = false;
deleteFile(outOneFileOne);
buildArtifact(outTwo);
- assertTrue(outOneFileOne.getPath().exists());
- assertTrue(buttonOne.pressed);
- assertFalse(buttonTwo.pressed); // should have been cached
+ assertThat(outOneFileOne.getPath().exists()).isTrue();
+ assertThat(buttonOne.pressed).isTrue();
+ assertThat(buttonTwo.pressed).isFalse(); // should have been cached
buttonOne.pressed = buttonTwo.pressed = false;
deleteFile(outTwoFileOne);
buildArtifact(outTwo);
- assertTrue(outTwoFileOne.getPath().exists());
- assertFalse(buttonOne.pressed);
- assertTrue(buttonTwo.pressed);
+ assertThat(outTwoFileOne.getPath().exists()).isTrue();
+ assertThat(buttonOne.pressed).isFalse();
+ assertThat(buttonTwo.pressed).isTrue();
}
/** TreeArtifacts don't care about mtime, even when the file is empty. */
@@ -318,30 +316,30 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buttonOne.pressed = buttonTwo.pressed = false;
buildArtifact(outTwo);
- assertTrue(buttonOne.pressed); // built
- assertTrue(buttonTwo.pressed); // built
+ assertThat(buttonOne.pressed).isTrue(); // built
+ assertThat(buttonTwo.pressed).isTrue(); // built
buttonOne.pressed = buttonTwo.pressed = false;
touchFile(in);
buildArtifact(outTwo);
// mtime does not matter.
- assertFalse(buttonOne.pressed);
- assertFalse(buttonTwo.pressed);
+ assertThat(buttonOne.pressed).isFalse();
+ assertThat(buttonTwo.pressed).isFalse();
// None of the below following should result in anything being built.
buttonOne.pressed = buttonTwo.pressed = false;
touchFile(outOneFileOne);
buildArtifact(outTwo);
// Nothing should be built.
- assertFalse(buttonOne.pressed);
- assertFalse(buttonTwo.pressed);
+ assertThat(buttonOne.pressed).isFalse();
+ assertThat(buttonTwo.pressed).isFalse();
buttonOne.pressed = buttonTwo.pressed = false;
touchFile(outOneFileTwo);
buildArtifact(outTwo);
// Nothing should be built.
- assertFalse(buttonOne.pressed);
- assertFalse(buttonTwo.pressed);
+ assertThat(buttonOne.pressed).isFalse();
+ assertThat(buttonTwo.pressed).isFalse();
}
/** Tests that the declared order of TreeArtifact contents does not matter. */
@@ -455,17 +453,17 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
}
private static void checkDirectoryPermissions(Path path) throws IOException {
- assertTrue(path.isDirectory());
- assertTrue(path.isExecutable());
- assertTrue(path.isReadable());
- assertFalse(path.isWritable());
+ assertThat(path.isDirectory()).isTrue();
+ assertThat(path.isExecutable()).isTrue();
+ assertThat(path.isReadable()).isTrue();
+ assertThat(path.isWritable()).isFalse();
}
private static void checkFilePermissions(Path path) throws IOException {
- assertFalse(path.isDirectory());
- assertTrue(path.isExecutable());
- assertTrue(path.isReadable());
- assertFalse(path.isWritable());
+ assertThat(path.isDirectory()).isFalse();
+ assertThat(path.isExecutable()).isTrue();
+ assertThat(path.isReadable()).isTrue();
+ assertThat(path.isWritable()).isFalse();
}
@Test
@@ -777,7 +775,7 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buildArtifact(artifact2);
fail("Expected BuildFailedException");
} catch (BuildFailedException e) {
- assertThat(e.getMessage()).contains("not all outputs were created or valid");
+ assertThat(e).hasMessageThat().contains("not all outputs were created or valid");
}
}
@@ -822,7 +820,7 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buildArtifact(artifact2);
fail("Expected BuildFailedException");
} catch (BuildFailedException e) {
- assertThat(e.getMessage()).contains("Throwing dummy action");
+ assertThat(e).hasMessageThat().contains("Throwing dummy action");
}
}
@@ -866,7 +864,7 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buildArtifact(artifact2);
fail("Expected BuildFailedException");
} catch (BuildFailedException e) {
- assertThat(e.getMessage()).contains("Throwing dummy action");
+ assertThat(e).hasMessageThat().contains("Throwing dummy action");
}
}
@@ -890,7 +888,7 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
buildArtifact(artifact2);
fail("Expected BuildFailedException");
} catch (BuildFailedException e) {
- assertThat(e.getMessage()).contains("Throwing dummy action");
+ assertThat(e).hasMessageThat().contains("Throwing dummy action");
}
}
@@ -999,7 +997,7 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
}
Artifact output = getSoleOutput();
- assertTrue(output.getPath().exists());
+ assertThat(output.getPath().exists()).isTrue();
try {
effect.call();
executeTestBehavior(actionExecutionContext);
@@ -1147,8 +1145,8 @@ public class TreeArtifactBuildTest extends TimestampBuilderTestCase {
}
// both iterators must be of the same size
- assertFalse(inputIterator.hasNext());
- assertFalse(inputIterator.hasNext());
+ assertThat(inputIterator.hasNext()).isFalse();
+ assertThat(inputIterator.hasNext()).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactMetadataTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactMetadataTest.java
index 56bf8a511c..647d90f885 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactMetadataTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/TreeArtifactMetadataTest.java
@@ -191,7 +191,7 @@ public class TreeArtifactMetadataTest extends ArtifactFunctionTestCase {
ImmutableList.of(PathFragment.create("one")));
fail("MissingInputFileException expected, got " + value);
} catch (Exception e) {
- assertThat(Throwables.getRootCause(e).getMessage()).contains(exception.getMessage());
+ assertThat(Throwables.getRootCause(e)).hasMessageThat().contains(exception.getMessage());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/WorkspaceFileFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/WorkspaceFileFunctionTest.java
index 714c662fc8..61a6e9865f 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/WorkspaceFileFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/WorkspaceFileFunctionTest.java
@@ -14,9 +14,7 @@
package com.google.devtools.build.lib.skyframe;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
@@ -178,7 +176,7 @@ public class WorkspaceFileFunctionTest extends BuildViewTestCase {
(PackageValue) externalSkyFunc
.compute(ExternalPackageFunction.key(workspacePath), getEnv());
Package pkg = value.getPackage();
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
MoreAsserts.assertContainsEvent(pkg.getEvents(), "foo$ is not a legal workspace name");
}
@@ -190,7 +188,7 @@ public class WorkspaceFileFunctionTest extends BuildViewTestCase {
SkyKey key = ExternalPackageFunction.key(workspacePath);
PackageValue value = (PackageValue) externalSkyFunc.compute(key, getEnv());
Package pkg = value.getPackage();
- assertEquals(Label.parseAbsolute("//foo:bar"), getLabelMapping(pkg, "foo/bar"));
+ assertThat(getLabelMapping(pkg, "foo/bar")).isEqualTo(Label.parseAbsolute("//foo:bar"));
MoreAsserts.assertNoEvents(pkg.getEvents());
}
@@ -202,7 +200,7 @@ public class WorkspaceFileFunctionTest extends BuildViewTestCase {
SkyKey key = ExternalPackageFunction.key(workspacePath);
PackageValue value = (PackageValue) externalSkyFunc.compute(key, getEnv());
Package pkg = value.getPackage();
- assertEquals(Label.parseAbsolute("//foo:bar"), getLabelMapping(pkg, "foo/bar"));
+ assertThat(getLabelMapping(pkg, "foo/bar")).isEqualTo(Label.parseAbsolute("//foo:bar"));
MoreAsserts.assertNoEvents(pkg.getEvents());
}
@@ -216,7 +214,7 @@ public class WorkspaceFileFunctionTest extends BuildViewTestCase {
(PackageValue) externalSkyFunc
.compute(ExternalPackageFunction.key(workspacePath), getEnv());
Package pkg = value.getPackage();
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
MoreAsserts.assertContainsEvent(pkg.getEvents(), "target names may not contain ':'");
}
@@ -230,7 +228,7 @@ public class WorkspaceFileFunctionTest extends BuildViewTestCase {
(PackageValue) externalSkyFunc
.compute(ExternalPackageFunction.key(workspacePath), getEnv());
Package pkg = value.getPackage();
- assertTrue(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isTrue();
MoreAsserts.assertContainsEvent(pkg.getEvents(), "target names may not contain ':'");
}
@@ -245,7 +243,7 @@ public class WorkspaceFileFunctionTest extends BuildViewTestCase {
(PackageValue) externalSkyFunc
.compute(ExternalPackageFunction.key(workspacePath), getEnv());
Package pkg = value.getPackage();
- assertFalse(pkg.containsErrors());
+ assertThat(pkg.containsErrors()).isFalse();
MoreAsserts.assertNoEvents(pkg.getEvents());
}
@@ -258,7 +256,7 @@ public class WorkspaceFileFunctionTest extends BuildViewTestCase {
SkyKey key = ExternalPackageFunction.key(workspacePath);
PackageValue value = (PackageValue) externalSkyFunc.compute(key, getEnv());
Package pkg = value.getPackage();
- assertEquals(Label.parseAbsolute("//foo:bar"), getLabelMapping(pkg, "foo/bar"));
+ assertThat(getLabelMapping(pkg, "foo/bar")).isEqualTo(Label.parseAbsolute("//foo:bar"));
MoreAsserts.assertNoEvents(pkg.getEvents());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkFileHelperTest.java b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkFileHelperTest.java
index 93ec145659..45fb637630 100644
--- a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkFileHelperTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkFileHelperTest.java
@@ -15,7 +15,6 @@
package com.google.devtools.build.lib.skylark;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
@@ -49,7 +48,7 @@ public class SkylarkFileHelperTest extends SkylarkTestCase {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result =
evalRuleContextCode(ruleContext, "FileType(['.img']).filter(ruleContext.files.srcs)");
- assertEquals("b.img", ActionsTestUtil.baseNamesOf((Iterable<Artifact>) result));
+ assertThat(ActionsTestUtil.baseNamesOf((Iterable<Artifact>) result)).isEqualTo("b.img");
}
@Test
@@ -64,7 +63,7 @@ public class SkylarkFileHelperTest extends SkylarkTestCase {
public void testArtifactPath() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
String result = (String) evalRuleContextCode(ruleContext, "ruleContext.files.tools[0].path");
- assertEquals("foo/t.exe", result);
+ assertThat(result).isEqualTo("foo/t.exe");
}
@Test
@@ -72,6 +71,6 @@ public class SkylarkFileHelperTest extends SkylarkTestCase {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
String result =
(String) evalRuleContextCode(ruleContext, "ruleContext.files.tools[0].short_path");
- assertEquals("foo/t.exe", result);
+ assertThat(result).isEqualTo("foo/t.exe");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkIntegrationTest.java b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkIntegrationTest.java
index d5dc696df8..fb30097765 100644
--- a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkIntegrationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkIntegrationTest.java
@@ -16,8 +16,6 @@ package com.google.devtools.build.lib.skylark;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.analysis.OutputGroupProvider.INTERNAL_SUFFIX;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
@@ -423,7 +421,7 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
ConfiguredTarget target = getConfiguredTarget("//test/skylark:cr");
- assertEquals("//test/skylark:cr", target.getLabel().toString());
+ assertThat(target.getLabel().toString()).isEqualTo("//test/skylark:cr");
assertThat(
ActionsTestUtil.baseArtifactNames(
target.getProvider(FileProvider.class).getFilesToBuild()))
@@ -450,7 +448,7 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
ConfiguredTarget target = getConfiguredTarget("//test/skylark:cr");
- assertEquals("//test/skylark:cr", target.getLabel().toString());
+ assertThat(target.getLabel().toString()).isEqualTo("//test/skylark:cr");
assertThat(
ActionsTestUtil.baseArtifactNames(
target.getProvider(RunfilesProvider.class).getDefaultRunfiles().getAllArtifacts()))
@@ -515,8 +513,8 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
ConfiguredTarget target = getConfiguredTarget("//test/skylark:cr");
- assertEquals("//test/skylark:cr", target.getLabel().toString());
- assertTrue(target.getProvider(RunfilesProvider.class).getDefaultRunfiles().isEmpty());
+ assertThat(target.getLabel().toString()).isEqualTo("//test/skylark:cr");
+ assertThat(target.getProvider(RunfilesProvider.class).getDefaultRunfiles().isEmpty()).isTrue();
assertThat(
ActionsTestUtil.baseArtifactNames(
target.getProvider(RunfilesProvider.class).getDataRunfiles().getAllArtifacts()))
@@ -543,7 +541,7 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
ConfiguredTarget target = getConfiguredTarget("//test/skylark:cr");
- assertEquals("//test/skylark:cr", target.getLabel().toString());
+ assertThat(target.getLabel().toString()).isEqualTo("//test/skylark:cr");
assertThat(
ActionsTestUtil.baseArtifactNames(
target.getProvider(RunfilesProvider.class).getDefaultRunfiles().getAllArtifacts()))
@@ -601,7 +599,7 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
ConfiguredTarget target = getConfiguredTarget("//test/skylark:cr");
- assertEquals("//test/skylark:cr", target.getLabel().toString());
+ assertThat(target.getLabel().toString()).isEqualTo("//test/skylark:cr");
InstrumentedFilesProvider provider = target.getProvider(InstrumentedFilesProvider.class);
assertWithMessage("InstrumentedFilesProvider should be set.").that(provider).isNotNull();
assertThat(ActionsTestUtil.baseArtifactNames(provider.getInstrumentedFiles())).isEmpty();
@@ -633,7 +631,7 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
ConfiguredTarget target = getConfiguredTarget("//test/skylark:cr");
- assertEquals("//test/skylark:cr", target.getLabel().toString());
+ assertThat(target.getLabel().toString()).isEqualTo("//test/skylark:cr");
InstrumentedFilesProvider provider = target.getProvider(InstrumentedFilesProvider.class);
assertWithMessage("InstrumentedFilesProvider should be set.").that(provider).isNotNull();
assertThat(ActionsTestUtil.baseArtifactNames(provider.getInstrumentedFiles()))
@@ -923,8 +921,8 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
"custom_rule(name = 'cr')");
ConfiguredTarget target = getConfiguredTarget("//test/skylark:cr");
- assertEquals(Runtime.NONE, target.get("o1"));
- assertEquals(MutableList.EMPTY, target.get("o2"));
+ assertThat(target.get("o1")).isEqualTo(Runtime.NONE);
+ assertThat(target.get("o2")).isEqualTo(MutableList.EMPTY);
}
@Test
@@ -1112,7 +1110,7 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
ConfiguredTarget target = getConfiguredTarget("//test/skylark:cr");
- assertEquals("//test/skylark:cr", target.getLabel().toString());
+ assertThat(target.getLabel().toString()).isEqualTo("//test/skylark:cr");
assertThat(
ActionsTestUtil.baseArtifactNames(
target.getProvider(FileProvider.class).getFilesToBuild()))
@@ -1353,9 +1351,9 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
} catch (BuildFileContainsErrorsException e) {
// The reason that this is an exception and not reported to the event handler is that the
// error is reported by the parent sky function, which we don't have here.
- assertThat(e.getMessage()).contains("Skylark import cycle");
- assertThat(e.getMessage()).contains("test/skylark:ext1.bzl");
- assertThat(e.getMessage()).contains("test/skylark:ext2.bzl");
+ assertThat(e).hasMessageThat().contains("Skylark import cycle");
+ assertThat(e).hasMessageThat().contains("test/skylark:ext1.bzl");
+ assertThat(e).hasMessageThat().contains("test/skylark:ext2.bzl");
}
}
@@ -1379,10 +1377,10 @@ public class SkylarkIntegrationTest extends BuildViewTestCase {
} catch (BuildFileContainsErrorsException e) {
// The reason that this is an exception and not reported to the event handler is that the
// error is reported by the parent sky function, which we don't have here.
- assertThat(e.getMessage()).contains("Skylark import cycle");
- assertThat(e.getMessage()).contains("//test/skylark:ext2.bzl");
- assertThat(e.getMessage()).contains("//test/skylark:ext3.bzl");
- assertThat(e.getMessage()).contains("//test/skylark:ext4.bzl");
+ assertThat(e).hasMessageThat().contains("Skylark import cycle");
+ assertThat(e).hasMessageThat().contains("//test/skylark:ext2.bzl");
+ assertThat(e).hasMessageThat().contains("//test/skylark:ext3.bzl");
+ assertThat(e).hasMessageThat().contains("//test/skylark:ext4.bzl");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleClassFunctionsTest.java b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleClassFunctionsTest.java
index 2be126be91..2b9166835f 100644
--- a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleClassFunctionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleClassFunctionsTest.java
@@ -15,10 +15,6 @@
package com.google.devtools.build.lib.skylark;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
@@ -109,8 +105,9 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
+ "There is already a built-in attribute 'tags' which cannot be overridden"
+ "' but got no error");
} catch (AssertionError e) {
- assertThat(e.getMessage()).contains(
- "There is already a built-in attribute 'tags' which cannot be overridden");
+ assertThat(e)
+ .hasMessageThat()
+ .contains("There is already a built-in attribute 'tags' which cannot be overridden");
}
}
@@ -124,8 +121,9 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
+ "There is already a built-in attribute 'name' which cannot be overridden"
+ "' but got no error");
} catch (AssertionError e) {
- assertThat(e.getMessage()).contains(
- "There is already a built-in attribute 'name' which cannot be overridden");
+ assertThat(e)
+ .hasMessageThat()
+ .contains("There is already a built-in attribute 'name' which cannot be overridden");
}
}
@@ -137,8 +135,8 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
" pass",
"exec_rule = rule(implementation = _impl, executable = True)",
"non_exec_rule = rule(implementation = _impl)");
- assertTrue(getRuleClass("exec_rule").hasAttr("args", Type.STRING_LIST));
- assertFalse(getRuleClass("non_exec_rule").hasAttr("args", Type.STRING_LIST));
+ assertThat(getRuleClass("exec_rule").hasAttr("args", Type.STRING_LIST)).isTrue();
+ assertThat(getRuleClass("non_exec_rule").hasAttr("args", Type.STRING_LIST)).isFalse();
}
private RuleClass getRuleClass(String name) throws Exception {
@@ -152,7 +150,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
@Test
public void testAttrWithOnlyType() throws Exception {
Attribute attr = buildAttribute("a1", "attr.string_list()");
- assertEquals(Type.STRING_LIST, attr.getType());
+ assertThat(attr.getType()).isEqualTo(Type.STRING_LIST);
}
private Attribute buildAttribute(String name, String... lines) throws Exception {
@@ -166,37 +164,37 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
@Test
public void testOutputListAttr() throws Exception {
Attribute attr = buildAttribute("a1", "attr.output_list()");
- assertEquals(BuildType.OUTPUT_LIST, attr.getType());
+ assertThat(attr.getType()).isEqualTo(BuildType.OUTPUT_LIST);
}
@Test
public void testIntListAttr() throws Exception {
Attribute attr = buildAttribute("a1", "attr.int_list()");
- assertEquals(Type.INTEGER_LIST, attr.getType());
+ assertThat(attr.getType()).isEqualTo(Type.INTEGER_LIST);
}
@Test
public void testOutputAttr() throws Exception {
Attribute attr = buildAttribute("a1", "attr.output()");
- assertEquals(BuildType.OUTPUT, attr.getType());
+ assertThat(attr.getType()).isEqualTo(BuildType.OUTPUT);
}
@Test
public void testStringDictAttr() throws Exception {
Attribute attr = buildAttribute("a1", "attr.string_dict(default = {'a': 'b'})");
- assertEquals(Type.STRING_DICT, attr.getType());
+ assertThat(attr.getType()).isEqualTo(Type.STRING_DICT);
}
@Test
public void testStringListDictAttr() throws Exception {
Attribute attr = buildAttribute("a1", "attr.string_list_dict(default = {'a': ['b', 'c']})");
- assertEquals(Type.STRING_LIST_DICT, attr.getType());
+ assertThat(attr.getType()).isEqualTo(Type.STRING_LIST_DICT);
}
@Test
public void testAttrAllowedFileTypesAnyFile() throws Exception {
Attribute attr = buildAttribute("a1", "attr.label_list(allow_files = True)");
- assertEquals(FileTypeSet.ANY_FILE, attr.getAllowedFileTypesPredicate());
+ assertThat(attr.getAllowedFileTypesPredicate()).isEqualTo(FileTypeSet.ANY_FILE);
}
@Test
@@ -216,24 +214,24 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
@Test
public void testAttrWithList() throws Exception {
Attribute attr = buildAttribute("a1", "attr.label_list(allow_files = ['.xml'])");
- assertTrue(attr.getAllowedFileTypesPredicate().apply("a.xml"));
- assertFalse(attr.getAllowedFileTypesPredicate().apply("a.txt"));
- assertFalse(attr.isSingleArtifact());
+ assertThat(attr.getAllowedFileTypesPredicate().apply("a.xml")).isTrue();
+ assertThat(attr.getAllowedFileTypesPredicate().apply("a.txt")).isFalse();
+ assertThat(attr.isSingleArtifact()).isFalse();
}
@Test
public void testAttrSingleFileWithList() throws Exception {
Attribute attr = buildAttribute("a1", "attr.label(allow_single_file = ['.xml'])");
- assertTrue(attr.getAllowedFileTypesPredicate().apply("a.xml"));
- assertFalse(attr.getAllowedFileTypesPredicate().apply("a.txt"));
- assertTrue(attr.isSingleArtifact());
+ assertThat(attr.getAllowedFileTypesPredicate().apply("a.xml")).isTrue();
+ assertThat(attr.getAllowedFileTypesPredicate().apply("a.txt")).isFalse();
+ assertThat(attr.isSingleArtifact()).isTrue();
}
@Test
public void testAttrWithSkylarkFileType() throws Exception {
Attribute attr = buildAttribute("a1", "attr.label_list(allow_files = FileType(['.xml']))");
- assertTrue(attr.getAllowedFileTypesPredicate().apply("a.xml"));
- assertFalse(attr.getAllowedFileTypesPredicate().apply("a.txt"));
+ assertThat(attr.getAllowedFileTypesPredicate().apply("a.xml")).isTrue();
+ assertThat(attr.getAllowedFileTypesPredicate().apply("a.txt")).isFalse();
}
private static SkylarkProviderIdentifier legacy(String legacyId) {
@@ -435,13 +433,13 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
public void testAttrAllowedRuleClassesSpecificRuleClasses() throws Exception {
Attribute attr = buildAttribute("a",
"attr.label_list(allow_rules = ['java_binary'], allow_files = True)");
- assertTrue(attr.getAllowedRuleClassesPredicate().apply(ruleClass("java_binary")));
- assertFalse(attr.getAllowedRuleClassesPredicate().apply(ruleClass("genrule")));
+ assertThat(attr.getAllowedRuleClassesPredicate().apply(ruleClass("java_binary"))).isTrue();
+ assertThat(attr.getAllowedRuleClassesPredicate().apply(ruleClass("genrule"))).isFalse();
}
@Test
public void testAttrDefaultValue() throws Exception {
Attribute attr = buildAttribute("a1", "attr.string(default = 'some value')");
- assertEquals("some value", attr.getDefaultValueForTesting());
+ assertThat(attr.getDefaultValueForTesting()).isEqualTo("some value");
}
@Test
@@ -456,22 +454,22 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
@Test
public void testAttrMandatory() throws Exception {
Attribute attr = buildAttribute("a1", "attr.string(mandatory=True)");
- assertTrue(attr.isMandatory());
- assertFalse(attr.isNonEmpty());
+ assertThat(attr.isMandatory()).isTrue();
+ assertThat(attr.isNonEmpty()).isFalse();
}
@Test
public void testAttrNonEmpty() throws Exception {
Attribute attr = buildAttribute("a1", "attr.string_list(non_empty=True)");
- assertTrue(attr.isNonEmpty());
- assertFalse(attr.isMandatory());
+ assertThat(attr.isNonEmpty()).isTrue();
+ assertThat(attr.isMandatory()).isFalse();
}
@Test
public void testAttrAllowEmpty() throws Exception {
Attribute attr = buildAttribute("a1", "attr.string_list(allow_empty=False)");
- assertTrue(attr.isNonEmpty());
- assertFalse(attr.isMandatory());
+ assertThat(attr.isNonEmpty()).isTrue();
+ assertThat(attr.isMandatory()).isFalse();
}
@Test
@@ -483,19 +481,19 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
@Test
public void testAttrCfg() throws Exception {
Attribute attr = buildAttribute("a1", "attr.label(cfg = 'host', allow_files = True)");
- assertEquals(ConfigurationTransition.HOST, attr.getConfigurationTransition());
+ assertThat(attr.getConfigurationTransition()).isEqualTo(ConfigurationTransition.HOST);
}
@Test
public void testAttrCfgData() throws Exception {
Attribute attr = buildAttribute("a1", "attr.label(cfg = 'data', allow_files = True)");
- assertEquals(ConfigurationTransition.DATA, attr.getConfigurationTransition());
+ assertThat(attr.getConfigurationTransition()).isEqualTo(ConfigurationTransition.DATA);
}
@Test
public void testAttrCfgTarget() throws Exception {
Attribute attr = buildAttribute("a1", "attr.label(cfg = 'target', allow_files = True)");
- assertEquals(ConfigurationTransition.NONE, attr.getConfigurationTransition());
+ assertThat(attr.getConfigurationTransition()).isEqualTo(ConfigurationTransition.NONE);
}
@Test
@@ -518,7 +516,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
public void testRuleImplementation() throws Exception {
evalAndExport("def impl(ctx): return None", "rule1 = rule(impl)");
RuleClass c = ((RuleFunction) lookup("rule1")).getRuleClass();
- assertEquals("impl", c.getConfiguredTargetFunction().getName());
+ assertThat(c.getConfiguredTargetFunction().getName()).isEqualTo("impl");
}
@Test
@@ -537,7 +535,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
public void testRuleAddAttribute() throws Exception {
evalAndExport("def impl(ctx): return None", "r1 = rule(impl, attrs={'a1': attr.string()})");
RuleClass c = ((RuleFunction) lookup("r1")).getRuleClass();
- assertTrue(c.hasAttr("a1", Type.STRING));
+ assertThat(c.hasAttr("a1", Type.STRING)).isTrue();
}
protected void evalAndExport(String... lines) throws Exception {
@@ -577,7 +575,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
public void testOutputToGenfiles() throws Exception {
evalAndExport("def impl(ctx): pass", "r1 = rule(impl, output_to_genfiles=True)");
RuleClass c = ((RuleFunction) lookup("r1")).getRuleClass();
- assertFalse(c.hasBinaryOutput());
+ assertThat(c.hasBinaryOutput()).isFalse();
}
@Test
@@ -590,8 +588,8 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
" 'a2': attr.int()",
"})");
RuleClass c = ((RuleFunction) lookup("r1")).getRuleClass();
- assertTrue(c.hasAttr("a1", BuildType.LABEL_LIST));
- assertTrue(c.hasAttr("a2", Type.INTEGER));
+ assertThat(c.hasAttr("a1", BuildType.LABEL_LIST)).isTrue();
+ assertThat(c.hasAttr("a2", Type.INTEGER)).isTrue();
}
@Test
public void testRuleAttributeFlag() throws Exception {
@@ -599,7 +597,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
"def impl(ctx): return None",
"r1 = rule(impl, attrs = {'a1': attr.string(mandatory=True)})");
RuleClass c = ((RuleFunction) lookup("r1")).getRuleClass();
- assertTrue(c.getAttributeByName("a1").isMandatory());
+ assertThat(c.getAttributeByName("a1").isMandatory()).isTrue();
}
@Test
@@ -609,7 +607,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
"r1 = rule(impl, outputs = {'a': 'a.txt'})");
RuleClass c = ((RuleFunction) lookup("r1")).getRuleClass();
ImplicitOutputsFunction function = c.getDefaultImplicitOutputsFunction();
- assertEquals("a.txt", Iterables.getOnlyElement(function.getImplicitOutputs(null)));
+ assertThat(function.getImplicitOutputs(null)).containsExactly("a.txt");
}
@Test
@@ -649,7 +647,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
public void testLabel() throws Exception {
Object result = evalRuleClassCode("Label('//foo/foo:foo')");
assertThat(result).isInstanceOf(Label.class);
- assertEquals("//foo/foo:foo", result.toString());
+ assertThat(result.toString()).isEqualTo("//foo/foo:foo");
}
@Test
@@ -657,16 +655,16 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
Object l1 = evalRuleClassCode("Label('//foo/foo:foo')");
// Implicitly creates a new pkgContext and environment, yet labels should be the same.
Object l2 = evalRuleClassCode("Label('//foo/foo:foo')");
- assertSame(l2, l1);
+ assertThat(l1).isSameAs(l2);
}
@Test
public void testLabelNameAndPackage() throws Exception {
Object result = evalRuleClassCode("Label('//foo/bar:baz').name");
- assertEquals("baz", result);
+ assertThat(result).isEqualTo("baz");
// NB: implicitly creates a new pkgContext and environments, yet labels should be the same.
result = evalRuleClassCode("Label('//foo/bar:baz').package");
- assertEquals("foo/bar", result);
+ assertThat(result).isEqualTo("foo/bar");
}
@Test
@@ -678,7 +676,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
RuleClass c = ((RuleFunction) lookup("r1")).getRuleClass();
Attribute a = c.getAttributeByName("a1");
assertThat(a.getDefaultValueForTesting()).isInstanceOf(Label.class);
- assertEquals("//foo:foo", a.getDefaultValueForTesting().toString());
+ assertThat(a.getDefaultValueForTesting().toString()).isEqualTo("//foo:foo");
}
@Test
@@ -688,29 +686,30 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
"r1 = rule(impl, attrs = {'a1': attr.int(default = 40+2)})");
RuleClass c = ((RuleFunction) lookup("r1")).getRuleClass();
Attribute a = c.getAttributeByName("a1");
- assertEquals(42, a.getDefaultValueForTesting());
+ assertThat(a.getDefaultValueForTesting()).isEqualTo(42);
}
@Test
public void testFileType() throws Exception {
Object result = evalRuleClassCode("FileType(['.css'])");
SkylarkFileType fts = (SkylarkFileType) result;
- assertEquals(ImmutableList.of(".css"), fts.getExtensions());
+ assertThat(fts.getExtensions()).isEqualTo(ImmutableList.of(".css"));
}
@Test
public void testRuleInheritsBaseRuleAttributes() throws Exception {
evalAndExport("def impl(ctx): return None", "r1 = rule(impl)");
RuleClass c = ((RuleFunction) lookup("r1")).getRuleClass();
- assertTrue(c.hasAttr("tags", Type.STRING_LIST));
- assertTrue(c.hasAttr("visibility", BuildType.NODEP_LABEL_LIST));
- assertTrue(c.hasAttr("deprecation", Type.STRING));
- assertTrue(c.hasAttr(":action_listener", BuildType.LABEL_LIST)); // required for extra actions
+ assertThat(c.hasAttr("tags", Type.STRING_LIST)).isTrue();
+ assertThat(c.hasAttr("visibility", BuildType.NODEP_LABEL_LIST)).isTrue();
+ assertThat(c.hasAttr("deprecation", Type.STRING)).isTrue();
+ assertThat(c.hasAttr(":action_listener", BuildType.LABEL_LIST))
+ .isTrue(); // required for extra actions
}
private void checkTextMessage(String from, String... lines) throws Exception {
Object result = evalRuleClassCode(from);
- assertEquals(Joiner.on("\n").join(lines) + "\n", result);
+ assertThat(result).isEqualTo(Joiner.on("\n").join(lines) + "\n");
}
@Test
@@ -771,7 +770,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
private void checkJson(String from, String expected) throws Exception {
Object result = evalRuleClassCode(from);
- assertEquals(expected, result);
+ assertThat(result).isEqualTo(expected);
}
@Test
@@ -826,8 +825,8 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
@Test
public void testLabelGetRelative() throws Exception {
- assertEquals("//foo:baz", eval("Label('//foo:bar').relative('baz')").toString());
- assertEquals("//baz:qux", eval("Label('//foo:bar').relative('//baz:qux')").toString());
+ assertThat(eval("Label('//foo:bar').relative('baz')").toString()).isEqualTo("//foo:baz");
+ assertThat(eval("Label('//foo:bar').relative('//baz:qux')").toString()).isEqualTo("//baz:qux");
}
@Test
@@ -872,28 +871,28 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
// TODO(fwe): cannot be handled by current testing suite
eval("x = struct(a = 1, b = 2)");
ClassObject x = (ClassObject) lookup("x");
- assertEquals(1, x.getValue("a"));
- assertEquals(2, x.getValue("b"));
+ assertThat(x.getValue("a")).isEqualTo(1);
+ assertThat(x.getValue("b")).isEqualTo(2);
}
@Test
public void testStructEquality() throws Exception {
- assertTrue((Boolean) eval("struct(a = 1, b = 2) == struct(b = 2, a = 1)"));
- assertFalse((Boolean) eval("struct(a = 1) == struct(a = 1, b = 2)"));
- assertFalse((Boolean) eval("struct(a = 1, b = 2) == struct(a = 1)"));
+ assertThat((Boolean) eval("struct(a = 1, b = 2) == struct(b = 2, a = 1)")).isTrue();
+ assertThat((Boolean) eval("struct(a = 1) == struct(a = 1, b = 2)")).isFalse();
+ assertThat((Boolean) eval("struct(a = 1, b = 2) == struct(a = 1)")).isFalse();
// Compare a recursive object to itself to make sure reference equality is checked
- assertTrue((Boolean) eval("s = (struct(a = 1, b = [])); s.b.append(s); s == s"));
- assertFalse((Boolean) eval("struct(a = 1, b = 2) == struct(a = 1, b = 3)"));
- assertFalse((Boolean) eval("struct(a = 1) == [1]"));
- assertFalse((Boolean) eval("[1] == struct(a = 1)"));
- assertTrue((Boolean) eval("struct() == struct()"));
- assertFalse((Boolean) eval("struct() == struct(a = 1)"));
+ assertThat((Boolean) eval("s = (struct(a = 1, b = [])); s.b.append(s); s == s")).isTrue();
+ assertThat((Boolean) eval("struct(a = 1, b = 2) == struct(a = 1, b = 3)")).isFalse();
+ assertThat((Boolean) eval("struct(a = 1) == [1]")).isFalse();
+ assertThat((Boolean) eval("[1] == struct(a = 1)")).isFalse();
+ assertThat((Boolean) eval("struct() == struct()")).isTrue();
+ assertThat((Boolean) eval("struct() == struct(a = 1)")).isFalse();
eval("foo = provider(); bar = provider()");
- assertFalse((Boolean) eval("struct(a = 1) == foo(a = 1)"));
- assertFalse((Boolean) eval("foo(a = 1) == struct(a = 1)"));
- assertFalse((Boolean) eval("foo(a = 1) == bar(a = 1)"));
- assertTrue((Boolean) eval("foo(a = 1) == foo(a = 1)"));
+ assertThat((Boolean) eval("struct(a = 1) == foo(a = 1)")).isFalse();
+ assertThat((Boolean) eval("foo(a = 1) == struct(a = 1)")).isFalse();
+ assertThat((Boolean) eval("foo(a = 1) == bar(a = 1)")).isFalse();
+ assertThat((Boolean) eval("foo(a = 1) == foo(a = 1)")).isTrue();
}
@Test
@@ -950,7 +949,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
"y = struct(c = 1, d = 2)",
"z = x + y\n");
SkylarkClassObject z = (SkylarkClassObject) lookup("z");
- assertEquals(ImmutableSet.of("a", "b", "c", "d"), z.getKeys());
+ assertThat(z.getKeys()).isEqualTo(ImmutableSet.of("a", "b", "c", "d"));
}
@Test
@@ -960,10 +959,10 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
"y = struct(c = 1, d = 2)",
"z = x + y\n");
SkylarkClassObject z = (SkylarkClassObject) lookup("z");
- assertEquals(1, z.getValue("a"));
- assertEquals(2, z.getValue("b"));
- assertEquals(1, z.getValue("c"));
- assertEquals(2, z.getValue("d"));
+ assertThat(z.getValue("a")).isEqualTo(1);
+ assertThat(z.getValue("b")).isEqualTo(2);
+ assertThat(z.getValue("c")).isEqualTo(1);
+ assertThat(z.getValue("d")).isEqualTo(2);
}
@Test
@@ -982,10 +981,10 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
" return x",
"x = func()");
SkylarkClassObject x = (SkylarkClassObject) lookup("x");
- assertEquals(1, x.getValue("a"));
- assertEquals(2, x.getValue("b"));
- assertEquals(1, x.getValue("c"));
- assertEquals(2, x.getValue("d"));
+ assertThat(x.getValue("a")).isEqualTo(1);
+ assertThat(x.getValue("b")).isEqualTo(2);
+ assertThat(x.getValue("c")).isEqualTo(1);
+ assertThat(x.getValue("d")).isEqualTo(2);
}
@Test
@@ -1093,7 +1092,7 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
@Test
public void testStructMutabilityShallow() throws Exception {
- assertTrue(EvalUtils.isImmutable(makeStruct("a", 1)));
+ assertThat(EvalUtils.isImmutable(makeStruct("a", 1))).isTrue();
}
private static MutableList<Object> makeList(Environment env) {
@@ -1102,13 +1101,13 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
@Test
public void testStructMutabilityDeep() throws Exception {
- assertTrue(EvalUtils.isImmutable(Tuple.<Object>of(makeList(null))));
- assertTrue(EvalUtils.isImmutable(makeStruct("a", makeList(null))));
- assertTrue(EvalUtils.isImmutable(makeBigStruct(null)));
+ assertThat(EvalUtils.isImmutable(Tuple.<Object>of(makeList(null)))).isTrue();
+ assertThat(EvalUtils.isImmutable(makeStruct("a", makeList(null)))).isTrue();
+ assertThat(EvalUtils.isImmutable(makeBigStruct(null))).isTrue();
- assertFalse(EvalUtils.isImmutable(Tuple.<Object>of(makeList(ev.getEnvironment()))));
- assertFalse(EvalUtils.isImmutable(makeStruct("a", makeList(ev.getEnvironment()))));
- assertFalse(EvalUtils.isImmutable(makeBigStruct(ev.getEnvironment())));
+ assertThat(EvalUtils.isImmutable(Tuple.<Object>of(makeList(ev.getEnvironment())))).isFalse();
+ assertThat(EvalUtils.isImmutable(makeStruct("a", makeList(ev.getEnvironment())))).isFalse();
+ assertThat(EvalUtils.isImmutable(makeBigStruct(ev.getEnvironment()))).isFalse();
}
@Test
@@ -1374,8 +1373,9 @@ public class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
createRuleContext("//third_party/foo:main");
Assert.fail();
} catch (AssertionError e) {
- assertThat(e.getMessage()).contains("cfg parameter is mandatory when executable=True is "
- + "provided.");
+ assertThat(e)
+ .hasMessageThat()
+ .contains("cfg parameter is mandatory when executable=True is " + "provided.");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleContextTest.java b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleContextTest.java
index c4b01a9562..0330ccc863 100644
--- a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleContextTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleContextTest.java
@@ -15,11 +15,6 @@
package com.google.devtools.build.lib.skylark;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -224,7 +219,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
"my_other_rule = rule(implementation = my_other_rule_impl, ",
" attrs = { 'srcs' : attr.label_list(allow_files=True)})");
reporter.removeHandler(failFastHandler);
- assertNotNull(getConfiguredTarget("//test:skyrule1"));
+ assertThat(getConfiguredTarget("//test:skyrule1")).isNotNull();
try {
createRuleContext("//test:skyrule2");
@@ -258,7 +253,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
"my_other_rule = rule(implementation = my_other_rule_impl, ",
" attrs = { 'srcs' : attr.label_list(allow_files=True)})");
reporter.removeHandler(failFastHandler);
- assertNotNull(getConfiguredTarget("//test:skyrule1"));
+ assertThat(getConfiguredTarget("//test:skyrule1")).isNotNull();
try {
createRuleContext("//test:skyrule2");
@@ -419,10 +414,10 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
private void assertArtifactList(Object result, List<String> artifacts) {
assertThat(result).isInstanceOf(SkylarkList.class);
SkylarkList resultList = (SkylarkList) result;
- assertEquals(artifacts.size(), resultList.size());
+ assertThat(resultList).hasSize(artifacts.size());
int i = 0;
for (String artifact : artifacts) {
- assertEquals(artifact, ((Artifact) resultList.get(i++)).getFilename());
+ assertThat(((Artifact) resultList.get(i++)).getFilename()).isEqualTo(artifact);
}
}
@@ -432,9 +427,9 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
Object result = evalRuleContextCode(ruleContext, "ruleContext.attr.srcs");
// Check for a known provider
TransitiveInfoCollection tic1 = (TransitiveInfoCollection) ((SkylarkList) result).get(0);
- assertNotNull(JavaProvider.getProvider(JavaSourceJarsProvider.class, tic1));
+ assertThat(JavaProvider.getProvider(JavaSourceJarsProvider.class, tic1)).isNotNull();
// Check an unimplemented provider too
- assertNull(tic1.get(PyCommon.PYTHON_SKYLARK_PROVIDER_NAME));
+ assertThat(tic1.get(PyCommon.PYTHON_SKYLARK_PROVIDER_NAME)).isNull();
}
@Test
@@ -443,7 +438,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
Object result = evalRuleContextCode(ruleContext, "ruleContext.attr.srcjar");
TransitiveInfoCollection tic = (TransitiveInfoCollection) result;
assertThat(tic).isInstanceOf(FileConfiguredTarget.class);
- assertEquals("asr-src.jar", tic.getLabel().getName());
+ assertThat(tic.getLabel().getName()).isEqualTo("asr-src.jar");
}
@Test
@@ -495,8 +490,8 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
"test_rule('a', 'does not exist')",
"test_rule('b', 'BUILD')");
- assertNotNull(getConfiguredTarget("//test:a"));
- assertNotNull(getConfiguredTarget("//test:b"));
+ assertThat(getConfiguredTarget("//test:a")).isNotNull();
+ assertThat(getConfiguredTarget("//test:b")).isNotNull();
}
@Test
@@ -574,28 +569,28 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
public void testGetRuleAttributeListValue() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.attr.outs");
- assertEquals(1, ((SkylarkList) result).size());
+ assertThat(((SkylarkList) result)).hasSize(1);
}
@Test
public void testGetRuleAttributeListValueNoGet() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.attr.outs");
- assertEquals(1, ((SkylarkList) result).size());
+ assertThat(((SkylarkList) result)).hasSize(1);
}
@Test
public void testGetRuleAttributeStringTypeValue() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.attr.cmd");
- assertEquals("dummy_cmd", (String) result);
+ assertThat((String) result).isEqualTo("dummy_cmd");
}
@Test
public void testGetRuleAttributeStringTypeValueNoGet() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.attr.cmd");
- assertEquals("dummy_cmd", (String) result);
+ assertThat((String) result).isEqualTo("dummy_cmd");
}
@Test
@@ -608,7 +603,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
public void testGetLabel() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.label");
- assertEquals("//foo:foo", ((Label) result).toString());
+ assertThat(((Label) result).toString()).isEqualTo("//foo:foo");
}
@Test
@@ -652,14 +647,14 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
public void testOutputs() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:bar");
Iterable<?> result = (Iterable<?>) evalRuleContextCode(ruleContext, "ruleContext.outputs.outs");
- assertEquals("d.txt", ((Artifact) Iterables.getOnlyElement(result)).getFilename());
+ assertThat(((Artifact) Iterables.getOnlyElement(result)).getFilename()).isEqualTo("d.txt");
}
@Test
public void testSkylarkRuleContextStr() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "'%s' % ruleContext");
- assertEquals("//foo:foo", result);
+ assertThat(result).isEqualTo("//foo:foo");
}
@Test
@@ -674,7 +669,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result =
evalRuleContextCode(ruleContext, "ruleContext.check_placeholders('%{name}', ['name'])");
- assertEquals(true, result);
+ assertThat(result).isEqualTo(true);
}
@Test
@@ -682,7 +677,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result =
evalRuleContextCode(ruleContext, "ruleContext.check_placeholders('%{name}', ['abc'])");
- assertEquals(false, result);
+ assertThat(result).isEqualTo(false);
}
@Test
@@ -691,7 +686,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
Object result =
evalRuleContextCode(
ruleContext, "ruleContext.expand_make_variables('cmd', '$(ABC)', {'ABC': 'DEF'})");
- assertEquals("DEF", result);
+ assertThat(result).isEqualTo("DEF");
}
@Test
@@ -699,14 +694,14 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result =
evalRuleContextCode(ruleContext, "ruleContext.expand_make_variables('cmd', '$$ABC', {})");
- assertEquals("$ABC", result);
+ assertThat(result).isEqualTo("$ABC");
}
@Test
public void testConfiguration() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.configuration");
- assertSame(result, ruleContext.getRuleContext().getConfiguration());
+ assertThat(ruleContext.getRuleContext().getConfiguration()).isSameAs(result);
}
@Test
@@ -721,7 +716,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
public void testHostConfiguration() throws Exception {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.host_configuration");
- assertSame(result, ruleContext.getRuleContext().getHostConfiguration());
+ assertThat(ruleContext.getRuleContext().getHostConfiguration()).isSameAs(result);
}
@Test
@@ -730,7 +725,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
assertThat(ruleClassProvider.getRunfilesPrefix()).isNotEmpty();
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.workspace_name");
- assertEquals(result, ruleClassProvider.getRunfilesPrefix());
+ assertThat(ruleClassProvider.getRunfilesPrefix()).isEqualTo(result);
}
@Test
@@ -741,7 +736,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
ruleContext,
"ruleContext.new_file(ruleContext.genfiles_dir," + " 'a/b.txt')");
PathFragment fragment = ((Artifact) result).getRootRelativePath();
- assertEquals("foo/a/b.txt", fragment.getPathString());
+ assertThat(fragment.getPathString()).isEqualTo("foo/a/b.txt");
}
@Test
@@ -749,7 +744,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
SkylarkRuleContext ruleContext = createRuleContext("//foo:foo");
Object result = evalRuleContextCode(ruleContext, "ruleContext.new_file('a/b.txt')");
PathFragment fragment = ((Artifact) result).getRootRelativePath();
- assertEquals("foo/a/b.txt", fragment.getPathString());
+ assertThat(fragment.getPathString()).isEqualTo("foo/a/b.txt");
}
@Test
@@ -759,8 +754,8 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
evalRuleContextCode(ruleContext, "ruleContext.experimental_new_directory('a/b')");
Artifact artifact = (Artifact) result;
PathFragment fragment = artifact.getRootRelativePath();
- assertEquals("foo/a/b", fragment.getPathString());
- assertTrue(artifact.isTreeArtifact());
+ assertThat(fragment.getPathString()).isEqualTo("foo/a/b");
+ assertThat(artifact.isTreeArtifact()).isTrue();
}
@Test
@@ -773,8 +768,8 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
+ "ruleContext.experimental_new_directory('c', sibling=b)");
Artifact artifact = (Artifact) result;
PathFragment fragment = artifact.getRootRelativePath();
- assertEquals("foo/a/c", fragment.getPathString());
- assertTrue(artifact.isTreeArtifact());
+ assertThat(fragment.getPathString()).isEqualTo("foo/a/c");
+ assertThat(artifact.isTreeArtifact()).isTrue();
}
@Test
@@ -786,7 +781,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
"ruleContext.new_file(ruleContext.bin_dir,"
+ "ruleContext.files.tools[0], '.params')");
PathFragment fragment = ((Artifact) result).getRootRelativePath();
- assertEquals("foo/t.exe.params", fragment.getPathString());
+ assertThat(fragment.getPathString()).isEqualTo("foo/t.exe.params");
}
@Test
@@ -798,7 +793,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
"ruleContext.new_file(ruleContext.files.tools[0], "
+ "ruleContext.files.tools[0].basename + '.params')");
PathFragment fragment = ((Artifact) result).getRootRelativePath();
- assertEquals("foo/t.exe.params", fragment.getPathString());
+ assertThat(fragment.getPathString()).isEqualTo("foo/t.exe.params");
}
@Test
@@ -1363,7 +1358,7 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
ruleWithInitContext, "list(ruleContext.attr.dep.default_runfiles.empty_filenames)");
assertThat(noEmptyFilenames).isInstanceOf(SkylarkList.class);
SkylarkList noEmptyFilenamesList = (SkylarkList) noEmptyFilenames;
- assertThat(noEmptyFilenamesList).containsExactly().inOrder();
+ assertThat(noEmptyFilenamesList).isEmpty();
}
@Test
@@ -1826,9 +1821,12 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
getConfiguredTarget("//test:main");
fail("Should have been unable to access dep_ctx." + attribute);
} catch (AssertionError e) {
- assertThat(e.getMessage()).contains("cannot access field or method '"
- + attribute.split("\\(")[0]
- + "' of rule context for '//test:dep' outside of its own rule implementation function");
+ assertThat(e)
+ .hasMessageThat()
+ .contains("cannot access field or method '"
+ + attribute.split("\\(")[0]
+ + "' of rule context for '//test:dep' outside of its own rule implementation "
+ + "function");
}
}
}
@@ -1871,9 +1869,12 @@ public class SkylarkRuleContextTest extends SkylarkTestCase {
getConfiguredTarget("//test:main");
fail("Should have been unable to access dep." + attribute);
} catch (AssertionError e) {
- assertThat(e.getMessage()).contains("cannot access field or method '"
- + attribute.split("\\(")[0]
- + "' of rule context for '//test:dep' outside of its own rule implementation function");
+ assertThat(e)
+ .hasMessageThat()
+ .contains("cannot access field or method '"
+ + attribute.split("\\(")[0]
+ + "' of rule context for '//test:dep' outside of its own rule implementation "
+ + "function");
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleImplementationFunctionsTest.java b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleImplementationFunctionsTest.java
index 138215fb28..0dc5e6b4ea 100644
--- a/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleImplementationFunctionsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skylark/SkylarkRuleImplementationFunctionsTest.java
@@ -15,14 +15,11 @@
package com.google.devtools.build.lib.skylark;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.Artifact;
@@ -157,7 +154,7 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
optionalKey);
}
};
- assertFalse(mockFunc.isConfigured());
+ assertThat(mockFunc.isConfigured()).isFalse();
mockFunc.configure(
SkylarkRuleImplementationFunctionsTest.class
.getDeclaredField("mockFunc")
@@ -187,20 +184,20 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
public void testSkylarkFunctionPosArgs() throws Exception {
setupSkylarkFunction("a = mock('a', 'b', mandatory_key='c')");
Map<?, ?> params = (Map<?, ?>) lookup("a");
- assertEquals("a", params.get("mandatory"));
- assertEquals("b", params.get("optional"));
- assertEquals("c", params.get("mandatory_key"));
- assertEquals("x", params.get("optional_key"));
+ assertThat(params.get("mandatory")).isEqualTo("a");
+ assertThat(params.get("optional")).isEqualTo("b");
+ assertThat(params.get("mandatory_key")).isEqualTo("c");
+ assertThat(params.get("optional_key")).isEqualTo("x");
}
@Test
public void testSkylarkFunctionKwArgs() throws Exception {
setupSkylarkFunction("a = mock(optional='b', mandatory='a', mandatory_key='c')");
Map<?, ?> params = (Map<?, ?>) lookup("a");
- assertEquals("a", params.get("mandatory"));
- assertEquals("b", params.get("optional"));
- assertEquals("c", params.get("mandatory_key"));
- assertEquals("x", params.get("optional_key"));
+ assertThat(params.get("mandatory")).isEqualTo("a");
+ assertThat(params.get("optional")).isEqualTo("b");
+ assertThat(params.get("mandatory_key")).isEqualTo("c");
+ assertThat(params.get("optional_key")).isEqualTo("x");
}
@Test
@@ -257,9 +254,9 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
assertArtifactFilenames(action.getOutputs(), "a.txt", "b.img");
MoreAsserts.assertContainsSublist(
action.getArguments(), "-c", "dummy_command", "", "--a", "--b");
- assertEquals("DummyMnemonic", action.getMnemonic());
- assertEquals("dummy_message", action.getProgressMessage());
- assertEquals(targetConfig.getLocalShellEnvironment(), action.getEnvironment());
+ assertThat(action.getMnemonic()).isEqualTo("DummyMnemonic");
+ assertThat(action.getProgressMessage()).isEqualTo("dummy_message");
+ assertThat(action.getEnvironment()).isEqualTo(targetConfig.getLocalShellEnvironment());
}
@Test
@@ -331,8 +328,8 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
(SpawnAction)
Iterables.getOnlyElement(
ruleContext.getRuleContext().getAnalysisEnvironment().getRegisteredActions());
- assertEquals(ImmutableMap.of("a", "b"), action.getEnvironment());
- assertEquals(ImmutableMap.of("a", "b"), action.getExecutionInfo());
+ assertThat(action.getEnvironment()).containsExactly("a", "b");
+ assertThat(action.getExecutionInfo()).containsExactly("a", "b");
}
@Test
@@ -400,9 +397,10 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
(FileWriteAction)
Iterables.getOnlyElement(
ruleContext.getRuleContext().getAnalysisEnvironment().getRegisteredActions());
- assertEquals("foo/a.txt", Iterables.getOnlyElement(action.getOutputs()).getExecPathString());
- assertEquals("hello world", action.getFileContents());
- assertFalse(action.makeExecutable());
+ assertThat(Iterables.getOnlyElement(action.getOutputs()).getExecPathString())
+ .isEqualTo("foo/a.txt");
+ assertThat(action.getFileContents()).isEqualTo("hello world");
+ assertThat(action.makeExecutable()).isFalse();
}
@Test
@@ -509,10 +507,11 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
private void assertMatches(String description, String expectedPattern, String computedValue)
throws Exception {
- assertTrue(
- Printer.format(
- "%s %r did not match pattern '%s'", description, computedValue, expectedPattern),
- Pattern.matches(expectedPattern, computedValue));
+ assertWithMessage(
+ Printer.format(
+ "%s %r did not match pattern '%s'", description, computedValue, expectedPattern))
+ .that(Pattern.matches(expectedPattern, computedValue))
+ .isTrue();
}
@Test
@@ -621,11 +620,13 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
" output = ruleContext.files.srcs[1],",
" substitutions = {'a': 'b'},",
" executable = False)");
- assertEquals("foo/a.txt", Iterables.getOnlyElement(action.getInputs()).getExecPathString());
- assertEquals("foo/b.img", Iterables.getOnlyElement(action.getOutputs()).getExecPathString());
- assertEquals("a", Iterables.getOnlyElement(action.getSubstitutions()).getKey());
- assertEquals("b", Iterables.getOnlyElement(action.getSubstitutions()).getValue());
- assertFalse(action.makeExecutable());
+ assertThat(Iterables.getOnlyElement(action.getInputs()).getExecPathString())
+ .isEqualTo("foo/a.txt");
+ assertThat(Iterables.getOnlyElement(action.getOutputs()).getExecPathString())
+ .isEqualTo("foo/b.img");
+ assertThat(Iterables.getOnlyElement(action.getSubstitutions()).getKey()).isEqualTo("a");
+ assertThat(Iterables.getOnlyElement(action.getSubstitutions()).getValue()).isEqualTo("b");
+ assertThat(action.makeExecutable()).isFalse();
}
/**
@@ -719,9 +720,8 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
ruleContext,
"artifacts = ruleContext.files.srcs",
"ruleContext.runfiles(files = artifacts)");
- assertEquals(
- ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)),
- ImmutableList.of("a.txt", "b.img"));
+ assertThat(ImmutableList.of("a.txt", "b.img"))
+ .isEqualTo(ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)));
}
@Test
@@ -732,9 +732,8 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
ruleContext,
"ftb = depset() + ruleContext.files.srcs",
"ruleContext.runfiles(transitive_files = ftb)");
- assertEquals(
- ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)),
- ImmutableList.of("a.txt", "b.img"));
+ assertThat(ImmutableList.of("a.txt", "b.img"))
+ .isEqualTo(ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)));
}
@Test
@@ -748,9 +747,8 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
// is an ImmutableList and Skylark interprets it as a tuple.
"ruleContext.runfiles(collect_default = True, files = artifacts)");
// From DEFAULT only libjl.jar comes, see testRunfilesAddFromDependencies().
- assertEquals(
- ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)),
- ImmutableList.of("libjl.jar", "gl.a", "gl.gcgox"));
+ assertThat(ImmutableList.of("libjl.jar", "gl.a", "gl.gcgox"))
+ .isEqualTo(ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)));
}
@Test
@@ -759,8 +757,8 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
evalRuleContextCode(
"artifacts = ruleContext.files.srcs",
"ruleContext.runfiles(symlinks = {'sym1': artifacts[0]})");
- assertEquals(
- ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)), ImmutableList.of("a.txt"));
+ assertThat(ImmutableList.of("a.txt"))
+ .isEqualTo(ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)));
}
@Test
@@ -769,8 +767,8 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
evalRuleContextCode(
"artifacts = ruleContext.files.srcs",
"ruleContext.runfiles(root_symlinks = {'sym1': artifacts[0]})");
- assertEquals(
- ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)), ImmutableList.of("a.txt"));
+ assertThat(ImmutableList.of("a.txt"))
+ .isEqualTo(ActionsTestUtil.baseArtifactNames(getRunfileArtifacts(result)));
}
@Test
@@ -814,7 +812,7 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
Object result =
evalRuleContextCode(
ruleContext, "f = depset(ruleContext.files.srcs)", "cmd_helper.join_paths(':', f)");
- assertEquals("foo/a.txt:foo/b.img", result);
+ assertThat(result).isEqualTo("foo/a.txt:foo/b.img");
}
@Test
@@ -838,8 +836,8 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
public void testFilesForRuleConfiguredTarget() throws Exception {
Object result =
evalRuleContextCode(createRuleContext("//foo:foo"), "ruleContext.attr.srcs[0].files");
- assertEquals(
- "a.txt", ActionsTestUtil.baseNamesOf(((SkylarkNestedSet) result).getSet(Artifact.class)));
+ assertThat(ActionsTestUtil.baseNamesOf(((SkylarkNestedSet) result).getSet(Artifact.class)))
+ .isEqualTo("a.txt");
}
@Test
@@ -1042,7 +1040,7 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
getConfiguredTarget("//test:my_rule");
fail();
} catch (AssertionError expected) {
- assertThat(expected.getMessage()).contains("Invalid key for default provider: foo");
+ assertThat(expected).hasMessageThat().contains("Invalid key for default provider: foo");
}
}
@@ -1178,8 +1176,9 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
getConfiguredTarget("//test:my_rule");
fail();
} catch (AssertionError expected) {
- assertThat(expected.getMessage()).contains("Object of type Target doesn't "
- + "contain declared provider unused_provider");
+ assertThat(expected)
+ .hasMessageThat()
+ .contains("Object of type Target doesn't " + "contain declared provider unused_provider");
}
}
@@ -1222,8 +1221,10 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
getConfiguredTarget("//test:my_rule");
fail();
} catch (AssertionError expected) {
- assertThat(expected.getMessage()).contains("Type Target only supports indexing "
- + "by object constructors, got string instead");
+ assertThat(expected)
+ .hasMessageThat()
+ .contains(
+ "Type Target only supports indexing " + "by object constructors, got string instead");
}
}
@@ -1251,8 +1252,9 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
getConfiguredTarget("//test:my_rule");
fail();
} catch (AssertionError expected) {
- assertThat(expected.getMessage()).contains("Object of type Target doesn't "
- + "contain declared provider unused_provider");
+ assertThat(expected)
+ .hasMessageThat()
+ .contains("Object of type Target doesn't " + "contain declared provider unused_provider");
}
}
@@ -1332,8 +1334,10 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
getConfiguredTarget("//test:my_rule");
fail();
} catch (AssertionError expected) {
- assertThat(expected.getMessage()).contains("Type Target only supports querying by object "
- + "constructors, got string instead");
+ assertThat(expected)
+ .hasMessageThat()
+ .contains(
+ "Type Target only supports querying by object " + "constructors, got string instead");
}
}
@@ -1341,9 +1345,8 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
public void testFilesForFileConfiguredTarget() throws Exception {
Object result =
evalRuleContextCode(createRuleContext("//foo:bar"), "ruleContext.attr.srcs[0].files");
- assertEquals(
- "libjl.jar",
- ActionsTestUtil.baseNamesOf(((SkylarkNestedSet) result).getSet(Artifact.class)));
+ assertThat(ActionsTestUtil.baseNamesOf(((SkylarkNestedSet) result).getSet(Artifact.class)))
+ .isEqualTo("libjl.jar");
}
@Test
@@ -1359,14 +1362,14 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
public void testBinDirPath() throws Exception {
SkylarkRuleContext ctx = createRuleContext("//foo:bar");
Object result = evalRuleContextCode(ctx, "ruleContext.bin_dir.path");
- assertEquals(ctx.getConfiguration().getBinFragment().getPathString(), result);
+ assertThat(result).isEqualTo(ctx.getConfiguration().getBinFragment().getPathString());
}
@Test
public void testEmptyLabelListTypeAttrInCtx() throws Exception {
SkylarkRuleContext ctx = createRuleContext("//foo:baz");
Object result = evalRuleContextCode(ctx, "ruleContext.attr.srcs");
- assertEquals(MutableList.EMPTY, result);
+ assertThat(result).isEqualTo(MutableList.EMPTY);
}
@Test
@@ -1375,7 +1378,7 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
String java = (String) evalRuleContextCode(ctx, "ruleContext.var['JAVA']");
// Get the last path segment
java = java.substring(java.lastIndexOf('/'));
- assertEquals("/java" + OsUtils.executableExtension(), java);
+ assertThat(java).isEqualTo("/java" + OsUtils.executableExtension());
}
@Test
@@ -1383,7 +1386,7 @@ public class SkylarkRuleImplementationFunctionsTest extends SkylarkTestCase {
SkylarkRuleContext ctx = createRuleContext("//foo:baz");
boolean coverage =
(Boolean) evalRuleContextCode(ctx, "ruleContext.configuration.coverage_enabled");
- assertEquals(coverage, ctx.getRuleContext().getConfiguration().isCodeCoverageEnabled());
+ assertThat(ctx.getRuleContext().getConfiguration().isCodeCoverageEnabled()).isEqualTo(coverage);
}
@Override
diff --git a/src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java b/src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java
index e41699792a..b3a74af30a 100644
--- a/src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java
@@ -151,7 +151,7 @@ public abstract class SkylarkTestCase extends BuildViewTestCase {
evalRuleContextCode(ruleContext, lines);
fail();
} catch (EvalException e) {
- assertThat(e.getMessage()).startsWith(errorMsg);
+ assertThat(e).hasMessageThat().startsWith(errorMsg);
}
}
@@ -161,7 +161,7 @@ public abstract class SkylarkTestCase extends BuildViewTestCase {
eval(lines);
fail("checkErrorContains(String, String...): There was no error");
} catch (EvalException e) {
- assertThat(e.getMessage()).contains(errorMsg);
+ assertThat(e).hasMessageThat().contains(errorMsg);
}
}
@@ -171,7 +171,7 @@ public abstract class SkylarkTestCase extends BuildViewTestCase {
evalRuleContextCode(ruleContext, lines);
fail("checkErrorContains(SkylarkRuleContext, String, String...): There was no error");
} catch (EvalException e) {
- assertThat(e.getMessage()).contains(errorMsg);
+ assertThat(e).hasMessageThat().contains(errorMsg);
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java b/src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java
index a78c662c3b..d8f54b637c 100644
--- a/src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java
+++ b/src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java
@@ -14,8 +14,7 @@
package com.google.devtools.build.lib.standalone;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -166,8 +165,9 @@ public class StandaloneSpawnStrategyTest {
run(createSpawn(getFalseCommand()));
fail();
} catch (ExecException e) {
- assertTrue("got: " + e.getMessage(), e
- .getMessage().startsWith("false failed: error executing command"));
+ assertWithMessage("got: " + e.getMessage())
+ .that(e.getMessage().startsWith("false failed: error executing command"))
+ .isTrue();
}
}
@@ -183,7 +183,7 @@ public class StandaloneSpawnStrategyTest {
public void testBinEchoPrintsArguments() throws Exception {
Spawn spawn = createSpawn("/bin/echo", "Hello,", "world.");
run(spawn);
- assertEquals("Hello, world.\n", out());
+ assertThat(out()).isEqualTo("Hello, world.\n");
assertThat(err()).isEmpty();
}
@@ -191,7 +191,7 @@ public class StandaloneSpawnStrategyTest {
public void testCommandRunsInWorkingDir() throws Exception {
Spawn spawn = createSpawn("/bin/pwd");
run(spawn);
- assertEquals(executor.getExecRoot() + "\n", out());
+ assertThat(out()).isEqualTo(executor.getExecRoot() + "\n");
}
@Test
@@ -202,14 +202,14 @@ public class StandaloneSpawnStrategyTest {
new ActionsTestUtil.NullAction(),
ResourceSet.ZERO);
run(spawn);
- assertEquals(Sets.newHashSet("foo=bar", "baz=boo"), Sets.newHashSet(out().split("\n")));
+ assertThat(Sets.newHashSet(out().split("\n"))).isEqualTo(Sets.newHashSet("foo=bar", "baz=boo"));
}
@Test
public void testStandardError() throws Exception {
Spawn spawn = createSpawn("/bin/sh", "-c", "echo Oops! >&2");
run(spawn);
- assertEquals("Oops!\n", err());
+ assertThat(err()).isEqualTo("Oops!\n");
assertThat(out()).isEmpty();
}
@@ -232,7 +232,9 @@ public class StandaloneSpawnStrategyTest {
run(spawn);
fail("action should fail due to being unable to resolve SDKROOT");
} catch (ExecException e) {
- assertThat(e.getMessage()).contains("Cannot locate iOS SDK on non-darwin operating system");
+ assertThat(e)
+ .hasMessageThat()
+ .contains("Cannot locate iOS SDK on non-darwin operating system");
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/BaseFunctionTest.java b/src/test/java/com/google/devtools/build/lib/syntax/BaseFunctionTest.java
index 6cda0b7962..4450b67eb3 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/BaseFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/BaseFunctionTest.java
@@ -14,23 +14,20 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.syntax.util.EvaluationTestCase;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
- * Tests for {@link BaseFunction}.
- * This tests the argument processing by BaseFunction
- * between the outer call(posargs, kwargs, ast, env) and the inner call(args, ast, env).
+ * Tests for {@link BaseFunction}. This tests the argument processing by BaseFunction between the
+ * outer call(posargs, kwargs, ast, env) and the inner call(args, ast, env).
*/
@RunWith(JUnit4.class)
public class BaseFunctionTest extends EvaluationTestCase {
@@ -56,16 +53,18 @@ public class BaseFunctionTest extends EvaluationTestCase {
update(func.getName(), func);
if (expectedOutput.charAt(0) == '[') { // a tuple => expected to pass
- assertEquals("Wrong output for " + callExpression,
- expectedOutput, eval(callExpression).toString());
+ assertWithMessage("Wrong output for " + callExpression)
+ .that(eval(callExpression).toString())
+ .isEqualTo(expectedOutput);
} else { // expected to fail with an exception
try {
eval(callExpression);
fail();
} catch (EvalException e) {
- assertEquals("Wrong exception for " + callExpression,
- expectedOutput, e.getMessage());
+ assertWithMessage("Wrong exception for " + callExpression)
+ .that(e.getMessage())
+ .isEqualTo(expectedOutput);
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/BuildFileASTTest.java b/src/test/java/com/google/devtools/build/lib/syntax/BuildFileASTTest.java
index a710481d46..dbab9976cd 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/BuildFileASTTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/BuildFileASTTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.syntax.SkylarkList.Tuple;
@@ -59,14 +56,14 @@ public class BuildFileASTTest extends EvaluationTestCase {
"",
"x = [1,2,'foo',4] + [1,2, \"%s%d\" % ('foo', 1)]");
- assertTrue(buildfile.exec(env, getEventHandler()));
+ assertThat(buildfile.exec(env, getEventHandler())).isTrue();
// Test final environment is correctly modified:
//
// input1.BUILD contains:
// x = [1,2,'foo',4] + [1,2, "%s%d" % ('foo', 1)]
- assertEquals(SkylarkList.createImmutable(Tuple.of(1, 2, "foo", 4, 1, 2, "foo1")),
- env.lookup("x"));
+ assertThat(env.lookup("x"))
+ .isEqualTo(SkylarkList.createImmutable(Tuple.of(1, 2, "foo", 4, 1, 2, "foo1")));
}
@Test
@@ -78,9 +75,9 @@ public class BuildFileASTTest extends EvaluationTestCase {
"",
"z = x + y");
- assertFalse(buildfile.exec(env, getEventHandler()));
+ assertThat(buildfile.exec(env, getEventHandler())).isFalse();
Event e = assertContainsError("unsupported operand type(s) for +: 'int' and 'list'");
- assertEquals(4, e.getLocation().getStartLineAndColumn().getLine());
+ assertThat(e.getLocation().getStartLineAndColumn().getLine()).isEqualTo(4);
}
@Test
@@ -97,10 +94,9 @@ public class BuildFileASTTest extends EvaluationTestCase {
parseBuildFile("foo() bar() something = baz() bar()");
Event event = assertContainsError("syntax error at \'bar\': expected newline");
- assertEquals("/a/build/file/BUILD",
- event.getLocation().getPath().toString());
- assertEquals(1, event.getLocation().getStartLineAndColumn().getLine());
- assertTrue(buildFileAST.containsErrors());
+ assertThat(event.getLocation().getPath().toString()).isEqualTo("/a/build/file/BUILD");
+ assertThat(event.getLocation().getStartLineAndColumn().getLine()).isEqualTo(1);
+ assertThat(buildFileAST.containsErrors()).isTrue();
}
@Test
@@ -109,11 +105,10 @@ public class BuildFileASTTest extends EvaluationTestCase {
BuildFileAST buildFileAST = parseBuildFile("a = 'foo' 'bar'");
Event event = assertContainsError(
"Implicit string concatenation is forbidden, use the + operator");
- assertEquals("/a/build/file/BUILD",
- event.getLocation().getPath().toString());
- assertEquals(1, event.getLocation().getStartLineAndColumn().getLine());
- assertEquals(10, event.getLocation().getStartLineAndColumn().getColumn());
- assertTrue(buildFileAST.containsErrors());
+ assertThat(event.getLocation().getPath().toString()).isEqualTo("/a/build/file/BUILD");
+ assertThat(event.getLocation().getStartLineAndColumn().getLine()).isEqualTo(1);
+ assertThat(event.getLocation().getStartLineAndColumn().getColumn()).isEqualTo(10);
+ assertThat(buildFileAST.containsErrors()).isTrue();
}
@Test
@@ -122,11 +117,10 @@ public class BuildFileASTTest extends EvaluationTestCase {
BuildFileAST buildFileAST = parseBuildFile("a = 'foo'\n 'bar'");
Event event = assertContainsError("indentation error");
- assertEquals("/a/build/file/BUILD",
- event.getLocation().getPath().toString());
- assertEquals(2, event.getLocation().getStartLineAndColumn().getLine());
- assertEquals(2, event.getLocation().getStartLineAndColumn().getColumn());
- assertTrue(buildFileAST.containsErrors());
+ assertThat(event.getLocation().getPath().toString()).isEqualTo("/a/build/file/BUILD");
+ assertThat(event.getLocation().getStartLineAndColumn().getLine()).isEqualTo(2);
+ assertThat(event.getLocation().getStartLineAndColumn().getColumn()).isEqualTo(2);
+ assertThat(buildFileAST.containsErrors()).isTrue();
}
@Test
@@ -140,9 +134,9 @@ public class BuildFileASTTest extends EvaluationTestCase {
"cc_library(name = 'cc',",
" srcs = libs,",
" includes = [ abi + opt_level + '/include' ])");
- assertTrue(buildFile.containsErrors());
+ assertThat(buildFile.containsErrors()).isTrue();
assertContainsError("syntax error at '+': expected expression");
- assertFalse(buildFile.exec(env, getEventHandler()));
+ assertThat(buildFile.exec(env, getEventHandler())).isFalse();
MoreAsserts.assertDoesNotContainEvent(getEventCollector(), "$error$");
// This message should not be printed anymore.
MoreAsserts.assertDoesNotContainEvent(getEventCollector(), "contains syntax error(s)");
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/EnvironmentTest.java b/src/test/java/com/google/devtools/build/lib/syntax/EnvironmentTest.java
index 9f14759fa4..8001f4e469 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/EnvironmentTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/EnvironmentTest.java
@@ -15,8 +15,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import com.google.common.collect.Sets;
@@ -41,9 +39,9 @@ public class EnvironmentTest extends EvaluationTestCase {
// Test the API directly
@Test
public void testLookupAndUpdate() throws Exception {
- assertNull(lookup("foo"));
+ assertThat(lookup("foo")).isNull();
update("foo", "bar");
- assertEquals("bar", lookup("foo"));
+ assertThat(lookup("foo")).isEqualTo("bar");
}
@Test
@@ -56,17 +54,17 @@ public class EnvironmentTest extends EvaluationTestCase {
@Test
public void testDoubleUpdateSucceeds() throws Exception {
update("VERSION", 42);
- assertEquals(42, lookup("VERSION"));
+ assertThat(lookup("VERSION")).isEqualTo(42);
update("VERSION", 43);
- assertEquals(43, lookup("VERSION"));
+ assertThat(lookup("VERSION")).isEqualTo(43);
}
// Test assign through interpreter, lookup through API:
@Test
public void testAssign() throws Exception {
- assertNull(lookup("foo"));
+ assertThat(lookup("foo")).isNull();
eval("foo = 'bar'");
- assertEquals("bar", lookup("foo"));
+ assertThat(lookup("foo")).isEqualTo("bar");
}
// Test update through API, reference through interpreter:
@@ -80,7 +78,7 @@ public class EnvironmentTest extends EvaluationTestCase {
assertThat(e).hasMessage("name 'foo' is not defined");
}
update("foo", "bar");
- assertEquals("bar", eval("foo"));
+ assertThat(eval("foo")).isEqualTo("bar");
}
// Test assign and reference through interpreter:
@@ -94,7 +92,7 @@ public class EnvironmentTest extends EvaluationTestCase {
assertThat(e).hasMessage("name 'foo' is not defined");
}
eval("foo = 'bar'");
- assertEquals("bar", eval("foo"));
+ assertThat(eval("foo")).isEqualTo("bar");
}
@Test
@@ -116,71 +114,71 @@ public class EnvironmentTest extends EvaluationTestCase {
.update("quux", 42);
}
- assertEquals(
- Sets.newHashSet(
- "foo",
- "wiz",
- "False",
- "None",
- "True",
- "-",
- "all",
- "any",
- "bool",
- "dict",
- "dir",
- "enumerate",
- "fail",
- "getattr",
- "hasattr",
- "hash",
- "int",
- "len",
- "list",
- "max",
- "min",
- "print",
- "range",
- "repr",
- "reversed",
- "sorted",
- "str",
- "tuple",
- "zip"),
- outerEnv.getVariableNames());
- assertEquals(
- Sets.newHashSet(
- "foo",
- "wiz",
- "quux",
- "False",
- "None",
- "True",
- "-",
- "all",
- "any",
- "bool",
- "dict",
- "dir",
- "enumerate",
- "fail",
- "getattr",
- "hasattr",
- "hash",
- "int",
- "len",
- "list",
- "max",
- "min",
- "print",
- "range",
- "repr",
- "reversed",
- "sorted",
- "str",
- "tuple",
- "zip"),
- innerEnv.getVariableNames());
+ assertThat(outerEnv.getVariableNames())
+ .isEqualTo(
+ Sets.newHashSet(
+ "foo",
+ "wiz",
+ "False",
+ "None",
+ "True",
+ "-",
+ "all",
+ "any",
+ "bool",
+ "dict",
+ "dir",
+ "enumerate",
+ "fail",
+ "getattr",
+ "hasattr",
+ "hash",
+ "int",
+ "len",
+ "list",
+ "max",
+ "min",
+ "print",
+ "range",
+ "repr",
+ "reversed",
+ "sorted",
+ "str",
+ "tuple",
+ "zip"));
+ assertThat(innerEnv.getVariableNames())
+ .isEqualTo(
+ Sets.newHashSet(
+ "foo",
+ "wiz",
+ "quux",
+ "False",
+ "None",
+ "True",
+ "-",
+ "all",
+ "any",
+ "bool",
+ "dict",
+ "dir",
+ "enumerate",
+ "fail",
+ "getattr",
+ "hasattr",
+ "hash",
+ "int",
+ "len",
+ "list",
+ "max",
+ "min",
+ "print",
+ "range",
+ "repr",
+ "reversed",
+ "sorted",
+ "str",
+ "tuple",
+ "zip"));
}
@Test
@@ -210,12 +208,12 @@ public class EnvironmentTest extends EvaluationTestCase {
.setEventHandler(Environment.FAIL_FAST_HANDLER)
.build();
env.update("x", 1);
- assertEquals(1, env.lookup("x"));
+ assertThat(env.lookup("x")).isEqualTo(1);
env.update("y", 2);
- assertEquals(2, env.lookup("y"));
- assertEquals(1, env.lookup("x"));
+ assertThat(env.lookup("y")).isEqualTo(2);
+ assertThat(env.lookup("x")).isEqualTo(1);
env.update("x", 3);
- assertEquals(3, env.lookup("x"));
+ assertThat(env.lookup("x")).isEqualTo(3);
}
try {
// This update to an existing variable should fail because the environment was frozen.
@@ -299,15 +297,18 @@ public class EnvironmentTest extends EvaluationTestCase {
BuildFileAST.eval(env, "special_var = 41");
throw new AssertionError("failed to fail");
} catch (EvalException e) {
- assertThat(e.getMessage()).contains("Variable special_var is read only");
+ assertThat(e).hasMessageThat().contains("Variable special_var is read only");
}
try {
BuildFileAST.eval(env, "def foo(x): x += global_var; global_var = 36; return x", "foo(1)");
throw new AssertionError("failed to fail");
} catch (EvalExceptionWithStackTrace e) {
- assertThat(e.getMessage()).contains("Variable 'global_var' is referenced before assignment. "
- + "The variable is defined in the global scope.");
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "Variable 'global_var' is referenced before assignment. "
+ + "The variable is defined in the global scope.");
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/EvalUtilsTest.java b/src/test/java/com/google/devtools/build/lib/syntax/EvalUtilsTest.java
index e5f669e587..94e50ae811 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/EvalUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/EvalUtilsTest.java
@@ -15,9 +15,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -81,38 +78,38 @@ public class EvalUtilsTest extends EvaluationTestCase {
@Test
public void testDataTypeNames() throws Exception {
- assertEquals("string", EvalUtils.getDataTypeName("foo"));
- assertEquals("int", EvalUtils.getDataTypeName(3));
- assertEquals("tuple", EvalUtils.getDataTypeName(Tuple.of(1, 2, 3)));
- assertEquals("list", EvalUtils.getDataTypeName(makeList(null)));
- assertEquals("dict", EvalUtils.getDataTypeName(makeDict(null)));
- assertEquals("NoneType", EvalUtils.getDataTypeName(Runtime.NONE));
- assertEquals("MockClassA", EvalUtils.getDataTypeName(new MockClassA()));
- assertEquals("MockClassA", EvalUtils.getDataTypeName(new MockClassB()));
+ assertThat(EvalUtils.getDataTypeName("foo")).isEqualTo("string");
+ assertThat(EvalUtils.getDataTypeName(3)).isEqualTo("int");
+ assertThat(EvalUtils.getDataTypeName(Tuple.of(1, 2, 3))).isEqualTo("tuple");
+ assertThat(EvalUtils.getDataTypeName(makeList(null))).isEqualTo("list");
+ assertThat(EvalUtils.getDataTypeName(makeDict(null))).isEqualTo("dict");
+ assertThat(EvalUtils.getDataTypeName(Runtime.NONE)).isEqualTo("NoneType");
+ assertThat(EvalUtils.getDataTypeName(new MockClassA())).isEqualTo("MockClassA");
+ assertThat(EvalUtils.getDataTypeName(new MockClassB())).isEqualTo("MockClassA");
}
@Test
public void testDatatypeMutabilityPrimitive() throws Exception {
- assertTrue(EvalUtils.isImmutable("foo"));
- assertTrue(EvalUtils.isImmutable(3));
+ assertThat(EvalUtils.isImmutable("foo")).isTrue();
+ assertThat(EvalUtils.isImmutable(3)).isTrue();
}
@Test
public void testDatatypeMutabilityShallow() throws Exception {
- assertTrue(EvalUtils.isImmutable(Tuple.of(1, 2, 3)));
+ assertThat(EvalUtils.isImmutable(Tuple.of(1, 2, 3))).isTrue();
// Mutability depends on the environment.
- assertTrue(EvalUtils.isImmutable(makeList(null)));
- assertTrue(EvalUtils.isImmutable(makeDict(null)));
- assertFalse(EvalUtils.isImmutable(makeList(env)));
- assertFalse(EvalUtils.isImmutable(makeDict(env)));
+ assertThat(EvalUtils.isImmutable(makeList(null))).isTrue();
+ assertThat(EvalUtils.isImmutable(makeDict(null))).isTrue();
+ assertThat(EvalUtils.isImmutable(makeList(env))).isFalse();
+ assertThat(EvalUtils.isImmutable(makeDict(env))).isFalse();
}
@Test
public void testDatatypeMutabilityDeep() throws Exception {
- assertTrue(EvalUtils.isImmutable(Tuple.<Object>of(makeList(null))));
+ assertThat(EvalUtils.isImmutable(Tuple.<Object>of(makeList(null)))).isTrue();
- assertFalse(EvalUtils.isImmutable(Tuple.<Object>of(makeList(env))));
+ assertThat(EvalUtils.isImmutable(Tuple.<Object>of(makeList(env)))).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/EvaluationTest.java b/src/test/java/com/google/devtools/build/lib/syntax/EvaluationTest.java
index 6e826bd766..bd4f18c8f4 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/EvaluationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/EvaluationTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.syntax.SkylarkList.MutableList;
@@ -355,13 +352,13 @@ public class EvaluationTest extends EvaluationTestCase {
// list
Object x = eval("[1,2] + [3,4]");
assertThat((Iterable<Object>) x).containsExactly(1, 2, 3, 4).inOrder();
- assertEquals(MutableList.of(env, 1, 2, 3, 4), x);
- assertFalse(EvalUtils.isImmutable(x));
+ assertThat(x).isEqualTo(MutableList.of(env, 1, 2, 3, 4));
+ assertThat(EvalUtils.isImmutable(x)).isFalse();
// tuple
x = eval("(1,2) + (3,4)");
- assertEquals(Tuple.of(1, 2, 3, 4), x);
- assertTrue(EvalUtils.isImmutable(x));
+ assertThat(x).isEqualTo(Tuple.of(1, 2, 3, 4));
+ assertThat(EvalUtils.isImmutable(x)).isTrue();
checkEvalError("unsupported operand type(s) for +: 'tuple' and 'list'",
"(1,2) + [3,4]"); // list + tuple
@@ -533,10 +530,10 @@ public class EvaluationTest extends EvaluationTestCase {
@Test
public void testDictComprehensions_ToString() throws Exception {
- assertEquals("{x: x for x in [1, 2]}",
- parseExpression("{x : x for x in [1, 2]}").toString());
- assertEquals("{x + \"a\": x for x in [1, 2]}",
- parseExpression("{x + 'a' : x for x in [1, 2]}").toString());
+ assertThat(parseExpression("{x : x for x in [1, 2]}").toString())
+ .isEqualTo("{x: x for x in [1, 2]}");
+ assertThat(parseExpression("{x + 'a' : x for x in [1, 2]}").toString())
+ .isEqualTo("{x + \"a\": x for x in [1, 2]}");
}
@Test
@@ -573,7 +570,7 @@ public class EvaluationTest extends EvaluationTestCase {
// TODO(fwe): cannot be handled by current testing suite
SelectorList x = (SelectorList) eval("select({'foo': ['FOO'], 'bar': ['BAR']}) + []");
List<Object> elements = x.getElements();
- assertThat(elements.size()).isEqualTo(2);
+ assertThat(elements).hasSize(2);
assertThat(elements.get(0)).isInstanceOf(SelectorValue.class);
assertThat((Iterable<Object>) elements.get(1)).isEmpty();
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/ExceptionTest.java b/src/test/java/com/google/devtools/build/lib/syntax/ExceptionTest.java
index b91e9c264f..77a5a8068a 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/ExceptionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/ExceptionTest.java
@@ -16,7 +16,6 @@ package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.events.Location;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -32,7 +31,8 @@ public class ExceptionTest {
public void testEmptyMessage() throws Exception {
EvalExceptionWithStackTrace ex =
new EvalExceptionWithStackTrace(new NullPointerException(), DUMMY_NODE);
- assertThat(ex.getMessage())
+ assertThat(ex)
+ .hasMessageThat()
.contains("Null Pointer: ExceptionTest.testEmptyMessage() in ExceptionTest.java:");
}
@@ -47,6 +47,6 @@ public class ExceptionTest {
private void runExceptionTest(Exception toThrow, Exception expectedCause) {
EvalExceptionWithStackTrace ex = new EvalExceptionWithStackTrace(toThrow, DUMMY_NODE);
- assertThat(ex.getCause()).isEqualTo(expectedCause);
+ assertThat(ex).hasCauseThat().isEqualTo(expectedCause);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/FunctionTest.java b/src/test/java/com/google/devtools/build/lib/syntax/FunctionTest.java
index 258d219431..0103669222 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/FunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/FunctionTest.java
@@ -14,8 +14,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.syntax.util.EvaluationTestCase;
@@ -38,7 +36,7 @@ public class FunctionTest extends EvaluationTestCase {
" a = 1",
" b = a\n");
UserDefinedFunction stmt = (UserDefinedFunction) lookup("func");
- assertNotNull(stmt);
+ assertThat(stmt).isNotNull();
assertThat(stmt.getName()).isEqualTo("func");
assertThat(stmt.getFunctionSignature().getSignature().getShape().getMandatoryPositionals())
.isEqualTo(3);
@@ -82,7 +80,7 @@ public class FunctionTest extends EvaluationTestCase {
eval("def func():",
" a = 2",
"func()\n");
- assertEquals(1, lookup("a"));
+ assertThat(lookup("a")).isEqualTo(1);
}
@Test
@@ -92,7 +90,7 @@ public class FunctionTest extends EvaluationTestCase {
" b = a",
" return b",
"c = func()\n");
- assertEquals(1, lookup("c"));
+ assertThat(lookup("c")).isEqualTo(1);
}
@Test
@@ -103,7 +101,7 @@ public class FunctionTest extends EvaluationTestCase {
" b = a",
" return b",
"c = func()\n");
- assertEquals(2, lookup("c"));
+ assertThat(lookup("c")).isEqualTo(2);
}
@Test
@@ -138,7 +136,7 @@ public class FunctionTest extends EvaluationTestCase {
" a = 3",
" return b",
"c = func()\n");
- assertEquals(2, lookup("c"));
+ assertThat(lookup("c")).isEqualTo(2);
}
@SuppressWarnings("unchecked")
@@ -153,7 +151,7 @@ public class FunctionTest extends EvaluationTestCase {
eval("def func():",
" return 2",
"b = func()\n");
- assertEquals(2, lookup("b"));
+ assertThat(lookup("b")).isEqualTo(2);
}
@Test
@@ -162,7 +160,7 @@ public class FunctionTest extends EvaluationTestCase {
" for i in [1, 2, 3, 4, 5]:",
" return i",
"b = func()\n");
- assertEquals(1, lookup("b"));
+ assertThat(lookup("b")).isEqualTo(1);
}
@Test
@@ -174,8 +172,8 @@ public class FunctionTest extends EvaluationTestCase {
" return b",
"c = func(0)",
"d = func(1)\n");
- assertEquals(1, lookup("c"));
- assertEquals(2, lookup("d"));
+ assertThat(lookup("c")).isEqualTo(1);
+ assertThat(lookup("d")).isEqualTo(2);
}
@Test
@@ -199,14 +197,14 @@ public class FunctionTest extends EvaluationTestCase {
"def func1():",
" return func2()",
"b = func1()\n");
- assertEquals(1, lookup("b"));
+ assertThat(lookup("b")).isEqualTo(1);
}
@Test
public void testSingleLineFunction() throws Exception {
eval("def func(): return 'a'",
"s = func()\n");
- assertEquals("a", lookup("s"));
+ assertThat(lookup("s")).isEqualTo("a");
}
@Test
@@ -214,7 +212,7 @@ public class FunctionTest extends EvaluationTestCase {
eval("def func(): return {'a' : 1}",
"d = func()",
"a = d['a']\n");
- assertEquals(1, lookup("a"));
+ assertThat(lookup("a")).isEqualTo(1);
}
@Test
@@ -222,7 +220,7 @@ public class FunctionTest extends EvaluationTestCase {
eval("def func(): return [1, 2, 3]",
"d = func()",
"a = d[1]\n");
- assertEquals(2, lookup("a"));
+ assertThat(lookup("a")).isEqualTo(2);
}
@SuppressWarnings("unchecked")
@@ -241,7 +239,7 @@ public class FunctionTest extends EvaluationTestCase {
"def func(d):",
" d += {'a' : 2}",
"func(d)");
- assertEquals(ImmutableMap.of("a", 1), lookup("d"));
+ assertThat(lookup("d")).isEqualTo(ImmutableMap.of("a", 1));
}
@Test
@@ -250,7 +248,7 @@ public class FunctionTest extends EvaluationTestCase {
" return a + 1",
"alias = func",
"r = alias(1)");
- assertEquals(2, lookup("r"));
+ assertThat(lookup("r")).isEqualTo(2);
}
@Test
@@ -258,7 +256,7 @@ public class FunctionTest extends EvaluationTestCase {
eval("def func(a, b, c):",
" return a + b + c",
"v = func(1, c = 2, b = 3)");
- assertEquals(6, lookup("v"));
+ assertThat(lookup("v")).isEqualTo(6);
}
private String functionWithOptionalArgs() {
@@ -278,10 +276,10 @@ public class FunctionTest extends EvaluationTestCase {
"v2 = func(b = 2, a = '2', c = 2)",
"v3 = func('3')",
"v4 = func('4', c = 1)\n");
- assertEquals("1abc", lookup("v1"));
- assertEquals("2abc", lookup("v2"));
- assertEquals("3a", lookup("v3"));
- assertEquals("4ac", lookup("v4"));
+ assertThat(lookup("v1")).isEqualTo("1abc");
+ assertThat(lookup("v2")).isEqualTo("2abc");
+ assertThat(lookup("v3")).isEqualTo("3a");
+ assertThat(lookup("v4")).isEqualTo("4ac");
}
@Test
@@ -292,10 +290,10 @@ public class FunctionTest extends EvaluationTestCase {
"v2 = func(b = 'x', a = 'a', c = 'y')",
"v3 = func('a')",
"v4 = func('a', c = 'y')\n");
- assertEquals("axy", lookup("v1"));
- assertEquals("axy", lookup("v2"));
- assertEquals("abc", lookup("v3"));
- assertEquals("aby", lookup("v4"));
+ assertThat(lookup("v1")).isEqualTo("axy");
+ assertThat(lookup("v2")).isEqualTo("axy");
+ assertThat(lookup("v3")).isEqualTo("abc");
+ assertThat(lookup("v4")).isEqualTo("aby");
}
@Test
@@ -328,11 +326,11 @@ public class FunctionTest extends EvaluationTestCase {
"v1 = foo(**args)",
"v2 = foo('x', c = 'c', d = 'e', **{'b': 'y'})",
"v3 = foo(c = 'z', a = 'x', **{'b': 'y', 'd': 'f'})");
- assertEquals("xbzd", lookup("v1"));
- assertEquals("xyce", lookup("v2"));
- assertEquals("xyzf", lookup("v3"));
+ assertThat(lookup("v1")).isEqualTo("xbzd");
+ assertThat(lookup("v2")).isEqualTo("xyce");
+ assertThat(lookup("v3")).isEqualTo("xyzf");
UserDefinedFunction foo = (UserDefinedFunction) lookup("foo");
- assertEquals("foo(a, b = \"b\", *, c, d = \"d\")", foo.toString());
+ assertThat(foo.toString()).isEqualTo("foo(a, b = \"b\", *, c, d = \"d\")");
}
@Test
@@ -385,14 +383,14 @@ public class FunctionTest extends EvaluationTestCase {
" a = 3",
" return foo()",
"v = bar()\n");
- assertEquals(2, lookup("v"));
+ assertThat(lookup("v")).isEqualTo(2);
}
@Test
public void testMixingPositionalOptional() throws Exception {
eval("def f(name, value = '', optional = ''): return value",
"v = f('name', 'value')\n");
- assertEquals("value", lookup("v"));
+ assertThat(lookup("v")).isEqualTo("value");
}
@Test
@@ -402,10 +400,10 @@ public class FunctionTest extends EvaluationTestCase {
"v2 = f('0', *['name', 'value'])",
"v3 = f('0', *['b'], optional = '3')",
"v4 = f(*[],name='a')\n");
- assertEquals("namevalue2", lookup("v1"));
- assertEquals("0namevalue", lookup("v2"));
- assertEquals("0b3", lookup("v3"));
- assertEquals("a12", lookup("v4"));
+ assertThat(lookup("v1")).isEqualTo("namevalue2");
+ assertThat(lookup("v2")).isEqualTo("0namevalue");
+ assertThat(lookup("v3")).isEqualTo("0b3");
+ assertThat(lookup("v4")).isEqualTo("a12");
}
@Test
@@ -419,11 +417,11 @@ public class FunctionTest extends EvaluationTestCase {
"v3 = f('a', *['b', 'c', 'd'], mandatory = 'y', optional = 'z')",
"v4 = f(*['a'], **{'value': 'b', 'mandatory': 'c'})",
"v5 = f('a', 'b', 'c', *['d', 'e'], mandatory = 'f', **{'optional': 'g'})\n");
- assertEquals("abz2|", lookup("v1"));
- assertEquals("abz2|cd", lookup("v2"));
- assertEquals("abyz|cd", lookup("v3"));
- assertEquals("abc2|", lookup("v4"));
- assertEquals("abfg|cde", lookup("v5"));
+ assertThat(lookup("v1")).isEqualTo("abz2|");
+ assertThat(lookup("v2")).isEqualTo("abz2|cd");
+ assertThat(lookup("v3")).isEqualTo("abyz|cd");
+ assertThat(lookup("v4")).isEqualTo("abc2|");
+ assertThat(lookup("v5")).isEqualTo("abfg|cde");
}
@Test
@@ -436,8 +434,8 @@ public class FunctionTest extends EvaluationTestCase {
"v1 = f('a', 'b', 'c', 'd', 'e')",
"v2 = f('a', optional='b', value='c')",
"v3 = f('a')");
- assertEquals("abc|de", lookup("v1"));
- assertEquals("acb|", lookup("v2"));
- assertEquals("a12|", lookup("v3"));
+ assertThat(lookup("v1")).isEqualTo("abc|de");
+ assertThat(lookup("v2")).isEqualTo("acb|");
+ assertThat(lookup("v3")).isEqualTo("a12|");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/GlobCriteriaTest.java b/src/test/java/com/google/devtools/build/lib/syntax/GlobCriteriaTest.java
index ba70c5a445..c75633a8f5 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/GlobCriteriaTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/GlobCriteriaTest.java
@@ -14,14 +14,10 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.testutil.Suite;
import com.google.devtools.build.lib.testutil.TestSpec;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -36,7 +32,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_EmptyList() throws Exception {
GlobCriteria gc = GlobCriteria.parse("[]");
- assertFalse(gc.isGlob());
+ assertThat(gc.isGlob()).isFalse();
assertThat(gc.getIncludePatterns()).isEmpty();
assertThat(gc.getExcludePatterns()).isEmpty();
}
@@ -44,7 +40,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_SingleList() throws Exception {
GlobCriteria gc = GlobCriteria.parse("['abc']");
- assertFalse(gc.isGlob());
+ assertThat(gc.isGlob()).isFalse();
assertThat(gc.getIncludePatterns()).containsExactly("abc");
assertThat(gc.getExcludePatterns()).isEmpty();
}
@@ -52,7 +48,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_MultipleList() throws Exception {
GlobCriteria gc = GlobCriteria.parse("['abc', 'def', 'ghi']");
- assertFalse(gc.isGlob());
+ assertThat(gc.isGlob()).isFalse();
assertThat(gc.getIncludePatterns()).containsExactly("abc", "def", "ghi").inOrder();
assertThat(gc.getExcludePatterns()).isEmpty();
}
@@ -60,7 +56,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_EmptyGlob() throws Exception {
GlobCriteria gc = GlobCriteria.parse("glob([])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).isEmpty();
assertThat(gc.getExcludePatterns()).isEmpty();
}
@@ -68,7 +64,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_SingleGlob() throws Exception {
GlobCriteria gc = GlobCriteria.parse("glob(['abc'])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).containsExactly("abc");
assertThat(gc.getExcludePatterns()).isEmpty();
}
@@ -76,7 +72,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_MultipleGlob() throws Exception {
GlobCriteria gc = GlobCriteria.parse("glob(['abc', 'def', 'ghi'])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).containsExactly("abc", "def", "ghi").inOrder();
assertThat(gc.getExcludePatterns()).isEmpty();
}
@@ -84,7 +80,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_EmptyGlobWithExclude() throws Exception {
GlobCriteria gc = GlobCriteria.parse("glob([], exclude=['xyz'])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).isEmpty();
assertThat(gc.getExcludePatterns()).containsExactly("xyz");
}
@@ -92,7 +88,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_SingleGlobWithExclude() throws Exception {
GlobCriteria gc = GlobCriteria.parse("glob(['abc'], exclude=['xyz'])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).containsExactly("abc");
assertThat(gc.getExcludePatterns()).containsExactly("xyz");
}
@@ -100,7 +96,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_MultipleGlobWithExclude() throws Exception {
GlobCriteria gc = GlobCriteria.parse("glob(['abc', 'def', 'ghi'], exclude=['xyz'])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).containsExactly("abc", "def", "ghi").inOrder();
assertThat(gc.getExcludePatterns()).containsExactly("xyz");
}
@@ -109,7 +105,7 @@ public class GlobCriteriaTest {
public void testParse_MultipleGlobWithMultipleExclude() throws Exception {
GlobCriteria gc = GlobCriteria.parse(
"glob(['abc', 'def', 'ghi'], exclude=['rst', 'uvw', 'xyz'])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).containsExactly("abc", "def", "ghi").inOrder();
assertThat(gc.getExcludePatterns()).containsExactly("rst", "uvw", "xyz").inOrder();
}
@@ -117,7 +113,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_GlobWithSlashesAndWildcards() throws Exception {
GlobCriteria gc = GlobCriteria.parse("glob(['java/src/net/jsunit/*.java'])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).containsExactly("java/src/net/jsunit/*.java");
assertThat(gc.getExcludePatterns()).isEmpty();
}
@@ -125,7 +121,7 @@ public class GlobCriteriaTest {
@Test
public void testParse_ExcludeWithInvalidLabel() throws Exception {
GlobCriteria gc = GlobCriteria.parse("glob(['abc', 'def', 'ghi'], exclude=['xyz~'])");
- assertTrue(gc.isGlob());
+ assertThat(gc.isGlob()).isTrue();
assertThat(gc.getIncludePatterns()).containsExactly("abc", "def", "ghi").inOrder();
assertThat(gc.getExcludePatterns()).containsExactly("xyz~");
}
@@ -190,6 +186,6 @@ public class GlobCriteriaTest {
builder.append("]");
String s = builder.toString();
GlobCriteria gc = GlobCriteria.parse(s);
- assertEquals(s, gc.toString());
+ assertThat(gc.toString()).isEqualTo(s);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/GlobListTest.java b/src/test/java/com/google/devtools/build/lib/syntax/GlobListTest.java
index 64419fcd23..d5da29e53f 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/GlobListTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/GlobListTest.java
@@ -14,21 +14,16 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.testutil.Suite;
import com.google.devtools.build.lib.testutil.TestSpec;
-
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.List;
-
-/**
- * Tests for {@link GlobList}
- */
+/** Tests for {@link GlobList} */
@TestSpec(size = Suite.SMALL_TESTS)
@RunWith(JUnit4.class)
public class GlobListTest {
@@ -36,19 +31,19 @@ public class GlobListTest {
@Test
public void testParse_glob() throws Exception {
String expression = "glob(['abc'])";
- assertEquals(expression, GlobList.parse(expression).toExpression());
+ assertThat(GlobList.parse(expression).toExpression()).isEqualTo(expression);
}
@Test
public void testParse_multipleGlobs() throws Exception {
String expression = "glob(['abc']) + glob(['def']) + glob(['ghi'])";
- assertEquals(expression, GlobList.parse(expression).toExpression());
+ assertThat(GlobList.parse(expression).toExpression()).isEqualTo(expression);
}
@Test
public void testParse_multipleLists() throws Exception {
String expression = "['abc'] + ['def'] + ['ghi']";
- assertEquals(expression, GlobList.parse(expression).toExpression());
+ assertThat(GlobList.parse(expression).toExpression()).isEqualTo(expression);
}
@Test
@@ -56,7 +51,7 @@ public class GlobListTest {
String expression = "glob(['abc', 'def', 'ghi'], "
+ "exclude=['rst', 'uvw', 'xyz']) "
+ "+ glob(['abc', 'def', 'ghi'], exclude=['rst', 'uvw', 'xyz'])";
- assertEquals(expression, GlobList.parse(expression).toExpression());
+ assertThat(GlobList.parse(expression).toExpression()).isEqualTo(expression);
}
@Test
@@ -66,7 +61,7 @@ public class GlobListTest {
GlobList<String> glob2 = GlobList.parse(
"glob(['xyzzy']) + glob(['foo'], exclude=['bar'])");
GlobList<String> cat = GlobList.concat(glob1, glob2);
- assertEquals(glob1.toExpression() + " + " + glob2.toExpression(), cat.toExpression());
+ assertThat(cat.toExpression()).isEqualTo(glob1.toExpression() + " + " + glob2.toExpression());
}
@Test
@@ -75,8 +70,8 @@ public class GlobListTest {
"glob(['abc'], exclude=['def']) + glob(['xyz'])");
List<String> list = ImmutableList.of("xyzzy", "foo", "bar");
GlobList<String> cat = GlobList.concat(list, glob);
- assertEquals("['xyzzy', 'foo', 'bar'] + glob(['abc'], exclude=['def']) + glob(['xyz'])",
- cat.toExpression());
+ assertThat(cat.toExpression())
+ .isEqualTo("['xyzzy', 'foo', 'bar'] + glob(['abc'], exclude=['def']) + glob(['xyz'])");
}
@Test
@@ -85,8 +80,8 @@ public class GlobListTest {
"glob(['abc'], exclude=['def']) + glob(['xyz'])");
List<String> list = ImmutableList.of("xyzzy", "foo", "bar");
GlobList<String> cat = GlobList.concat(glob, list);
- assertEquals("glob(['abc'], exclude=['def']) + glob(['xyz']) + ['xyzzy', 'foo', 'bar']",
- cat.toExpression());
+ assertThat(cat.toExpression())
+ .isEqualTo("glob(['abc'], exclude=['def']) + glob(['xyz']) + ['xyzzy', 'foo', 'bar']");
}
@Test
@@ -95,10 +90,10 @@ public class GlobListTest {
List<String> exclude = ImmutableList.of("rst", "uvw", "xyz");
List<String> matches = ImmutableList.of("xyzzy", "foo", "bar");
GlobList<String> glob = GlobList.captureResults(include, exclude, matches);
- assertEquals(matches, glob);
+ assertThat(glob).isEqualTo(matches);
ImmutableList<GlobCriteria> criteria = glob.getCriteria();
assertThat(criteria).hasSize(1);
- assertEquals(include, criteria.get(0).getIncludePatterns());
- assertEquals(exclude, criteria.get(0).getExcludePatterns());
+ assertThat(criteria.get(0).getIncludePatterns()).isEqualTo(include);
+ assertThat(criteria.get(0).getExcludePatterns()).isEqualTo(exclude);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/LexerTest.java b/src/test/java/com/google/devtools/build/lib/syntax/LexerTest.java
index b270a54f65..bf9afdf2a3 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/LexerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/LexerTest.java
@@ -13,9 +13,8 @@
// limitations under the License.
package com.google.devtools.build.lib.syntax;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.events.Event;
@@ -133,46 +132,47 @@ public class LexerTest {
@Test
public void testBasics1() throws Exception {
- assertEquals("IDENTIFIER RPAREN NEWLINE EOF", names(tokens("wiz) ")));
- assertEquals("IDENTIFIER RPAREN NEWLINE EOF", names(tokens("wiz )")));
- assertEquals("IDENTIFIER RPAREN NEWLINE EOF", names(tokens(" wiz)")));
- assertEquals("IDENTIFIER RPAREN NEWLINE EOF", names(tokens(" wiz ) ")));
- assertEquals("IDENTIFIER RPAREN NEWLINE EOF", names(tokens("wiz\t)")));
+ assertThat(names(tokens("wiz) "))).isEqualTo("IDENTIFIER RPAREN NEWLINE EOF");
+ assertThat(names(tokens("wiz )"))).isEqualTo("IDENTIFIER RPAREN NEWLINE EOF");
+ assertThat(names(tokens(" wiz)"))).isEqualTo("IDENTIFIER RPAREN NEWLINE EOF");
+ assertThat(names(tokens(" wiz ) "))).isEqualTo("IDENTIFIER RPAREN NEWLINE EOF");
+ assertThat(names(tokens("wiz\t)"))).isEqualTo("IDENTIFIER RPAREN NEWLINE EOF");
}
@Test
public void testBasics2() throws Exception {
- assertEquals("RPAREN NEWLINE EOF", names(tokens(")")));
- assertEquals("RPAREN NEWLINE EOF", names(tokens(" )")));
- assertEquals("RPAREN NEWLINE EOF", names(tokens(" ) ")));
- assertEquals("RPAREN NEWLINE EOF", names(tokens(") ")));
+ assertThat(names(tokens(")"))).isEqualTo("RPAREN NEWLINE EOF");
+ assertThat(names(tokens(" )"))).isEqualTo("RPAREN NEWLINE EOF");
+ assertThat(names(tokens(" ) "))).isEqualTo("RPAREN NEWLINE EOF");
+ assertThat(names(tokens(") "))).isEqualTo("RPAREN NEWLINE EOF");
}
@Test
public void testBasics3() throws Exception {
- assertEquals("INT COMMENT NEWLINE INT NEWLINE EOF", names(tokens("123#456\n789")));
- assertEquals("INT COMMENT NEWLINE INT NEWLINE EOF", names(tokens("123 #456\n789")));
- assertEquals("INT COMMENT NEWLINE INT NEWLINE EOF", names(tokens("123#456 \n789")));
- assertEquals("INT COMMENT NEWLINE INDENT INT NEWLINE OUTDENT NEWLINE EOF",
- names(tokens("123#456\n 789")));
- assertEquals("INT COMMENT NEWLINE INT NEWLINE EOF", names(tokens("123#456\n789 ")));
+ assertThat(names(tokens("123#456\n789"))).isEqualTo("INT COMMENT NEWLINE INT NEWLINE EOF");
+ assertThat(names(tokens("123 #456\n789"))).isEqualTo("INT COMMENT NEWLINE INT NEWLINE EOF");
+ assertThat(names(tokens("123#456 \n789"))).isEqualTo("INT COMMENT NEWLINE INT NEWLINE EOF");
+ assertThat(names(tokens("123#456\n 789")))
+ .isEqualTo("INT COMMENT NEWLINE INDENT INT NEWLINE OUTDENT NEWLINE EOF");
+ assertThat(names(tokens("123#456\n789 "))).isEqualTo("INT COMMENT NEWLINE INT NEWLINE EOF");
}
@Test
public void testBasics4() throws Exception {
- assertEquals("NEWLINE EOF", names(tokens("")));
- assertEquals("COMMENT NEWLINE EOF", names(tokens("# foo")));
- assertEquals("INT INT INT INT NEWLINE EOF", names(tokens("1 2 3 4")));
- assertEquals("INT DOT INT NEWLINE EOF", names(tokens("1.234")));
- assertEquals("IDENTIFIER LPAREN IDENTIFIER COMMA IDENTIFIER RPAREN "
- + "NEWLINE EOF", names(tokens("foo(bar, wiz)")));
+ assertThat(names(tokens(""))).isEqualTo("NEWLINE EOF");
+ assertThat(names(tokens("# foo"))).isEqualTo("COMMENT NEWLINE EOF");
+ assertThat(names(tokens("1 2 3 4"))).isEqualTo("INT INT INT INT NEWLINE EOF");
+ assertThat(names(tokens("1.234"))).isEqualTo("INT DOT INT NEWLINE EOF");
+ assertThat(names(tokens("foo(bar, wiz)")))
+ .isEqualTo("IDENTIFIER LPAREN IDENTIFIER COMMA IDENTIFIER RPAREN " + "NEWLINE EOF");
}
@Test
public void testCrLf() throws Exception {
- assertEquals("NEWLINE EOF", names(tokens("\r\n\r\n")));
- assertEquals("NEWLINE INT NEWLINE EOF", names(tokens("\r\n\r1\r\r\n")));
- assertEquals("COMMENT NEWLINE COMMENT NEWLINE EOF", names(tokens("# foo\r\n# bar\r\n")));
+ assertThat(names(tokens("\r\n\r\n"))).isEqualTo("NEWLINE EOF");
+ assertThat(names(tokens("\r\n\r1\r\r\n"))).isEqualTo("NEWLINE INT NEWLINE EOF");
+ assertThat(names(tokens("# foo\r\n# bar\r\n")))
+ .isEqualTo("COMMENT NEWLINE COMMENT NEWLINE EOF");
}
@Test
@@ -181,262 +181,242 @@ public class LexerTest {
// don't consume too many chars.
// decimal
- assertEquals("INT(12345) MINUS NEWLINE EOF", values(tokens("12345-")));
+ assertThat(values(tokens("12345-"))).isEqualTo("INT(12345) MINUS NEWLINE EOF");
// octal
- assertEquals("INT(5349) MINUS NEWLINE EOF", values(tokens("012345-")));
+ assertThat(values(tokens("012345-"))).isEqualTo("INT(5349) MINUS NEWLINE EOF");
// octal (bad)
- assertEquals("INT(0) MINUS NEWLINE EOF", values(tokens("012349-")));
- assertEquals("/some/path.txt:1: invalid base-8 integer constant: 012349",
- lastError.toString());
+ assertThat(values(tokens("012349-"))).isEqualTo("INT(0) MINUS NEWLINE EOF");
+ assertThat(lastError.toString())
+ .isEqualTo("/some/path.txt:1: invalid base-8 integer constant: 012349");
// hexadecimal (uppercase)
- assertEquals("INT(1193055) MINUS NEWLINE EOF", values(tokens("0X12345F-")));
+ assertThat(values(tokens("0X12345F-"))).isEqualTo("INT(1193055) MINUS NEWLINE EOF");
// hexadecimal (lowercase)
- assertEquals("INT(1193055) MINUS NEWLINE EOF", values(tokens("0x12345f-")));
+ assertThat(values(tokens("0x12345f-"))).isEqualTo("INT(1193055) MINUS NEWLINE EOF");
// hexadecimal (lowercase) [note: "g" cause termination of token]
- assertEquals("INT(74565) IDENTIFIER(g) MINUS NEWLINE EOF",
- values(tokens("0x12345g-")));
+ assertThat(values(tokens("0x12345g-"))).isEqualTo("INT(74565) IDENTIFIER(g) MINUS NEWLINE EOF");
}
@Test
public void testIntegersAndDot() throws Exception {
- assertEquals("INT(1) DOT INT(2345) NEWLINE EOF", values(tokens("1.2345")));
+ assertThat(values(tokens("1.2345"))).isEqualTo("INT(1) DOT INT(2345) NEWLINE EOF");
- assertEquals("INT(1) DOT INT(2) DOT INT(345) NEWLINE EOF",
- values(tokens("1.2.345")));
+ assertThat(values(tokens("1.2.345"))).isEqualTo("INT(1) DOT INT(2) DOT INT(345) NEWLINE EOF");
- assertEquals("INT(1) DOT INT(0) NEWLINE EOF", values(tokens("1.23E10")));
- assertEquals("/some/path.txt:1: invalid base-10 integer constant: 23E10",
- lastError.toString());
+ assertThat(values(tokens("1.23E10"))).isEqualTo("INT(1) DOT INT(0) NEWLINE EOF");
+ assertThat(lastError.toString())
+ .isEqualTo("/some/path.txt:1: invalid base-10 integer constant: 23E10");
- assertEquals("INT(1) DOT INT(0) MINUS INT(10) NEWLINE EOF",
- values(tokens("1.23E-10")));
- assertEquals("/some/path.txt:1: invalid base-10 integer constant: 23E",
- lastError.toString());
+ assertThat(values(tokens("1.23E-10"))).isEqualTo("INT(1) DOT INT(0) MINUS INT(10) NEWLINE EOF");
+ assertThat(lastError.toString())
+ .isEqualTo("/some/path.txt:1: invalid base-10 integer constant: 23E");
- assertEquals("DOT INT(123) NEWLINE EOF", values(tokens(". 123")));
- assertEquals("DOT INT(123) NEWLINE EOF", values(tokens(".123")));
- assertEquals("DOT IDENTIFIER(abc) NEWLINE EOF", values(tokens(".abc")));
+ assertThat(values(tokens(". 123"))).isEqualTo("DOT INT(123) NEWLINE EOF");
+ assertThat(values(tokens(".123"))).isEqualTo("DOT INT(123) NEWLINE EOF");
+ assertThat(values(tokens(".abc"))).isEqualTo("DOT IDENTIFIER(abc) NEWLINE EOF");
- assertEquals("IDENTIFIER(foo) DOT INT(123) NEWLINE EOF",
- values(tokens("foo.123")));
- assertEquals("IDENTIFIER(foo) DOT IDENTIFIER(bcd) NEWLINE EOF",
- values(tokens("foo.bcd"))); // 'b' are hex chars
- assertEquals("IDENTIFIER(foo) DOT IDENTIFIER(xyz) NEWLINE EOF",
- values(tokens("foo.xyz")));
+ assertThat(values(tokens("foo.123"))).isEqualTo("IDENTIFIER(foo) DOT INT(123) NEWLINE EOF");
+ assertThat(values(tokens("foo.bcd")))
+ .isEqualTo("IDENTIFIER(foo) DOT IDENTIFIER(bcd) NEWLINE EOF"); // 'b' are hex chars
+ assertThat(values(tokens("foo.xyz")))
+ .isEqualTo("IDENTIFIER(foo) DOT IDENTIFIER(xyz) NEWLINE EOF");
}
@Test
public void testStringDelimiters() throws Exception {
- assertEquals("STRING(foo) NEWLINE EOF", values(tokens("\"foo\"")));
- assertEquals("STRING(foo) NEWLINE EOF", values(tokens("'foo'")));
+ assertThat(values(tokens("\"foo\""))).isEqualTo("STRING(foo) NEWLINE EOF");
+ assertThat(values(tokens("'foo'"))).isEqualTo("STRING(foo) NEWLINE EOF");
}
@Test
public void testQuotesInStrings() throws Exception {
- assertEquals("STRING(foo'bar) NEWLINE EOF", values(tokens("'foo\\'bar'")));
- assertEquals("STRING(foo'bar) NEWLINE EOF", values(tokens("\"foo'bar\"")));
- assertEquals("STRING(foo\"bar) NEWLINE EOF", values(tokens("'foo\"bar'")));
- assertEquals("STRING(foo\"bar) NEWLINE EOF",
- values(tokens("\"foo\\\"bar\"")));
+ assertThat(values(tokens("'foo\\'bar'"))).isEqualTo("STRING(foo'bar) NEWLINE EOF");
+ assertThat(values(tokens("\"foo'bar\""))).isEqualTo("STRING(foo'bar) NEWLINE EOF");
+ assertThat(values(tokens("'foo\"bar'"))).isEqualTo("STRING(foo\"bar) NEWLINE EOF");
+ assertThat(values(tokens("\"foo\\\"bar\""))).isEqualTo("STRING(foo\"bar) NEWLINE EOF");
}
@Test
public void testStringEscapes() throws Exception {
- assertEquals("STRING(a\tb\nc\rd) NEWLINE EOF",
- values(tokens("'a\\tb\\nc\\rd'"))); // \t \r \n
- assertEquals("STRING(x\\hx) NEWLINE EOF",
- values(tokens("'x\\hx'"))); // \h is unknown => "\h"
- assertEquals("STRING(\\$$) NEWLINE EOF", values(tokens("'\\$$'")));
- assertEquals("STRING(ab) NEWLINE EOF",
- values(tokens("'a\\\nb'"))); // escape end of line
- assertEquals("STRING(abcd) NEWLINE EOF",
- values(tokens("\"ab\\ucd\"")));
- assertEquals("/some/path.txt:1: escape sequence not implemented: \\u",
- lastError.toString());
+ assertThat(values(tokens("'a\\tb\\nc\\rd'")))
+ .isEqualTo("STRING(a\tb\nc\rd) NEWLINE EOF"); // \t \r \n
+ assertThat(values(tokens("'x\\hx'")))
+ .isEqualTo("STRING(x\\hx) NEWLINE EOF"); // \h is unknown => "\h"
+ assertThat(values(tokens("'\\$$'"))).isEqualTo("STRING(\\$$) NEWLINE EOF");
+ assertThat(values(tokens("'a\\\nb'")))
+ .isEqualTo("STRING(ab) NEWLINE EOF"); // escape end of line
+ assertThat(values(tokens("\"ab\\ucd\""))).isEqualTo("STRING(abcd) NEWLINE EOF");
+ assertThat(lastError.toString())
+ .isEqualTo("/some/path.txt:1: escape sequence not implemented: \\u");
}
@Test
public void testEscapedCrlfInString() throws Exception {
- assertEquals("STRING(ab) NEWLINE EOF",
- values(tokens("'a\\\r\nb'")));
- assertEquals("STRING(ab) NEWLINE EOF",
- values(tokens("\"a\\\r\nb\"")));
- assertEquals("STRING(ab) NEWLINE EOF",
- values(tokens("\"\"\"a\\\r\nb\"\"\"")));
- assertEquals("STRING(ab) NEWLINE EOF",
- values(tokens("'''a\\\r\nb'''")));
- assertEquals("STRING(a\\\nb) NEWLINE EOF",
- values(tokens("r'a\\\r\nb'")));
- assertEquals("STRING(a\\\nb) NEWLINE EOF",
- values(tokens("r\"a\\\r\nb\"")));
- assertEquals("STRING(a\\\n\\\nb) NEWLINE EOF",
- values(tokens("r\"a\\\r\n\\\nb\"")));
+ assertThat(values(tokens("'a\\\r\nb'"))).isEqualTo("STRING(ab) NEWLINE EOF");
+ assertThat(values(tokens("\"a\\\r\nb\""))).isEqualTo("STRING(ab) NEWLINE EOF");
+ assertThat(values(tokens("\"\"\"a\\\r\nb\"\"\""))).isEqualTo("STRING(ab) NEWLINE EOF");
+ assertThat(values(tokens("'''a\\\r\nb'''"))).isEqualTo("STRING(ab) NEWLINE EOF");
+ assertThat(values(tokens("r'a\\\r\nb'"))).isEqualTo("STRING(a\\\nb) NEWLINE EOF");
+ assertThat(values(tokens("r\"a\\\r\nb\""))).isEqualTo("STRING(a\\\nb) NEWLINE EOF");
+ assertThat(values(tokens("r\"a\\\r\n\\\nb\""))).isEqualTo("STRING(a\\\n\\\nb) NEWLINE EOF");
}
@Test
public void testRawString() throws Exception {
- assertEquals("STRING(abcd) NEWLINE EOF",
- values(tokens("r'abcd'")));
- assertEquals("STRING(abcd) NEWLINE EOF",
- values(tokens("r\"abcd\"")));
- assertEquals("STRING(a\\tb\\nc\\rd) NEWLINE EOF",
- values(tokens("r'a\\tb\\nc\\rd'"))); // r'a\tb\nc\rd'
- assertEquals("STRING(a\\\") NEWLINE EOF",
- values(tokens("r\"a\\\"\""))); // r"a\""
- assertEquals("STRING(a\\\\b) NEWLINE EOF",
- values(tokens("r'a\\\\b'"))); // r'a\\b'
- assertEquals("STRING(ab) IDENTIFIER(r) NEWLINE EOF",
- values(tokens("r'ab'r")));
+ assertThat(values(tokens("r'abcd'"))).isEqualTo("STRING(abcd) NEWLINE EOF");
+ assertThat(values(tokens("r\"abcd\""))).isEqualTo("STRING(abcd) NEWLINE EOF");
+ assertThat(values(tokens("r'a\\tb\\nc\\rd'")))
+ .isEqualTo("STRING(a\\tb\\nc\\rd) NEWLINE EOF"); // r'a\tb\nc\rd'
+ assertThat(values(tokens("r\"a\\\"\""))).isEqualTo("STRING(a\\\") NEWLINE EOF"); // r"a\""
+ assertThat(values(tokens("r'a\\\\b'"))).isEqualTo("STRING(a\\\\b) NEWLINE EOF"); // r'a\\b'
+ assertThat(values(tokens("r'ab'r"))).isEqualTo("STRING(ab) IDENTIFIER(r) NEWLINE EOF");
// Unterminated raw string
values(tokens("r'\\'")); // r'\'
- assertEquals("/some/path.txt:1: unterminated string literal at eof",
- lastError.toString());
+ assertThat(lastError.toString())
+ .isEqualTo("/some/path.txt:1: unterminated string literal at eof");
}
@Test
public void testTripleRawString() throws Exception {
// r'''a\ncd'''
- assertEquals("STRING(ab\\ncd) NEWLINE EOF",
- values(tokens("r'''ab\\ncd'''")));
+ assertThat(values(tokens("r'''ab\\ncd'''"))).isEqualTo("STRING(ab\\ncd) NEWLINE EOF");
// r"""ab
// cd"""
- assertEquals(
- "STRING(ab\ncd) NEWLINE EOF",
- values(tokens("\"\"\"ab\ncd\"\"\"")));
+ assertThat(values(tokens("\"\"\"ab\ncd\"\"\""))).isEqualTo("STRING(ab\ncd) NEWLINE EOF");
// Unterminated raw string
values(tokens("r'''\\'''")); // r'''\'''
- assertEquals("/some/path.txt:1: unterminated string literal at eof",
- lastError.toString());
+ assertThat(lastError.toString())
+ .isEqualTo("/some/path.txt:1: unterminated string literal at eof");
}
@Test
public void testOctalEscapes() throws Exception {
// Regression test for a bug.
- assertEquals("STRING(\0 \1 \t \u003f I I1 \u00ff \u00ff \u00fe) NEWLINE EOF",
- values(tokens("'\\0 \\1 \\11 \\77 \\111 \\1111 \\377 \\777 \\776'")));
+ assertThat(values(tokens("'\\0 \\1 \\11 \\77 \\111 \\1111 \\377 \\777 \\776'")))
+ .isEqualTo("STRING(\0 \1 \t \u003f I I1 \u00ff \u00ff \u00fe) NEWLINE EOF");
// Test boundaries (non-octal char, EOF).
- assertEquals("STRING(\1b \1) NEWLINE EOF", values(tokens("'\\1b \\1'")));
+ assertThat(values(tokens("'\\1b \\1'"))).isEqualTo("STRING(\1b \1) NEWLINE EOF");
}
@Test
public void testTripleQuotedStrings() throws Exception {
- assertEquals("STRING(a\"b'c \n d\"\"e) NEWLINE EOF",
- values(tokens("\"\"\"a\"b'c \n d\"\"e\"\"\"")));
- assertEquals("STRING(a\"b'c \n d\"\"e) NEWLINE EOF",
- values(tokens("'''a\"b'c \n d\"\"e'''")));
+ assertThat(values(tokens("\"\"\"a\"b'c \n d\"\"e\"\"\"")))
+ .isEqualTo("STRING(a\"b'c \n d\"\"e) NEWLINE EOF");
+ assertThat(values(tokens("'''a\"b'c \n d\"\"e'''")))
+ .isEqualTo("STRING(a\"b'c \n d\"\"e) NEWLINE EOF");
}
@Test
public void testBadChar() throws Exception {
- assertEquals("IDENTIFIER(a) IDENTIFIER(b) NEWLINE EOF",
- values(tokens("a$b")));
- assertEquals("/some/path.txt:1: invalid character: '$'",
- lastError.toString());
+ assertThat(values(tokens("a$b"))).isEqualTo("IDENTIFIER(a) IDENTIFIER(b) NEWLINE EOF");
+ assertThat(lastError.toString()).isEqualTo("/some/path.txt:1: invalid character: '$'");
}
@Test
public void testIndentation() throws Exception {
- assertEquals("INT(1) NEWLINE INT(2) NEWLINE INT(3) NEWLINE EOF",
- values(tokens("1\n2\n3")));
- assertEquals("INT(1) NEWLINE INDENT INT(2) NEWLINE INT(3) NEWLINE OUTDENT "
- + "INT(4) NEWLINE EOF", values(tokens("1\n 2\n 3\n4 ")));
- assertEquals("INT(1) NEWLINE INDENT INT(2) NEWLINE INT(3) NEWLINE OUTDENT "
- + "NEWLINE EOF", values(tokens("1\n 2\n 3")));
- assertEquals("INT(1) NEWLINE INDENT INT(2) NEWLINE INDENT INT(3) NEWLINE "
- + "OUTDENT OUTDENT NEWLINE EOF",
- values(tokens("1\n 2\n 3")));
- assertEquals("INT(1) NEWLINE INDENT INT(2) NEWLINE INDENT INT(3) NEWLINE "
- + "OUTDENT INT(4) NEWLINE OUTDENT INT(5) NEWLINE EOF",
- values(tokens("1\n 2\n 3\n 4\n5")));
-
- assertEquals("INT(1) NEWLINE INDENT INT(2) NEWLINE INDENT INT(3) NEWLINE "
- + "OUTDENT INT(4) NEWLINE OUTDENT INT(5) NEWLINE EOF",
- values(tokens("1\n 2\n 3\n 4\n5")));
- assertEquals("/some/path.txt:4: indentation error", lastError.toString());
+ assertThat(values(tokens("1\n2\n3")))
+ .isEqualTo("INT(1) NEWLINE INT(2) NEWLINE INT(3) NEWLINE EOF");
+ assertThat(values(tokens("1\n 2\n 3\n4 ")))
+ .isEqualTo(
+ "INT(1) NEWLINE INDENT INT(2) NEWLINE INT(3) NEWLINE OUTDENT " + "INT(4) NEWLINE EOF");
+ assertThat(values(tokens("1\n 2\n 3")))
+ .isEqualTo("INT(1) NEWLINE INDENT INT(2) NEWLINE INT(3) NEWLINE OUTDENT " + "NEWLINE EOF");
+ assertThat(values(tokens("1\n 2\n 3")))
+ .isEqualTo(
+ "INT(1) NEWLINE INDENT INT(2) NEWLINE INDENT INT(3) NEWLINE "
+ + "OUTDENT OUTDENT NEWLINE EOF");
+ assertThat(values(tokens("1\n 2\n 3\n 4\n5")))
+ .isEqualTo(
+ "INT(1) NEWLINE INDENT INT(2) NEWLINE INDENT INT(3) NEWLINE "
+ + "OUTDENT INT(4) NEWLINE OUTDENT INT(5) NEWLINE EOF");
+
+ assertThat(values(tokens("1\n 2\n 3\n 4\n5")))
+ .isEqualTo(
+ "INT(1) NEWLINE INDENT INT(2) NEWLINE INDENT INT(3) NEWLINE "
+ + "OUTDENT INT(4) NEWLINE OUTDENT INT(5) NEWLINE EOF");
+ assertThat(lastError.toString()).isEqualTo("/some/path.txt:4: indentation error");
}
@Test
public void testIndentationWithCrLf() throws Exception {
- assertEquals("INT(1) NEWLINE INDENT INT(2) NEWLINE OUTDENT NEWLINE EOF",
- values(tokens("1\r\n 2\r\n")));
- assertEquals("INT(1) NEWLINE INDENT INT(2) NEWLINE OUTDENT NEWLINE EOF",
- values(tokens("1\r\n 2\r\n\r\n")));
- assertEquals("INT(1) NEWLINE INDENT INT(2) NEWLINE INDENT INT(3) NEWLINE OUTDENT INT(4) "
- + "NEWLINE OUTDENT INT(5) NEWLINE EOF",
- values(tokens("1\r\n 2\r\n 3\r\n 4\r\n5")));
- assertEquals(
- "INT(1) NEWLINE INDENT INT(2) NEWLINE INT(3) NEWLINE OUTDENT INT(4) NEWLINE EOF",
- values(tokens("1\r\n 2\r\n\r\n 3\r\n4")));
+ assertThat(values(tokens("1\r\n 2\r\n")))
+ .isEqualTo("INT(1) NEWLINE INDENT INT(2) NEWLINE OUTDENT NEWLINE EOF");
+ assertThat(values(tokens("1\r\n 2\r\n\r\n")))
+ .isEqualTo("INT(1) NEWLINE INDENT INT(2) NEWLINE OUTDENT NEWLINE EOF");
+ assertThat(values(tokens("1\r\n 2\r\n 3\r\n 4\r\n5")))
+ .isEqualTo(
+ "INT(1) NEWLINE INDENT INT(2) NEWLINE INDENT INT(3) NEWLINE OUTDENT INT(4) "
+ + "NEWLINE OUTDENT INT(5) NEWLINE EOF");
+ assertThat(values(tokens("1\r\n 2\r\n\r\n 3\r\n4")))
+ .isEqualTo(
+ "INT(1) NEWLINE INDENT INT(2) NEWLINE INT(3) NEWLINE OUTDENT INT(4) NEWLINE EOF");
}
@Test
public void testIndentationInsideParens() throws Exception {
// Indentation is ignored inside parens:
- assertEquals("INT(1) LPAREN INT(2) INT(3) INT(4) INT(5) NEWLINE EOF",
- values(tokens("1 (\n 2\n 3\n 4\n5")));
- assertEquals("INT(1) LBRACE INT(2) INT(3) INT(4) INT(5) NEWLINE EOF",
- values(tokens("1 {\n 2\n 3\n 4\n5")));
- assertEquals("INT(1) LBRACKET INT(2) INT(3) INT(4) INT(5) NEWLINE EOF",
- values(tokens("1 [\n 2\n 3\n 4\n5")));
- assertEquals("INT(1) LBRACKET INT(2) RBRACKET NEWLINE INDENT INT(3) "
- + "NEWLINE INT(4) NEWLINE OUTDENT INT(5) NEWLINE EOF",
- values(tokens("1 [\n 2]\n 3\n 4\n5")));
+ assertThat(values(tokens("1 (\n 2\n 3\n 4\n5")))
+ .isEqualTo("INT(1) LPAREN INT(2) INT(3) INT(4) INT(5) NEWLINE EOF");
+ assertThat(values(tokens("1 {\n 2\n 3\n 4\n5")))
+ .isEqualTo("INT(1) LBRACE INT(2) INT(3) INT(4) INT(5) NEWLINE EOF");
+ assertThat(values(tokens("1 [\n 2\n 3\n 4\n5")))
+ .isEqualTo("INT(1) LBRACKET INT(2) INT(3) INT(4) INT(5) NEWLINE EOF");
+ assertThat(values(tokens("1 [\n 2]\n 3\n 4\n5")))
+ .isEqualTo(
+ "INT(1) LBRACKET INT(2) RBRACKET NEWLINE INDENT INT(3) "
+ + "NEWLINE INT(4) NEWLINE OUTDENT INT(5) NEWLINE EOF");
}
@Test
public void testIndentationAtEOF() throws Exception {
// Matching OUTDENTS are created at EOF:
- assertEquals("INDENT INT(1) NEWLINE OUTDENT NEWLINE EOF",
- values(tokens("\n 1")));
+ assertThat(values(tokens("\n 1"))).isEqualTo("INDENT INT(1) NEWLINE OUTDENT NEWLINE EOF");
}
@Test
public void testBlankLineIndentation() throws Exception {
// Blank lines and comment lines should not generate any newlines indents
// (but note that every input ends with NEWLINE EOF).
- assertEquals("COMMENT NEWLINE EOF", names(tokens("\n #\n")));
- assertEquals("COMMENT NEWLINE EOF", names(tokens(" #")));
- assertEquals("COMMENT NEWLINE EOF", names(tokens(" #\n")));
- assertEquals("COMMENT NEWLINE EOF", names(tokens(" #comment\n")));
- assertEquals("DEF IDENTIFIER LPAREN IDENTIFIER RPAREN COLON NEWLINE "
- + "COMMENT INDENT RETURN IDENTIFIER NEWLINE "
- + "OUTDENT NEWLINE EOF",
- names(tokens("def f(x):\n"
- + " # comment\n"
- + "\n"
- + " \n"
- + " return x\n")));
+ assertThat(names(tokens("\n #\n"))).isEqualTo("COMMENT NEWLINE EOF");
+ assertThat(names(tokens(" #"))).isEqualTo("COMMENT NEWLINE EOF");
+ assertThat(names(tokens(" #\n"))).isEqualTo("COMMENT NEWLINE EOF");
+ assertThat(names(tokens(" #comment\n"))).isEqualTo("COMMENT NEWLINE EOF");
+ assertThat(names(tokens("def f(x):\n" + " # comment\n" + "\n" + " \n" + " return x\n")))
+ .isEqualTo(
+ "DEF IDENTIFIER LPAREN IDENTIFIER RPAREN COLON NEWLINE "
+ + "COMMENT INDENT RETURN IDENTIFIER NEWLINE "
+ + "OUTDENT NEWLINE EOF");
}
@Test
public void testMultipleCommentLines() throws Exception {
- assertEquals("COMMENT NEWLINE COMMENT COMMENT COMMENT "
- + "DEF IDENTIFIER LPAREN IDENTIFIER RPAREN COLON NEWLINE "
- + "INDENT RETURN IDENTIFIER NEWLINE OUTDENT NEWLINE EOF",
- names(tokens("# Copyright\n"
- + "#\n"
- + "# A comment line\n"
- + "# An adjoining line\n"
- + "def f(x):\n"
- + " return x\n")));
+ assertThat(
+ names(
+ tokens(
+ "# Copyright\n"
+ + "#\n"
+ + "# A comment line\n"
+ + "# An adjoining line\n"
+ + "def f(x):\n"
+ + " return x\n")))
+ .isEqualTo(
+ "COMMENT NEWLINE COMMENT COMMENT COMMENT "
+ + "DEF IDENTIFIER LPAREN IDENTIFIER RPAREN COLON NEWLINE "
+ + "INDENT RETURN IDENTIFIER NEWLINE OUTDENT NEWLINE EOF");
}
@Test
public void testBackslash() throws Exception {
- assertEquals("IDENTIFIER IDENTIFIER NEWLINE EOF",
- names(tokens("a\\\nb")));
- assertEquals("IDENTIFIER IDENTIFIER NEWLINE EOF", names(tokens("a\\\r\nb")));
- assertEquals("IDENTIFIER ILLEGAL IDENTIFIER NEWLINE EOF",
- names(tokens("a\\ b")));
- assertEquals("IDENTIFIER LPAREN INT RPAREN NEWLINE EOF",
- names(tokens("a(\\\n2)")));
+ assertThat(names(tokens("a\\\nb"))).isEqualTo("IDENTIFIER IDENTIFIER NEWLINE EOF");
+ assertThat(names(tokens("a\\\r\nb"))).isEqualTo("IDENTIFIER IDENTIFIER NEWLINE EOF");
+ assertThat(names(tokens("a\\ b"))).isEqualTo("IDENTIFIER ILLEGAL IDENTIFIER NEWLINE EOF");
+ assertThat(names(tokens("a(\\\n2)"))).isEqualTo("IDENTIFIER LPAREN INT RPAREN NEWLINE EOF");
}
@Test
@@ -450,43 +430,41 @@ public class LexerTest {
@Test
public void testLineNumbers() throws Exception {
- assertEquals("1 1 1 1 2 2 2 2 4 4 4 4 4",
- linenums("foo = 1\nbar = 2\n\nwiz = 3"));
+ assertThat(linenums("foo = 1\nbar = 2\n\nwiz = 3")).isEqualTo("1 1 1 1 2 2 2 2 4 4 4 4 4");
- assertEquals("IDENTIFIER(foo) EQUALS INT(1) NEWLINE "
- + "IDENTIFIER(bar) EQUALS INT(2) NEWLINE "
- + "IDENTIFIER(wiz) EQUALS NEWLINE "
- + "IDENTIFIER(bar) EQUALS INT(2) NEWLINE EOF",
- values(tokens("foo = 1\nbar = 2\n\nwiz = $\nbar = 2")));
- assertEquals("/some/path.txt:4: invalid character: '$'",
- lastError.toString());
+ assertThat(values(tokens("foo = 1\nbar = 2\n\nwiz = $\nbar = 2")))
+ .isEqualTo(
+ "IDENTIFIER(foo) EQUALS INT(1) NEWLINE "
+ + "IDENTIFIER(bar) EQUALS INT(2) NEWLINE "
+ + "IDENTIFIER(wiz) EQUALS NEWLINE "
+ + "IDENTIFIER(bar) EQUALS INT(2) NEWLINE EOF");
+ assertThat(lastError.toString()).isEqualTo("/some/path.txt:4: invalid character: '$'");
// '\\n' in string should not increment linenum:
String s = "1\n'foo\\nbar'\3";
- assertEquals("INT(1) NEWLINE STRING(foo\nbar) NEWLINE EOF",
- values(tokens(s)));
- assertEquals("1 1 2 2 2", linenums(s));
+ assertThat(values(tokens(s))).isEqualTo("INT(1) NEWLINE STRING(foo\nbar) NEWLINE EOF");
+ assertThat(linenums(s)).isEqualTo("1 1 2 2 2");
}
@Test
public void testContainsErrors() throws Exception {
Lexer lexerSuccess = createLexer("foo");
- assertFalse(lexerSuccess.containsErrors());
+ assertThat(lexerSuccess.containsErrors()).isFalse();
Lexer lexerFail = createLexer("f$o");
- assertTrue(lexerFail.containsErrors());
+ assertThat(lexerFail.containsErrors()).isTrue();
String s = "'unterminated";
lexerFail = createLexer(s);
- assertTrue(lexerFail.containsErrors());
- assertEquals(0, lastErrorLocation.getStartOffset());
- assertEquals(s.length(), lastErrorLocation.getEndOffset());
- assertEquals("STRING(unterminated) NEWLINE EOF", values(tokens(s)));
+ assertThat(lexerFail.containsErrors()).isTrue();
+ assertThat(lastErrorLocation.getStartOffset()).isEqualTo(0);
+ assertThat(lastErrorLocation.getEndOffset()).isEqualTo(s.length());
+ assertThat(values(tokens(s))).isEqualTo("STRING(unterminated) NEWLINE EOF");
}
@Test
public void testUnterminatedRawStringWithEscapingError() throws Exception {
- assertEquals("STRING NEWLINE EOF", names(tokens("r'\\")));
- assertEquals("/some/path.txt:1: unterminated string literal at eof", lastError);
+ assertThat(names(tokens("r'\\"))).isEqualTo("STRING NEWLINE EOF");
+ assertThat(lastError).isEqualTo("/some/path.txt:1: unterminated string literal at eof");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/LineNumberTableTest.java b/src/test/java/com/google/devtools/build/lib/syntax/LineNumberTableTest.java
index 4377b3527a..e7b4964f6a 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/LineNumberTableTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/LineNumberTableTest.java
@@ -13,12 +13,11 @@
// limitations under the License.
package com.google.devtools.build.lib.syntax;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.events.Location.LineAndColumn;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -35,23 +34,23 @@ public class LineNumberTableTest {
@Test
public void testEmpty() {
LineNumberTable table = create("");
- assertEquals(new LineAndColumn(1, 1), table.getLineAndColumn(0));
+ assertThat(table.getLineAndColumn(0)).isEqualTo(new LineAndColumn(1, 1));
}
@Test
public void testNewline() {
LineNumberTable table = create("\n");
- assertEquals(new LineAndColumn(1, 1), table.getLineAndColumn(0));
- assertEquals(new LineAndColumn(2, 1), table.getLineAndColumn(1));
+ assertThat(table.getLineAndColumn(0)).isEqualTo(new LineAndColumn(1, 1));
+ assertThat(table.getLineAndColumn(1)).isEqualTo(new LineAndColumn(2, 1));
}
@Test
public void testOneLiner() {
LineNumberTable table = create("foo");
- assertEquals(new LineAndColumn(1, 1), table.getLineAndColumn(0));
- assertEquals(new LineAndColumn(1, 2), table.getLineAndColumn(1));
- assertEquals(new LineAndColumn(1, 3), table.getLineAndColumn(2));
- assertEquals(Pair.of(0, 3), table.getOffsetsForLine(1));
+ assertThat(table.getLineAndColumn(0)).isEqualTo(new LineAndColumn(1, 1));
+ assertThat(table.getLineAndColumn(1)).isEqualTo(new LineAndColumn(1, 2));
+ assertThat(table.getLineAndColumn(2)).isEqualTo(new LineAndColumn(1, 3));
+ assertThat(table.getOffsetsForLine(1)).isEqualTo(Pair.of(0, 3));
}
@Test
@@ -59,29 +58,29 @@ public class LineNumberTableTest {
LineNumberTable table = create("\ntwo\nthree\n\nfive\n");
// \n
- assertEquals(new LineAndColumn(1, 1), table.getLineAndColumn(0));
- assertEquals(Pair.of(0, 1), table.getOffsetsForLine(1));
+ assertThat(table.getLineAndColumn(0)).isEqualTo(new LineAndColumn(1, 1));
+ assertThat(table.getOffsetsForLine(1)).isEqualTo(Pair.of(0, 1));
// two\n
- assertEquals(new LineAndColumn(2, 1), table.getLineAndColumn(1));
- assertEquals(new LineAndColumn(2, 2), table.getLineAndColumn(2));
- assertEquals(new LineAndColumn(2, 3), table.getLineAndColumn(3));
- assertEquals(new LineAndColumn(2, 4), table.getLineAndColumn(4));
- assertEquals(Pair.of(1, 5), table.getOffsetsForLine(2));
+ assertThat(table.getLineAndColumn(1)).isEqualTo(new LineAndColumn(2, 1));
+ assertThat(table.getLineAndColumn(2)).isEqualTo(new LineAndColumn(2, 2));
+ assertThat(table.getLineAndColumn(3)).isEqualTo(new LineAndColumn(2, 3));
+ assertThat(table.getLineAndColumn(4)).isEqualTo(new LineAndColumn(2, 4));
+ assertThat(table.getOffsetsForLine(2)).isEqualTo(Pair.of(1, 5));
// three\n
- assertEquals(new LineAndColumn(3, 1), table.getLineAndColumn(5));
- assertEquals(new LineAndColumn(3, 6), table.getLineAndColumn(10));
- assertEquals(Pair.of(5, 11), table.getOffsetsForLine(3));
+ assertThat(table.getLineAndColumn(5)).isEqualTo(new LineAndColumn(3, 1));
+ assertThat(table.getLineAndColumn(10)).isEqualTo(new LineAndColumn(3, 6));
+ assertThat(table.getOffsetsForLine(3)).isEqualTo(Pair.of(5, 11));
// \n
- assertEquals(new LineAndColumn(4, 1), table.getLineAndColumn(11));
- assertEquals(Pair.of(11, 12), table.getOffsetsForLine(4));
+ assertThat(table.getLineAndColumn(11)).isEqualTo(new LineAndColumn(4, 1));
+ assertThat(table.getOffsetsForLine(4)).isEqualTo(Pair.of(11, 12));
// five\n
- assertEquals(new LineAndColumn(5, 1), table.getLineAndColumn(12));
- assertEquals(new LineAndColumn(5, 5), table.getLineAndColumn(16));
- assertEquals(Pair.of(12, 17), table.getOffsetsForLine(5));
+ assertThat(table.getLineAndColumn(12)).isEqualTo(new LineAndColumn(5, 1));
+ assertThat(table.getLineAndColumn(16)).isEqualTo(new LineAndColumn(5, 5));
+ assertThat(table.getOffsetsForLine(5)).isEqualTo(Pair.of(12, 17));
}
@Test
@@ -96,25 +95,27 @@ public class LineNumberTableTest {
LineNumberTable table = create(data);
// Note: no attempt is made to return accurate column information.
- assertEquals(new LineAndColumn(67, 1), table.getLineAndColumn(data.indexOf("cc_binary")));
- assertEquals(new LineAndColumn(67, 1), table.getLineAndColumn(data.indexOf("name='a'")));
- assertEquals("/fake/file", table.getPath(0).toString());
+ assertThat(table.getLineAndColumn(data.indexOf("cc_binary")))
+ .isEqualTo(new LineAndColumn(67, 1));
+ assertThat(table.getLineAndColumn(data.indexOf("name='a'")))
+ .isEqualTo(new LineAndColumn(67, 1));
+ assertThat(table.getPath(0).toString()).isEqualTo("/fake/file");
// Note: newlines ignored; "srcs" is still (intentionally) considered to be
// on L67. Consider the alternative, and assume that rule 'a' is 50 lines
// when pretty-printed: the last line of 'a' would be reported as line 67 +
// 50, which may be in a part of the original BUILD file that has nothing
// to do with this rule. In other words, the size of rules before and
// after pretty printing are essentially unrelated.
- assertEquals(new LineAndColumn(67, 1), table.getLineAndColumn(data.indexOf("srcs")));
- assertEquals("/foo", table.getPath(data.indexOf("srcs")).toString());
- assertEquals(Pair.of(2, 57), table.getOffsetsForLine(67));
+ assertThat(table.getLineAndColumn(data.indexOf("srcs"))).isEqualTo(new LineAndColumn(67, 1));
+ assertThat(table.getPath(data.indexOf("srcs")).toString()).isEqualTo("/foo");
+ assertThat(table.getOffsetsForLine(67)).isEqualTo(Pair.of(2, 57));
- assertEquals(new LineAndColumn(23, 1), table.getLineAndColumn(data.indexOf("vardef")));
- assertEquals(new LineAndColumn(23, 1), table.getLineAndColumn(data.indexOf("x,y")));
- assertEquals("/ba.r", table.getPath(data.indexOf("x,y")).toString());
- assertEquals(Pair.of(57, 86), table.getOffsetsForLine(23));
+ assertThat(table.getLineAndColumn(data.indexOf("vardef"))).isEqualTo(new LineAndColumn(23, 1));
+ assertThat(table.getLineAndColumn(data.indexOf("x,y"))).isEqualTo(new LineAndColumn(23, 1));
+ assertThat(table.getPath(data.indexOf("x,y")).toString()).isEqualTo("/ba.r");
+ assertThat(table.getOffsetsForLine(23)).isEqualTo(Pair.of(57, 86));
- assertEquals(Pair.of(0, 0), table.getOffsetsForLine(42));
+ assertThat(table.getOffsetsForLine(42)).isEqualTo(Pair.of(0, 0));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java b/src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java
index fb9c5cccc4..6b93e7e938 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java
@@ -16,7 +16,6 @@ package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.syntax.SkylarkList.MutableList;
import com.google.devtools.build.lib.syntax.util.EvaluationTestCase;
@@ -1700,7 +1699,7 @@ public class MethodLibraryTest extends EvaluationTestCase {
eval("a = select({'a': 1})");
SelectorList result = (SelectorList) lookup("a");
assertThat(((SelectorValue) Iterables.getOnlyElement(result.getElements())).getDictionary())
- .isEqualTo(ImmutableMap.of("a", 1));
+ .containsExactly("a", 1);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/ParserInputSourceTest.java b/src/test/java/com/google/devtools/build/lib/syntax/ParserInputSourceTest.java
index 467a5ba84d..ce459d2eb8 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/ParserInputSourceTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/ParserInputSourceTest.java
@@ -15,23 +15,18 @@ package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.util.StringUtilities.joinLines;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
-
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-
-/**
- * A test case for {@link ParserInputSource}.
- */
+/** A test case for {@link ParserInputSource}. */
@RunWith(JUnit4.class)
public class ParserInputSourceTest {
@@ -42,8 +37,8 @@ public class ParserInputSourceTest {
String content = joinLines("Line 1", "Line 2", "Line 3", "");
Path file = scratch.file("/tmp/my/file.txt", content.getBytes(StandardCharsets.UTF_8));
ParserInputSource input = ParserInputSource.create(file);
- assertEquals(content, new String(input.getContent()));
- assertEquals("/tmp/my/file.txt", input.getPath().toString());
+ assertThat(new String(input.getContent())).isEqualTo(content);
+ assertThat(input.getPath().toString()).isEqualTo("/tmp/my/file.txt");
}
@Test
@@ -51,8 +46,8 @@ public class ParserInputSourceTest {
String content = "Content provided as a string.";
String pathName = "/the/name/of/the/content.txt";
ParserInputSource input = ParserInputSource.create(content, PathFragment.create(pathName));
- assertEquals(content, new String(input.getContent()));
- assertEquals(pathName, input.getPath().toString());
+ assertThat(new String(input.getContent())).isEqualTo(content);
+ assertThat(input.getPath().toString()).isEqualTo(pathName);
}
@Test
@@ -61,8 +56,8 @@ public class ParserInputSourceTest {
String pathName = "/the/name/of/the/content.txt";
char[] contentChars = content.toCharArray();
ParserInputSource input = ParserInputSource.create(contentChars, PathFragment.create(pathName));
- assertEquals(content, new String(input.getContent()));
- assertEquals(pathName, input.getPath().toString());
+ assertThat(new String(input.getContent())).isEqualTo(content);
+ assertThat(input.getPath().toString()).isEqualTo(pathName);
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/ParserTest.java b/src/test/java/com/google/devtools/build/lib/syntax/ParserTest.java
index e107d1b6bd..ad7d1c804b 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/ParserTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/ParserTest.java
@@ -15,9 +15,6 @@ package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -91,35 +88,35 @@ public class ParserTest extends EvaluationTestCase {
BinaryOperatorExpression e =
(BinaryOperatorExpression) parseExpression("'%sx' % 'foo' + 'bar'");
- assertEquals(Operator.PLUS, e.getOperator());
+ assertThat(e.getOperator()).isEqualTo(Operator.PLUS);
}
@Test
public void testPrecedence2() throws Exception {
BinaryOperatorExpression e =
(BinaryOperatorExpression) parseExpression("('%sx' % 'foo') + 'bar'");
- assertEquals(Operator.PLUS, e.getOperator());
+ assertThat(e.getOperator()).isEqualTo(Operator.PLUS);
}
@Test
public void testPrecedence3() throws Exception {
BinaryOperatorExpression e =
(BinaryOperatorExpression) parseExpression("'%sx' % ('foo' + 'bar')");
- assertEquals(Operator.PERCENT, e.getOperator());
+ assertThat(e.getOperator()).isEqualTo(Operator.PERCENT);
}
@Test
public void testPrecedence4() throws Exception {
BinaryOperatorExpression e =
(BinaryOperatorExpression) parseExpression("1 + - (2 - 3)");
- assertEquals(Operator.PLUS, e.getOperator());
+ assertThat(e.getOperator()).isEqualTo(Operator.PLUS);
}
@Test
public void testPrecedence5() throws Exception {
BinaryOperatorExpression e =
(BinaryOperatorExpression) parseExpression("2 * x | y + 1");
- assertEquals(Operator.PIPE, e.getOperator());
+ assertThat(e.getOperator()).isEqualTo(Operator.PIPE);
}
@Test
@@ -127,14 +124,14 @@ public class ParserTest extends EvaluationTestCase {
FuncallExpression e = (FuncallExpression) parseExpression("-5");
FuncallExpression e2 = (FuncallExpression) parseExpression("- 5");
- assertEquals("-", e.getFunction().getName());
- assertEquals("-", e2.getFunction().getName());
+ assertThat(e.getFunction().getName()).isEqualTo("-");
+ assertThat(e2.getFunction().getName()).isEqualTo("-");
assertThat(e.getArguments()).hasSize(1);
- assertEquals(1, e.getNumPositionalArguments());
+ assertThat(e.getNumPositionalArguments()).isEqualTo(1);
IntegerLiteral arg0 = (IntegerLiteral) e.getArguments().get(0).getValue();
- assertEquals(5, (int) arg0.getValue());
+ assertThat((int) arg0.getValue()).isEqualTo(5);
}
@Test
@@ -142,21 +139,21 @@ public class ParserTest extends EvaluationTestCase {
FuncallExpression e = (FuncallExpression) parseExpression("foo(1, 2, bar=wiz)");
Identifier ident = e.getFunction();
- assertEquals("foo", ident.getName());
+ assertThat(ident.getName()).isEqualTo("foo");
assertThat(e.getArguments()).hasSize(3);
- assertEquals(2, e.getNumPositionalArguments());
+ assertThat(e.getNumPositionalArguments()).isEqualTo(2);
IntegerLiteral arg0 = (IntegerLiteral) e.getArguments().get(0).getValue();
- assertEquals(1, (int) arg0.getValue());
+ assertThat((int) arg0.getValue()).isEqualTo(1);
IntegerLiteral arg1 = (IntegerLiteral) e.getArguments().get(1).getValue();
- assertEquals(2, (int) arg1.getValue());
+ assertThat((int) arg1.getValue()).isEqualTo(2);
Argument.Passed arg2 = e.getArguments().get(2);
- assertEquals("bar", arg2.getName());
+ assertThat(arg2.getName()).isEqualTo("bar");
Identifier arg2val = (Identifier) arg2.getValue();
- assertEquals("wiz", arg2val.getName());
+ assertThat(arg2val.getName()).isEqualTo("wiz");
}
@Test
@@ -165,21 +162,21 @@ public class ParserTest extends EvaluationTestCase {
(FuncallExpression) parseExpression("foo.foo(1, 2, bar=wiz)");
Identifier ident = e.getFunction();
- assertEquals("foo", ident.getName());
+ assertThat(ident.getName()).isEqualTo("foo");
assertThat(e.getArguments()).hasSize(3);
- assertEquals(2, e.getNumPositionalArguments());
+ assertThat(e.getNumPositionalArguments()).isEqualTo(2);
IntegerLiteral arg0 = (IntegerLiteral) e.getArguments().get(0).getValue();
- assertEquals(1, (int) arg0.getValue());
+ assertThat((int) arg0.getValue()).isEqualTo(1);
IntegerLiteral arg1 = (IntegerLiteral) e.getArguments().get(1).getValue();
- assertEquals(2, (int) arg1.getValue());
+ assertThat((int) arg1.getValue()).isEqualTo(2);
Argument.Passed arg2 = e.getArguments().get(2);
- assertEquals("bar", arg2.getName());
+ assertThat(arg2.getName()).isEqualTo("bar");
Identifier arg2val = (Identifier) arg2.getValue();
- assertEquals("wiz", arg2val.getName());
+ assertThat(arg2val.getName()).isEqualTo("wiz");
}
@Test
@@ -188,13 +185,13 @@ public class ParserTest extends EvaluationTestCase {
(FuncallExpression) parseExpression("foo.replace().split(1)");
Identifier ident = e.getFunction();
- assertEquals("split", ident.getName());
+ assertThat(ident.getName()).isEqualTo("split");
assertThat(e.getArguments()).hasSize(1);
- assertEquals(1, e.getNumPositionalArguments());
+ assertThat(e.getNumPositionalArguments()).isEqualTo(1);
IntegerLiteral arg0 = (IntegerLiteral) e.getArguments().get(0).getValue();
- assertEquals(1, (int) arg0.getValue());
+ assertThat((int) arg0.getValue()).isEqualTo(1);
}
@Test
@@ -202,7 +199,7 @@ public class ParserTest extends EvaluationTestCase {
DotExpression e = (DotExpression) parseExpression("foo.foo");
Identifier ident = e.getField();
- assertEquals("foo", ident.getName());
+ assertThat(ident.getName()).isEqualTo("foo");
}
@Test
@@ -210,7 +207,7 @@ public class ParserTest extends EvaluationTestCase {
FuncallExpression e = (FuncallExpression) parseExpression("'foo'.foo()");
Identifier ident = e.getFunction();
- assertEquals("foo", ident.getName());
+ assertThat(ident.getName()).isEqualTo("foo");
assertThat(e.getArguments()).isEmpty();
}
@@ -218,27 +215,27 @@ public class ParserTest extends EvaluationTestCase {
@Test
public void testStringLiteralOptimizationValue() throws Exception {
StringLiteral l = (StringLiteral) parseExpression("'abc' + 'def'");
- assertEquals("abcdef", l.value);
+ assertThat(l.value).isEqualTo("abcdef");
}
@Test
public void testStringLiteralOptimizationToString() throws Exception {
StringLiteral l = (StringLiteral) parseExpression("'abc' + 'def'");
- assertEquals("\"abcdef\"", l.toString());
+ assertThat(l.toString()).isEqualTo("\"abcdef\"");
}
@Test
public void testStringLiteralOptimizationLocation() throws Exception {
StringLiteral l = (StringLiteral) parseExpression("'abc' + 'def'");
- assertEquals(0, l.getLocation().getStartOffset());
- assertEquals(13, l.getLocation().getEndOffset());
+ assertThat(l.getLocation().getStartOffset()).isEqualTo(0);
+ assertThat(l.getLocation().getEndOffset()).isEqualTo(13);
}
@Test
public void testStringLiteralOptimizationDifferentQuote() throws Exception {
StringLiteral l = (StringLiteral) parseExpression("'abc' + \"def\"");
- assertEquals(0, l.getLocation().getStartOffset());
- assertEquals(13, l.getLocation().getEndOffset());
+ assertThat(l.getLocation().getStartOffset()).isEqualTo(0);
+ assertThat(l.getLocation().getEndOffset()).isEqualTo(13);
}
@Test
@@ -248,7 +245,7 @@ public class ParserTest extends EvaluationTestCase {
FuncallExpression e = (FuncallExpression) parseExpression(
"'FOO.CC'.lower()[1:].startswith('oo')");
- assertEquals("startswith", e.getFunction().getName());
+ assertThat(e.getFunction().getName()).isEqualTo("startswith");
assertThat(e.getArguments()).hasSize(1);
s = (SliceExpression) parseExpression("'FOO.CC'[1:][:2]");
@@ -313,24 +310,24 @@ public class ParserTest extends EvaluationTestCase {
// Test that the actual parameters are: (1, $error$, 3):
Identifier ident = e.getFunction();
- assertEquals("f", ident.getName());
+ assertThat(ident.getName()).isEqualTo("f");
assertThat(e.getArguments()).hasSize(3);
- assertEquals(3, e.getNumPositionalArguments());
+ assertThat(e.getNumPositionalArguments()).isEqualTo(3);
IntegerLiteral arg0 = (IntegerLiteral) e.getArguments().get(0).getValue();
- assertEquals(1, (int) arg0.getValue());
+ assertThat((int) arg0.getValue()).isEqualTo(1);
Argument.Passed arg1 = e.getArguments().get(1);
Identifier arg1val = ((Identifier) arg1.getValue());
- assertEquals("$error$", arg1val.getName());
+ assertThat(arg1val.getName()).isEqualTo("$error$");
assertLocation(5, 29, arg1val.getLocation());
- assertEquals("[x for foo foo foo foo]", expr.substring(5, 28));
- assertEquals(30, arg1val.getLocation().getEndLineAndColumn().getColumn());
+ assertThat(expr.substring(5, 28)).isEqualTo("[x for foo foo foo foo]");
+ assertThat(arg1val.getLocation().getEndLineAndColumn().getColumn()).isEqualTo(30);
IntegerLiteral arg2 = (IntegerLiteral) e.getArguments().get(2).getValue();
- assertEquals(3, (int) arg2.getValue());
+ assertThat((int) arg2.getValue()).isEqualTo(3);
}
@Test
@@ -370,7 +367,7 @@ public class ParserTest extends EvaluationTestCase {
public void testAssignLocation() {
List<Statement> statements = parseFile("a = b;c = d\n");
Statement statement = statements.get(0);
- assertEquals(5, statement.getLocation().getEndOffset());
+ assertThat(statement.getLocation().getEndOffset()).isEqualTo(5);
}
@Test
@@ -430,30 +427,31 @@ public class ParserTest extends EvaluationTestCase {
@Test
public void testAugmentedAssign() throws Exception {
- assertEquals("[x += 1\n]", parseFile("x += 1").toString());
- assertEquals("[x -= 1\n]", parseFile("x -= 1").toString());
- assertEquals("[x *= 1\n]", parseFile("x *= 1").toString());
- assertEquals("[x /= 1\n]", parseFile("x /= 1").toString());
- assertEquals("[x %= 1\n]", parseFile("x %= 1").toString());
+ assertThat(parseFile("x += 1").toString()).isEqualTo("[x += 1\n]");
+ assertThat(parseFile("x -= 1").toString()).isEqualTo("[x -= 1\n]");
+ assertThat(parseFile("x *= 1").toString()).isEqualTo("[x *= 1\n]");
+ assertThat(parseFile("x /= 1").toString()).isEqualTo("[x /= 1\n]");
+ assertThat(parseFile("x %= 1").toString()).isEqualTo("[x %= 1\n]");
}
@Test
public void testPrettyPrintFunctions() throws Exception {
- assertEquals("[x[1:3]\n]", parseFile("x[1:3]").toString());
- assertEquals("[x[1:3]\n]", parseFile("x[1:3:1]").toString());
- assertEquals("[x[1:3:2]\n]", parseFile("x[1:3:2]").toString());
- assertEquals("[x[1::2]\n]", parseFile("x[1::2]").toString());
- assertEquals("[x[1:]\n]", parseFile("x[1:]").toString());
- assertEquals("[str[42]\n]", parseFile("str[42]").toString());
- assertEquals("[ctx.new_file(\"hello\")\n]", parseFile("ctx.new_file('hello')").toString());
- assertEquals("[new_file(\"hello\")\n]", parseFile("new_file(\"hello\")").toString());
+ assertThat(parseFile("x[1:3]").toString()).isEqualTo("[x[1:3]\n]");
+ assertThat(parseFile("x[1:3:1]").toString()).isEqualTo("[x[1:3]\n]");
+ assertThat(parseFile("x[1:3:2]").toString()).isEqualTo("[x[1:3:2]\n]");
+ assertThat(parseFile("x[1::2]").toString()).isEqualTo("[x[1::2]\n]");
+ assertThat(parseFile("x[1:]").toString()).isEqualTo("[x[1:]\n]");
+ assertThat(parseFile("str[42]").toString()).isEqualTo("[str[42]\n]");
+ assertThat(parseFile("ctx.new_file('hello')").toString())
+ .isEqualTo("[ctx.new_file(\"hello\")\n]");
+ assertThat(parseFile("new_file(\"hello\")").toString()).isEqualTo("[new_file(\"hello\")\n]");
}
@Test
public void testFuncallLocation() {
List<Statement> statements = parseFile("a(b);c = d\n");
Statement statement = statements.get(0);
- assertEquals(4, statement.getLocation().getEndOffset());
+ assertThat(statement.getLocation().getEndOffset()).isEqualTo(4);
}
@Test
@@ -472,30 +470,30 @@ public class ParserTest extends EvaluationTestCase {
public void testListPositions() throws Exception {
String expr = "[0,f(1),2]";
ListLiteral list = (ListLiteral) parseExpression(expr);
- assertEquals("[0,f(1),2]", getText(expr, list));
- assertEquals("0", getText(expr, getElem(list, 0)));
- assertEquals("f(1)", getText(expr, getElem(list, 1)));
- assertEquals("2", getText(expr, getElem(list, 2)));
+ assertThat(getText(expr, list)).isEqualTo("[0,f(1),2]");
+ assertThat(getText(expr, getElem(list, 0))).isEqualTo("0");
+ assertThat(getText(expr, getElem(list, 1))).isEqualTo("f(1)");
+ assertThat(getText(expr, getElem(list, 2))).isEqualTo("2");
}
@Test
public void testDictPositions() throws Exception {
String expr = "{1:2,2:f(1),3:4}";
DictionaryLiteral list = (DictionaryLiteral) parseExpression(expr);
- assertEquals("{1:2,2:f(1),3:4}", getText(expr, list));
- assertEquals("1:2", getText(expr, getElem(list, 0)));
- assertEquals("2:f(1)", getText(expr, getElem(list, 1)));
- assertEquals("3:4", getText(expr, getElem(list, 2)));
+ assertThat(getText(expr, list)).isEqualTo("{1:2,2:f(1),3:4}");
+ assertThat(getText(expr, getElem(list, 0))).isEqualTo("1:2");
+ assertThat(getText(expr, getElem(list, 1))).isEqualTo("2:f(1)");
+ assertThat(getText(expr, getElem(list, 2))).isEqualTo("3:4");
}
@Test
public void testArgumentPositions() throws Exception {
String stmt = "f(0,g(1,2),2)";
FuncallExpression f = (FuncallExpression) parseExpression(stmt);
- assertEquals(stmt, getText(stmt, f));
- assertEquals("0", getText(stmt, getArg(f, 0)));
- assertEquals("g(1,2)", getText(stmt, getArg(f, 1)));
- assertEquals("2", getText(stmt, getArg(f, 2)));
+ assertThat(getText(stmt, f)).isEqualTo(stmt);
+ assertThat(getText(stmt, getArg(f, 0))).isEqualTo("0");
+ assertThat(getText(stmt, getArg(f, 1))).isEqualTo("g(1,2)");
+ assertThat(getText(stmt, getArg(f, 2))).isEqualTo("2");
}
@Test
@@ -526,33 +524,33 @@ public class ParserTest extends EvaluationTestCase {
@Test
public void testListLiterals1() throws Exception {
ListLiteral list = (ListLiteral) parseExpression("[0,1,2]");
- assertFalse(list.isTuple());
+ assertThat(list.isTuple()).isFalse();
assertThat(list.getElements()).hasSize(3);
- assertFalse(list.isTuple());
+ assertThat(list.isTuple()).isFalse();
for (int i = 0; i < 3; ++i) {
- assertEquals(i, getIntElem(list, i));
+ assertThat(getIntElem(list, i)).isEqualTo(i);
}
}
@Test
public void testTupleLiterals2() throws Exception {
ListLiteral tuple = (ListLiteral) parseExpression("(0,1,2)");
- assertTrue(tuple.isTuple());
+ assertThat(tuple.isTuple()).isTrue();
assertThat(tuple.getElements()).hasSize(3);
- assertTrue(tuple.isTuple());
+ assertThat(tuple.isTuple()).isTrue();
for (int i = 0; i < 3; ++i) {
- assertEquals(i, getIntElem(tuple, i));
+ assertThat(getIntElem(tuple, i)).isEqualTo(i);
}
}
@Test
public void testTupleWithoutParens() throws Exception {
ListLiteral tuple = (ListLiteral) parseExpression("0, 1, 2");
- assertTrue(tuple.isTuple());
+ assertThat(tuple.isTuple()).isTrue();
assertThat(tuple.getElements()).hasSize(3);
- assertTrue(tuple.isTuple());
+ assertThat(tuple.isTuple()).isTrue();
for (int i = 0; i < 3; ++i) {
- assertEquals(i, getIntElem(tuple, i));
+ assertThat(getIntElem(tuple, i)).isEqualTo(i);
}
}
@@ -570,56 +568,56 @@ public class ParserTest extends EvaluationTestCase {
clearEvents();
ListLiteral tuple = (ListLiteral) parseExpression("(0, 1, 2, 3,)");
- assertTrue(tuple.isTuple());
+ assertThat(tuple.isTuple()).isTrue();
assertThat(tuple.getElements()).hasSize(4);
- assertTrue(tuple.isTuple());
+ assertThat(tuple.isTuple()).isTrue();
for (int i = 0; i < 4; ++i) {
- assertEquals(i, getIntElem(tuple, i));
+ assertThat(getIntElem(tuple, i)).isEqualTo(i);
}
}
@Test
public void testTupleLiterals3() throws Exception {
ListLiteral emptyTuple = (ListLiteral) parseExpression("()");
- assertTrue(emptyTuple.isTuple());
+ assertThat(emptyTuple.isTuple()).isTrue();
assertThat(emptyTuple.getElements()).isEmpty();
}
@Test
public void testTupleLiterals4() throws Exception {
ListLiteral singletonTuple = (ListLiteral) parseExpression("(42,)");
- assertTrue(singletonTuple.isTuple());
+ assertThat(singletonTuple.isTuple()).isTrue();
assertThat(singletonTuple.getElements()).hasSize(1);
- assertEquals(42, getIntElem(singletonTuple, 0));
+ assertThat(getIntElem(singletonTuple, 0)).isEqualTo(42);
}
@Test
public void testTupleLiterals5() throws Exception {
IntegerLiteral intLit = (IntegerLiteral) parseExpression("(42)"); // not a tuple!
- assertEquals(42, (int) intLit.getValue());
+ assertThat((int) intLit.getValue()).isEqualTo(42);
}
@Test
public void testListLiterals6() throws Exception {
ListLiteral emptyList = (ListLiteral) parseExpression("[]");
- assertFalse(emptyList.isTuple());
+ assertThat(emptyList.isTuple()).isFalse();
assertThat(emptyList.getElements()).isEmpty();
}
@Test
public void testListLiterals7() throws Exception {
ListLiteral singletonList = (ListLiteral) parseExpression("[42,]");
- assertFalse(singletonList.isTuple());
+ assertThat(singletonList.isTuple()).isFalse();
assertThat(singletonList.getElements()).hasSize(1);
- assertEquals(42, getIntElem(singletonList, 0));
+ assertThat(getIntElem(singletonList, 0)).isEqualTo(42);
}
@Test
public void testListLiterals8() throws Exception {
ListLiteral singletonList = (ListLiteral) parseExpression("[42]"); // a singleton
- assertFalse(singletonList.isTuple());
+ assertThat(singletonList.isTuple()).isFalse();
assertThat(singletonList.getElements()).hasSize(1);
- assertEquals(42, getIntElem(singletonList, 0));
+ assertThat(getIntElem(singletonList, 0)).isEqualTo(42);
}
@Test
@@ -628,8 +626,8 @@ public class ParserTest extends EvaluationTestCase {
(DictionaryLiteral) parseExpression("{1:42}"); // a singleton dictionary
assertThat(dictionaryList.getEntries()).hasSize(1);
DictionaryEntryLiteral tuple = getElem(dictionaryList, 0);
- assertEquals(1, getIntElem(tuple, true));
- assertEquals(42, getIntElem(tuple, false));
+ assertThat(getIntElem(tuple, true)).isEqualTo(1);
+ assertThat(getIntElem(tuple, false)).isEqualTo(42);
}
@Test
@@ -645,8 +643,8 @@ public class ParserTest extends EvaluationTestCase {
(DictionaryLiteral) parseExpression("{1:42,}"); // a singleton dictionary
assertThat(dictionaryList.getEntries()).hasSize(1);
DictionaryEntryLiteral tuple = getElem(dictionaryList, 0);
- assertEquals(1, getIntElem(tuple, true));
- assertEquals(42, getIntElem(tuple, false));
+ assertThat(getIntElem(tuple, true)).isEqualTo(1);
+ assertThat(getIntElem(tuple, false)).isEqualTo(42);
}
@Test
@@ -655,8 +653,8 @@ public class ParserTest extends EvaluationTestCase {
assertThat(dictionaryList.getEntries()).hasSize(3);
for (int i = 0; i < 3; i++) {
DictionaryEntryLiteral tuple = getElem(dictionaryList, i);
- assertEquals(i + 1, getIntElem(tuple, true));
- assertEquals(i + 42, getIntElem(tuple, false));
+ assertThat(getIntElem(tuple, true)).isEqualTo(i + 1);
+ assertThat(getIntElem(tuple, false)).isEqualTo(i + 42);
}
}
@@ -664,7 +662,7 @@ public class ParserTest extends EvaluationTestCase {
public void testListLiterals9() throws Exception {
ListLiteral singletonList =
(ListLiteral) parseExpression("[ abi + opt_level + \'/include\' ]");
- assertFalse(singletonList.isTuple());
+ assertThat(singletonList.isTuple()).isFalse();
assertThat(singletonList.getElements()).hasSize(1);
}
@@ -858,10 +856,12 @@ public class ParserTest extends EvaluationTestCase {
StringBuilder commentLines = new StringBuilder();
for (Comment comment : result.getComments()) {
// Comments start and end on the same line
- assertEquals(comment.getLocation().getStartLineAndColumn().getLine() + " ends on "
- + comment.getLocation().getEndLineAndColumn().getLine(),
- comment.getLocation().getStartLineAndColumn().getLine(),
- comment.getLocation().getEndLineAndColumn().getLine());
+ assertWithMessage(
+ comment.getLocation().getStartLineAndColumn().getLine()
+ + " ends on "
+ + comment.getLocation().getEndLineAndColumn().getLine())
+ .that(comment.getLocation().getEndLineAndColumn().getLine())
+ .isEqualTo(comment.getLocation().getStartLineAndColumn().getLine());
commentLines.append('(');
commentLines.append(comment.getLocation().getStartLineAndColumn().getLine());
commentLines.append(',');
@@ -965,7 +965,7 @@ public class ParserTest extends EvaluationTestCase {
assertThat(bodyNone).hasSize(1);
ReturnStatement returnNone = (ReturnStatement) bodyNone.get(0);
- assertEquals("None", ((Identifier) returnNone.getReturnExpression()).getName());
+ assertThat(((Identifier) returnNone.getReturnExpression()).getName()).isEqualTo("None");
int i = 0;
for (String end : new String[]{";", "\n"}) {
@@ -978,7 +978,7 @@ public class ParserTest extends EvaluationTestCase {
ReturnStatement returnNoExpr = (ReturnStatement) bodyNoExpr.get(0);
Identifier none = (Identifier) returnNoExpr.getReturnExpression();
- assertEquals("None", none.getName());
+ assertThat(none.getName()).isEqualTo("None");
assertLocation(
returnNoExpr.getLocation().getStartOffset(),
returnNoExpr.getLocation().getEndOffset(),
@@ -1172,7 +1172,7 @@ public class ParserTest extends EvaluationTestCase {
List<Statement> statements = parseFileForSkylark(
"load('/foo/bar/file', 'fun_test')\n");
LoadStatement stmt = (LoadStatement) statements.get(0);
- assertEquals("/foo/bar/file", stmt.getImport().getValue());
+ assertThat(stmt.getImport().getValue()).isEqualTo("/foo/bar/file");
assertThat(stmt.getSymbols()).hasSize(1);
Identifier sym = stmt.getSymbols().get(0);
int startOffset = sym.getLocation().getStartOffset();
@@ -1186,7 +1186,7 @@ public class ParserTest extends EvaluationTestCase {
List<Statement> statements = parseFileForSkylark(
"load('/foo/bar/file', 'fun_test',)\n");
LoadStatement stmt = (LoadStatement) statements.get(0);
- assertEquals("/foo/bar/file", stmt.getImport().getValue());
+ assertThat(stmt.getImport().getValue()).isEqualTo("/foo/bar/file");
assertThat(stmt.getSymbols()).hasSize(1);
}
@@ -1195,7 +1195,7 @@ public class ParserTest extends EvaluationTestCase {
List<Statement> statements = parseFileForSkylark(
"load('file', 'foo', 'bar')\n");
LoadStatement stmt = (LoadStatement) statements.get(0);
- assertEquals("file", stmt.getImport().getValue());
+ assertThat(stmt.getImport().getValue()).isEqualTo("file");
assertThat(stmt.getSymbols()).hasSize(2);
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/PrinterTest.java b/src/test/java/com/google/devtools/build/lib/syntax/PrinterTest.java
index d2a427c168..0a7f8410a8 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/PrinterTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/PrinterTest.java
@@ -15,7 +15,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
@@ -24,17 +23,15 @@ import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.syntax.SkylarkList.MutableList;
import com.google.devtools.build.lib.syntax.SkylarkList.Tuple;
-
-import java.util.LinkedHashMap;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.Arrays;
import java.util.IllegalFormatException;
+import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Test properties of the evaluator's datatypes and utility functions
@@ -47,41 +44,37 @@ public class PrinterTest {
public void testPrinter() throws Exception {
// Note that prettyPrintValue and printValue only differ on behaviour of
// labels and strings at toplevel.
- assertEquals("foo\nbar", Printer.str("foo\nbar"));
- assertEquals("\"foo\\nbar\"", Printer.repr("foo\nbar"));
- assertEquals("'", Printer.str("'"));
- assertEquals("\"'\"", Printer.repr("'"));
- assertEquals("\"", Printer.str("\""));
- assertEquals("\"\\\"\"", Printer.repr("\""));
- assertEquals("3", Printer.str(3));
- assertEquals("3", Printer.repr(3));
- assertEquals("None", Printer.repr(Runtime.NONE));
-
- assertEquals("//x:x", Printer.str(
- Label.parseAbsolute("//x")));
- assertEquals("\"//x:x\"", Printer.repr(
- Label.parseAbsolute("//x")));
+ assertThat(Printer.str("foo\nbar")).isEqualTo("foo\nbar");
+ assertThat(Printer.repr("foo\nbar")).isEqualTo("\"foo\\nbar\"");
+ assertThat(Printer.str("'")).isEqualTo("'");
+ assertThat(Printer.repr("'")).isEqualTo("\"'\"");
+ assertThat(Printer.str("\"")).isEqualTo("\"");
+ assertThat(Printer.repr("\"")).isEqualTo("\"\\\"\"");
+ assertThat(Printer.str(3)).isEqualTo("3");
+ assertThat(Printer.repr(3)).isEqualTo("3");
+ assertThat(Printer.repr(Runtime.NONE)).isEqualTo("None");
+
+ assertThat(Printer.str(Label.parseAbsolute("//x"))).isEqualTo("//x:x");
+ assertThat(Printer.repr(Label.parseAbsolute("//x"))).isEqualTo("\"//x:x\"");
List<?> list = MutableList.of(null, "foo", "bar");
List<?> tuple = Tuple.of("foo", "bar");
- assertEquals("(1, [\"foo\", \"bar\"], 3)",
- Printer.str(Tuple.of(1, list, 3)));
- assertEquals("(1, [\"foo\", \"bar\"], 3)",
- Printer.repr(Tuple.of(1, list, 3)));
- assertEquals("[1, (\"foo\", \"bar\"), 3]",
- Printer.str(MutableList.of(null, 1, tuple, 3)));
- assertEquals("[1, (\"foo\", \"bar\"), 3]",
- Printer.repr(MutableList.of(null, 1, tuple, 3)));
+ assertThat(Printer.str(Tuple.of(1, list, 3))).isEqualTo("(1, [\"foo\", \"bar\"], 3)");
+ assertThat(Printer.repr(Tuple.of(1, list, 3))).isEqualTo("(1, [\"foo\", \"bar\"], 3)");
+ assertThat(Printer.str(MutableList.of(null, 1, tuple, 3)))
+ .isEqualTo("[1, (\"foo\", \"bar\"), 3]");
+ assertThat(Printer.repr(MutableList.of(null, 1, tuple, 3)))
+ .isEqualTo("[1, (\"foo\", \"bar\"), 3]");
Map<Object, Object> dict = ImmutableMap.<Object, Object>of(
1, tuple,
2, list,
"foo", MutableList.of(null));
- assertEquals("{1: (\"foo\", \"bar\"), 2: [\"foo\", \"bar\"], \"foo\": []}",
- Printer.str(dict));
- assertEquals("{1: (\"foo\", \"bar\"), 2: [\"foo\", \"bar\"], \"foo\": []}",
- Printer.repr(dict));
+ assertThat(Printer.str(dict))
+ .isEqualTo("{1: (\"foo\", \"bar\"), 2: [\"foo\", \"bar\"], \"foo\": []}");
+ assertThat(Printer.repr(dict))
+ .isEqualTo("{1: (\"foo\", \"bar\"), 2: [\"foo\", \"bar\"], \"foo\": []}");
}
private void checkFormatPositionalFails(String errorMessage, String format, Object... arguments) {
@@ -105,26 +98,26 @@ public class PrinterTest {
@Test
public void testFormatPositional() throws Exception {
- assertEquals("foo 3", Printer.formatToString("%s %d", Tuple.of("foo", 3)));
- assertEquals("foo 3", Printer.format("%s %d", "foo", 3));
+ assertThat(Printer.formatToString("%s %d", Tuple.of("foo", 3))).isEqualTo("foo 3");
+ assertThat(Printer.format("%s %d", "foo", 3)).isEqualTo("foo 3");
// Note: formatToString doesn't perform scalar x -> (x) conversion;
// The %-operator is responsible for that.
assertThat(Printer.formatToString("", Tuple.of())).isEmpty();
- assertEquals("foo", Printer.format("%s", "foo"));
- assertEquals("3.14159", Printer.format("%s", 3.14159));
+ assertThat(Printer.format("%s", "foo")).isEqualTo("foo");
+ assertThat(Printer.format("%s", 3.14159)).isEqualTo("3.14159");
checkFormatPositionalFails("not all arguments converted during string formatting",
"%s", 1, 2, 3);
- assertEquals("%foo", Printer.format("%%%s", "foo"));
+ assertThat(Printer.format("%%%s", "foo")).isEqualTo("%foo");
checkFormatPositionalFails("not all arguments converted during string formatting",
"%%s", "foo");
checkFormatPositionalFails("unsupported format character \" \" at index 1 in \"% %s\"",
"% %s", "foo");
- assertEquals("[1, 2, 3]", Printer.format("%s", MutableList.of(null, 1, 2, 3)));
- assertEquals("(1, 2, 3)", Printer.format("%s", Tuple.of(1, 2, 3)));
- assertEquals("[]", Printer.format("%s", MutableList.of(null)));
- assertEquals("()", Printer.format("%s", Tuple.of()));
- assertEquals("% 1 \"2\" 3", Printer.format("%% %d %r %s", 1, "2", "3"));
+ assertThat(Printer.format("%s", MutableList.of(null, 1, 2, 3))).isEqualTo("[1, 2, 3]");
+ assertThat(Printer.format("%s", Tuple.of(1, 2, 3))).isEqualTo("(1, 2, 3)");
+ assertThat(Printer.format("%s", MutableList.of(null))).isEqualTo("[]");
+ assertThat(Printer.format("%s", Tuple.of())).isEqualTo("()");
+ assertThat(Printer.format("%% %d %r %s", 1, "2", "3")).isEqualTo("% 1 \"2\" 3");
checkFormatPositionalFails(
"invalid argument \"1\" for format pattern %d",
@@ -142,9 +135,9 @@ public class PrinterTest {
assertThat(Printer.str("test", '\'')).isEqualTo("test");
assertThat(Printer.repr("test", '\'')).isEqualTo("'test'");
- assertEquals("'\\''", Printer.repr("'", '\''));
- assertEquals("\"", Printer.str("\"", '\''));
- assertEquals("'\"'", Printer.repr("\"", '\''));
+ assertThat(Printer.repr("'", '\'')).isEqualTo("'\\''");
+ assertThat(Printer.str("\"", '\'')).isEqualTo("\"");
+ assertThat(Printer.repr("\"", '\'')).isEqualTo("'\"'");
List<?> list = MutableList.of(null, "foo", "bar");
List<?> tuple = Tuple.of("foo", "bar");
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/SkylarkEvaluationTest.java b/src/test/java/com/google/devtools/build/lib/syntax/SkylarkEvaluationTest.java
index b88d972ca0..d00c1bd50a 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/SkylarkEvaluationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/SkylarkEvaluationTest.java
@@ -14,8 +14,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
@@ -1293,11 +1291,11 @@ public class SkylarkEvaluationTest extends EvaluationTest {
@Test
public void testSkylarkTypes() {
- assertEquals(TransitiveInfoCollection.class,
- EvalUtils.getSkylarkType(FileConfiguredTarget.class));
- assertEquals(TransitiveInfoCollection.class,
- EvalUtils.getSkylarkType(RuleConfiguredTarget.class));
- assertEquals(Artifact.class, EvalUtils.getSkylarkType(SpecialArtifact.class));
+ assertThat(EvalUtils.getSkylarkType(FileConfiguredTarget.class))
+ .isEqualTo(TransitiveInfoCollection.class);
+ assertThat(EvalUtils.getSkylarkType(RuleConfiguredTarget.class))
+ .isEqualTo(TransitiveInfoCollection.class);
+ assertThat(EvalUtils.getSkylarkType(SpecialArtifact.class)).isEqualTo(Artifact.class);
}
// Override tests in EvaluationTest incompatible with Skylark
@@ -1317,11 +1315,11 @@ public class SkylarkEvaluationTest extends EvaluationTest {
// tuple
x = eval("(1,2)");
assertThat((Iterable<Object>) x).containsExactly(1, 2).inOrder();
- assertTrue(((SkylarkList) x).isTuple());
+ assertThat(((SkylarkList) x).isTuple()).isTrue();
x = eval("(1,2) + (3,4)");
assertThat((Iterable<Object>) x).containsExactly(1, 2, 3, 4).inOrder();
- assertTrue(((SkylarkList) x).isTuple());
+ assertThat(((SkylarkList) x).isTuple()).isTrue();
}
@Override
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/SkylarkListTest.java b/src/test/java/com/google/devtools/build/lib/syntax/SkylarkListTest.java
index 8a17607aa8..161b91341d 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/SkylarkListTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/SkylarkListTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
import com.google.devtools.build.lib.syntax.SkylarkList.Tuple;
import com.google.devtools.build.lib.syntax.util.EvaluationTestCase;
@@ -165,10 +164,10 @@ public class SkylarkListTest extends EvaluationTestCase {
"e1 = l[1]",
"e2 = l[2]",
"e3 = l[3]");
- assertEquals(1, lookup("e0"));
- assertEquals(2, lookup("e1"));
- assertEquals(3, lookup("e2"));
- assertEquals(4, lookup("e3"));
+ assertThat(lookup("e0")).isEqualTo(1);
+ assertThat(lookup("e1")).isEqualTo(2);
+ assertThat(lookup("e2")).isEqualTo(3);
+ assertThat(lookup("e3")).isEqualTo(4);
}
@Test
@@ -179,37 +178,37 @@ public class SkylarkListTest extends EvaluationTestCase {
"e2 = l[2]",
"e3 = l[3]",
"e4 = l[4]");
- assertEquals(1, lookup("e0"));
- assertEquals(2, lookup("e1"));
- assertEquals(3, lookup("e2"));
- assertEquals(4, lookup("e3"));
- assertEquals(5, lookup("e4"));
+ assertThat(lookup("e0")).isEqualTo(1);
+ assertThat(lookup("e1")).isEqualTo(2);
+ assertThat(lookup("e2")).isEqualTo(3);
+ assertThat(lookup("e3")).isEqualTo(4);
+ assertThat(lookup("e4")).isEqualTo(5);
}
@Test
public void testConcatListSize() throws Exception {
- assertEquals(4, eval("len([1, 2] + [3, 4])"));
+ assertThat(eval("len([1, 2] + [3, 4])")).isEqualTo(4);
}
@Test
public void testAppend() throws Exception {
eval("l = [1, 2]");
- assertEquals(eval("l.append([3, 4])"), Runtime.NONE);
- assertEquals(lookup("l"), eval("[1, 2, [3, 4]]"));
+ assertThat(Runtime.NONE).isEqualTo(eval("l.append([3, 4])"));
+ assertThat(eval("[1, 2, [3, 4]]")).isEqualTo(lookup("l"));
}
@Test
public void testExtend() throws Exception {
eval("l = [1, 2]");
- assertEquals(eval("l.extend([3, 4])"), Runtime.NONE);
- assertEquals(lookup("l"), eval("[1, 2, 3, 4]"));
+ assertThat(Runtime.NONE).isEqualTo(eval("l.extend([3, 4])"));
+ assertThat(eval("[1, 2, 3, 4]")).isEqualTo(lookup("l"));
}
@Test
public void testConcatListToString() throws Exception {
eval("l = [1, 2] + [3, 4]",
"s = str(l)");
- assertEquals("[1, 2, 3, 4]", lookup("s"));
+ assertThat(lookup("s")).isEqualTo("[1, 2, 3, 4]");
}
@Test
@@ -219,7 +218,7 @@ public class SkylarkListTest extends EvaluationTestCase {
" v = 1",
"else:",
" v = 0");
- assertEquals(1, lookup("v"));
+ assertThat(lookup("v")).isEqualTo(1);
}
@Test
@@ -229,18 +228,18 @@ public class SkylarkListTest extends EvaluationTestCase {
" v = 1",
"else:",
" v = 0");
- assertEquals(0, lookup("v"));
+ assertThat(lookup("v")).isEqualTo(0);
}
@Test
public void testListComparison() throws Exception {
- assertEquals(true, eval("(1, 'two', [3, 4]) == (1, 'two', [3, 4])"));
- assertEquals(true, eval("[1, 2, 3, 4] == [1, 2] + [3, 4]"));
- assertEquals(false, eval("[1, 2, 3, 4] == (1, 2, 3, 4)"));
- assertEquals(false, eval("[1, 2] == [1, 2, 3]"));
- assertEquals(true, eval("[] == []"));
- assertEquals(true, eval("() == ()"));
- assertEquals(false, eval("() == (1,)"));
- assertEquals(false, eval("(1) == (1,)"));
+ assertThat(eval("(1, 'two', [3, 4]) == (1, 'two', [3, 4])")).isEqualTo(true);
+ assertThat(eval("[1, 2, 3, 4] == [1, 2] + [3, 4]")).isEqualTo(true);
+ assertThat(eval("[1, 2, 3, 4] == (1, 2, 3, 4)")).isEqualTo(false);
+ assertThat(eval("[1, 2] == [1, 2, 3]")).isEqualTo(false);
+ assertThat(eval("[] == []")).isEqualTo(true);
+ assertThat(eval("() == ()")).isEqualTo(true);
+ assertThat(eval("() == (1,)")).isEqualTo(false);
+ assertThat(eval("(1) == (1,)")).isEqualTo(false);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/SkylarkNestedSetTest.java b/src/test/java/com/google/devtools/build/lib/syntax/SkylarkNestedSetTest.java
index c42905fa37..58fef456fc 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/SkylarkNestedSetTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/SkylarkNestedSetTest.java
@@ -50,7 +50,7 @@ public class SkylarkNestedSetTest extends EvaluationTestCase {
eval("s = set([1, 2, 3], order='postorder')");
Assert.fail("`set` should have failed");
} catch (EvalException e) {
- assertThat(e.getMessage()).contains("The `set` constructor for depsets is deprecated");
+ assertThat(e).hasMessageThat().contains("The `set` constructor for depsets is deprecated");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/TypeTest.java b/src/test/java/com/google/devtools/build/lib/syntax/TypeTest.java
index 8674e462a4..995683e079 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/TypeTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/TypeTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -37,7 +33,6 @@ import com.google.devtools.build.lib.testutil.MoreAsserts;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -59,7 +54,7 @@ public class TypeTest {
@Test
public void testInteger() throws Exception {
Object x = 3;
- assertEquals(x, Type.INTEGER.convert(x, null));
+ assertThat(Type.INTEGER.convert(x, null)).isEqualTo(x);
assertThat(collectLabels(Type.INTEGER, x)).isEmpty();
}
@@ -91,7 +86,7 @@ public class TypeTest {
@Test
public void testString() throws Exception {
Object s = "foo";
- assertEquals(s, Type.STRING.convert(s, null));
+ assertThat(Type.STRING.convert(s, null)).isEqualTo(s);
assertThat(collectLabels(Type.STRING, s)).isEmpty();
}
@@ -109,12 +104,12 @@ public class TypeTest {
public void testBoolean() throws Exception {
Object myTrue = true;
Object myFalse = false;
- assertEquals(Boolean.TRUE, Type.BOOLEAN.convert(1, null));
- assertEquals(Boolean.FALSE, Type.BOOLEAN.convert(0, null));
- assertTrue(Type.BOOLEAN.convert(true, null));
- assertTrue(Type.BOOLEAN.convert(myTrue, null));
- assertFalse(Type.BOOLEAN.convert(false, null));
- assertFalse(Type.BOOLEAN.convert(myFalse, null));
+ assertThat(Type.BOOLEAN.convert(1, null)).isEqualTo(Boolean.TRUE);
+ assertThat(Type.BOOLEAN.convert(0, null)).isEqualTo(Boolean.FALSE);
+ assertThat(Type.BOOLEAN.convert(true, null)).isTrue();
+ assertThat(Type.BOOLEAN.convert(myTrue, null)).isTrue();
+ assertThat(Type.BOOLEAN.convert(false, null)).isFalse();
+ assertThat(Type.BOOLEAN.convert(myFalse, null)).isFalse();
assertThat(collectLabels(Type.BOOLEAN, myTrue)).isEmpty();
}
@@ -132,26 +127,26 @@ public class TypeTest {
Type.BOOLEAN.convert(2, null);
fail();
} catch (Type.ConversionException e) {
- assertEquals("boolean is not one of [0, 1]", e.getMessage());
+ assertThat(e).hasMessageThat().isEqualTo("boolean is not one of [0, 1]");
}
try {
Type.BOOLEAN.convert(-1, null);
fail();
} catch (Type.ConversionException e) {
- assertEquals("boolean is not one of [0, 1]", e.getMessage());
+ assertThat(e).hasMessageThat().isEqualTo("boolean is not one of [0, 1]");
}
}
@Test
public void testTriState() throws Exception {
- Assert.assertEquals(TriState.YES, BuildType.TRISTATE.convert(1, null));
- assertEquals(TriState.NO, BuildType.TRISTATE.convert(0, null));
- assertEquals(TriState.AUTO, BuildType.TRISTATE.convert(-1, null));
- assertEquals(TriState.YES, BuildType.TRISTATE.convert(true, null));
- assertEquals(TriState.NO, BuildType.TRISTATE.convert(false, null));
- assertEquals(TriState.YES, BuildType.TRISTATE.convert(TriState.YES, null));
- assertEquals(TriState.NO, BuildType.TRISTATE.convert(TriState.NO, null));
- assertEquals(TriState.AUTO, BuildType.TRISTATE.convert(TriState.AUTO, null));
+ assertThat(BuildType.TRISTATE.convert(1, null)).isEqualTo(TriState.YES);
+ assertThat(BuildType.TRISTATE.convert(0, null)).isEqualTo(TriState.NO);
+ assertThat(BuildType.TRISTATE.convert(-1, null)).isEqualTo(TriState.AUTO);
+ assertThat(BuildType.TRISTATE.convert(true, null)).isEqualTo(TriState.YES);
+ assertThat(BuildType.TRISTATE.convert(false, null)).isEqualTo(TriState.NO);
+ assertThat(BuildType.TRISTATE.convert(TriState.YES, null)).isEqualTo(TriState.YES);
+ assertThat(BuildType.TRISTATE.convert(TriState.NO, null)).isEqualTo(TriState.NO);
+ assertThat(BuildType.TRISTATE.convert(TriState.AUTO, null)).isEqualTo(TriState.AUTO);
assertThat(collectLabels(BuildType.TRISTATE, TriState.YES)).isEmpty();
}
@@ -227,7 +222,7 @@ public class TypeTest {
public void testLabel() throws Exception {
Label label = Label
.parseAbsolute("//foo:bar");
- assertEquals(label, BuildType.LABEL.convert("//foo:bar", null, currentRule));
+ assertThat(BuildType.LABEL.convert("//foo:bar", null, currentRule)).isEqualTo(label);
assertThat(collectLabels(BuildType.LABEL, label)).containsExactly(label);
}
@@ -235,16 +230,16 @@ public class TypeTest {
public void testNodepLabel() throws Exception {
Label label = Label
.parseAbsolute("//foo:bar");
- assertEquals(label, BuildType.NODEP_LABEL.convert("//foo:bar", null, currentRule));
+ assertThat(BuildType.NODEP_LABEL.convert("//foo:bar", null, currentRule)).isEqualTo(label);
assertThat(collectLabels(BuildType.NODEP_LABEL, label)).containsExactly(label);
}
@Test
public void testRelativeLabel() throws Exception {
- assertEquals(Label.parseAbsolute("//quux:wiz"),
- BuildType.LABEL.convert(":wiz", null, currentRule));
- assertEquals(Label.parseAbsolute("//quux:wiz"),
- BuildType.LABEL.convert("wiz", null, currentRule));
+ assertThat(BuildType.LABEL.convert(":wiz", null, currentRule))
+ .isEqualTo(Label.parseAbsolute("//quux:wiz"));
+ assertThat(BuildType.LABEL.convert("wiz", null, currentRule))
+ .isEqualTo(Label.parseAbsolute("//quux:wiz"));
try {
BuildType.LABEL.convert("wiz", null);
fail();
@@ -278,8 +273,8 @@ public class TypeTest {
Object input = Arrays.asList("foo", "bar", "wiz");
List<String> converted =
Type.STRING_LIST.convert(input, null);
- assertEquals(input, converted);
- assertNotSame(input, converted);
+ assertThat(converted).isEqualTo(input);
+ assertThat(converted).isNotSameAs(input);
assertThat(collectLabels(Type.STRING_LIST, input)).isEmpty();
}
@@ -288,8 +283,8 @@ public class TypeTest {
Object input = ImmutableMap.of("foo", "bar",
"wiz", "bang");
Map<String, String> converted = Type.STRING_DICT.convert(input, null);
- assertEquals(input, converted);
- assertNotSame(input, converted);
+ assertThat(converted).isEqualTo(input);
+ assertThat(converted).isNotSameAs(input);
assertThat(collectLabels(Type.STRING_DICT, converted)).isEmpty();
}
@@ -343,8 +338,8 @@ public class TypeTest {
List<Label> expected =
Arrays.asList(Label.parseAbsolute("//foo:bar"),
Label.parseAbsolute("//quux:wiz"));
- assertEquals(expected, converted);
- assertNotSame(expected, converted);
+ assertThat(converted).isEqualTo(expected);
+ assertThat(converted).isNotSameAs(expected);
assertThat(collectLabels(BuildType.LABEL_LIST, converted)).containsExactlyElementsIn(expected);
}
@@ -392,8 +387,8 @@ public class TypeTest {
Map<?, ?> expected = ImmutableMap.<String, List<String>>of(
"foo", Arrays.asList("foo", "bar"),
"wiz", Arrays.asList("bang"));
- assertEquals(expected, converted);
- assertNotSame(expected, converted);
+ assertThat(converted).isEqualTo(expected);
+ assertThat(converted).isNotSameAs(expected);
assertThat(collectLabels(Type.STRING_LIST_DICT, converted)).isEmpty();
}
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/ValidationTest.java b/src/test/java/com/google/devtools/build/lib/syntax/ValidationTest.java
index 9b17d4b9e4..0ad0297888 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/ValidationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/ValidationTest.java
@@ -292,9 +292,11 @@ public class ValidationTest extends EvaluationTestCase {
EvalUtils.getSkylarkType(ClassObject.class);
throw new Exception("Should have raised IllegalArgumentException exception");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(
- "interface com.google.devtools.build.lib.syntax.ClassObject is not allowed "
- + "as a Skylark value");
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "interface com.google.devtools.build.lib.syntax.ClassObject is not allowed "
+ + "as a Skylark value");
}
}
@@ -313,9 +315,11 @@ public class ValidationTest extends EvaluationTestCase {
SkylarkType.of(ClassObject.class);
throw new Exception("foo");
} catch (Exception e) {
- assertThat(e.getMessage()).contains(
- "interface com.google.devtools.build.lib.syntax.ClassObject "
- + "is not allowed as a Skylark value");
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "interface com.google.devtools.build.lib.syntax.ClassObject "
+ + "is not allowed as a Skylark value");
}
// Also test for these bazel classes, to avoid some regression.
diff --git a/src/test/java/com/google/devtools/build/lib/syntax/util/EvaluationTestCase.java b/src/test/java/com/google/devtools/build/lib/syntax/util/EvaluationTestCase.java
index 33ce2d8d09..9011cc9d76 100644
--- a/src/test/java/com/google/devtools/build/lib/syntax/util/EvaluationTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/syntax/util/EvaluationTestCase.java
@@ -184,7 +184,7 @@ public class EvaluationTestCase {
eval(input);
fail("Expected error containing '" + msg + "' but got no error");
} catch (IllegalArgumentException | EvalException e) {
- assertThat(e.getMessage()).contains(msg);
+ assertThat(e).hasMessageThat().contains(msg);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/testutil/MoreAsserts.java b/src/test/java/com/google/devtools/build/lib/testutil/MoreAsserts.java
index 5a1f89e6d3..576c2f38ae 100644
--- a/src/test/java/com/google/devtools/build/lib/testutil/MoreAsserts.java
+++ b/src/test/java/com/google/devtools/build/lib/testutil/MoreAsserts.java
@@ -16,7 +16,6 @@ package com.google.devtools.build.lib.testutil;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth.assert_;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
@@ -185,8 +184,9 @@ public class MoreAsserts {
public static void assertContainsWordsWithQuotes(String message,
String... strings) {
for (String string : strings) {
- assertTrue(message + " should contain '" + string + "' (with quotes)",
- message.contains("'" + string + "'"));
+ assertWithMessage(message + " should contain '" + string + "' (with quotes)")
+ .that(message.contains("'" + string + "'"))
+ .isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java b/src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java
index 975e365361..372ede2284 100644
--- a/src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java
@@ -18,16 +18,13 @@ import static com.google.devtools.build.lib.testutil.MoreAsserts.assertContainsS
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertDoesNotContainSublist;
import static org.junit.Assert.fail;
+import java.util.Arrays;
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Tests {@link com.google.devtools.build.lib.testutil.MoreAsserts}.
- */
+/** Tests {@link com.google.devtools.build.lib.testutil.MoreAsserts}. */
@RunWith(JUnit4.class)
public class MoreAssertsTest {
@@ -56,21 +53,21 @@ public class MoreAssertsTest {
assertContainsSublist(actual, "d");
fail("no exception thrown");
} catch (AssertionError e) {
- assertThat(e.getMessage()).startsWith("Did not find [d] as a sublist of [a, b, c]");
+ assertThat(e).hasMessageThat().startsWith("Did not find [d] as a sublist of [a, b, c]");
}
try {
assertContainsSublist(actual, "a", "c");
fail("no exception thrown");
} catch (AssertionError e) {
- assertThat(e.getMessage()).startsWith("Did not find [a, c] as a sublist of [a, b, c]");
+ assertThat(e).hasMessageThat().startsWith("Did not find [a, c] as a sublist of [a, b, c]");
}
try {
assertContainsSublist(actual, "b", "c", "d");
fail("no exception thrown");
} catch (AssertionError e) {
- assertThat(e.getMessage()).startsWith("Did not find [b, c, d] as a sublist of [a, b, c]");
+ assertThat(e).hasMessageThat().startsWith("Did not find [b, c, d] as a sublist of [a, b, c]");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/testutil/TestSizeAnnotationTest.java b/src/test/java/com/google/devtools/build/lib/testutil/TestSizeAnnotationTest.java
index 810cfa1cf7..4e02fa7ee3 100644
--- a/src/test/java/com/google/devtools/build/lib/testutil/TestSizeAnnotationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/testutil/TestSizeAnnotationTest.java
@@ -13,10 +13,8 @@
// limitations under the License.
package com.google.devtools.build.lib.testutil;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.Suite.getSize;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -81,58 +79,58 @@ public class TestSizeAnnotationTest {
@Test
public void testHasNoTestSpecAnnotationIsSmall() {
- assertEquals(Suite.SMALL_TESTS, getSize(HasNoTestSpecAnnotation.class));
+ assertThat(getSize(HasNoTestSpecAnnotation.class)).isEqualTo(Suite.SMALL_TESTS);
}
@Test
public void testHasNoSizeAnnotationElementIsSmall() {
- assertEquals(Suite.SMALL_TESTS, getSize(HasNoSizeAnnotationElement.class));
+ assertThat(getSize(HasNoSizeAnnotationElement.class)).isEqualTo(Suite.SMALL_TESTS);
}
@Test
public void testIsAnnotatedWithSmallSizeIsSmall() {
- assertEquals(Suite.SMALL_TESTS, getSize(IsAnnotatedWithSmallSize.class));
+ assertThat(getSize(IsAnnotatedWithSmallSize.class)).isEqualTo(Suite.SMALL_TESTS);
}
@Test
public void testIsAnnotatedWithMediumSizeIsMedium() {
- assertEquals(Suite.MEDIUM_TESTS, getSize(IsAnnotatedWithMediumSize.class));
+ assertThat(getSize(IsAnnotatedWithMediumSize.class)).isEqualTo(Suite.MEDIUM_TESTS);
}
@Test
public void testIsAnnotatedWithLargeSizeIsLarge() {
- assertEquals(Suite.LARGE_TESTS, getSize(IsAnnotatedWithLargeSize.class));
+ assertThat(getSize(IsAnnotatedWithLargeSize.class)).isEqualTo(Suite.LARGE_TESTS);
}
@Test
public void testSuperclassHasAnnotationButNoSizeElement() {
- assertEquals(Suite.SMALL_TESTS, getSize(SuperclassHasAnnotationButNoSizeElement.class));
+ assertThat(getSize(SuperclassHasAnnotationButNoSizeElement.class)).isEqualTo(Suite.SMALL_TESTS);
}
@Test
public void testHasSizeElementAndSuperclassHasAnnotationButNoSizeElement() {
- assertEquals(Suite.LARGE_TESTS,
- getSize(HasSizeElementAndSuperclassHasAnnotationButNoSizeElement.class));
+ assertThat(getSize(HasSizeElementAndSuperclassHasAnnotationButNoSizeElement.class))
+ .isEqualTo(Suite.LARGE_TESTS);
}
@Test
public void testSuperclassHasAnnotationWithSizeElement() {
- assertEquals(Suite.SMALL_TESTS, getSize(SuperclassHasAnnotationWithSizeElement.class));
+ assertThat(getSize(SuperclassHasAnnotationWithSizeElement.class)).isEqualTo(Suite.SMALL_TESTS);
}
@Test
public void testHasSizeElementAndSuperclassHasAnnotationWithSizeElement() {
- assertEquals(Suite.LARGE_TESTS,
- getSize(HasSizeElementAndSuperclassHasAnnotationWithSizeElement.class));
+ assertThat(getSize(HasSizeElementAndSuperclassHasAnnotationWithSizeElement.class))
+ .isEqualTo(Suite.LARGE_TESTS);
}
@Test
public void testIsNotFlaky() {
- assertFalse(Suite.isFlaky(HasNoTestSpecAnnotation.class));
+ assertThat(Suite.isFlaky(HasNoTestSpecAnnotation.class)).isFalse();
}
@Test
public void testIsFlaky() {
- assertTrue(Suite.isFlaky(FlakyTestSpecAnnotation.class));
+ assertThat(Suite.isFlaky(FlakyTestSpecAnnotation.class)).isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/unix/ProcMeminfoParserTest.java b/src/test/java/com/google/devtools/build/lib/unix/ProcMeminfoParserTest.java
index 493a260387..ad6ffae331 100644
--- a/src/test/java/com/google/devtools/build/lib/unix/ProcMeminfoParserTest.java
+++ b/src/test/java/com/google/devtools/build/lib/unix/ProcMeminfoParserTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.unix;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.util.StringUtilities;
@@ -72,9 +72,9 @@ public class ProcMeminfoParserTest {
String meminfoFile = scratch.file("test_meminfo", meminfoContent).getPathString();
ProcMeminfoParser memInfo = new ProcMeminfoParser(meminfoFile);
- assertEquals(2356756, memInfo.getFreeRamKb());
- assertEquals(509940, memInfo.getRamKb("Cached"));
- assertEquals(3091732, memInfo.getTotalKb());
+ assertThat(memInfo.getFreeRamKb()).isEqualTo(2356756);
+ assertThat(memInfo.getRamKb("Cached")).isEqualTo(509940);
+ assertThat(memInfo.getTotalKb()).isEqualTo(3091732);
assertNotAvailable("Bogus", memInfo);
assertNotAvailable("Bogus2", memInfo);
}
diff --git a/src/test/java/com/google/devtools/build/lib/unix/UnixFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/unix/UnixFileSystemTest.java
index 567b2f3d0e..ac2e13c2ea 100644
--- a/src/test/java/com/google/devtools/build/lib/unix/UnixFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/unix/UnixFileSystemTest.java
@@ -13,9 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.unix;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.vfs.FileSystem;
@@ -44,7 +42,7 @@ public class UnixFileSystemTest extends SymlinkAwareFileSystemTest {
@Override
protected void expectNotFound(Path path) throws IOException {
- assertNull(path.statIfFound());
+ assertThat(path.statIfFound()).isNull();
}
// Most tests are just inherited from FileSystemTest.
@@ -55,7 +53,7 @@ public class UnixFileSystemTest extends SymlinkAwareFileSystemTest {
Path linkB = absolutize("link-b");
linkA.createSymbolicLink(linkB);
linkB.createSymbolicLink(linkA);
- assertFalse(linkA.exists(Symlinks.FOLLOW));
+ assertThat(linkA.exists(Symlinks.FOLLOW)).isFalse();
try {
linkA.statIfFound(Symlinks.FOLLOW);
fail();
@@ -70,13 +68,13 @@ public class UnixFileSystemTest extends SymlinkAwareFileSystemTest {
Path fifo = absolutize("fifo");
FileSystemUtils.createEmptyFile(regular);
NativePosixFiles.mkfifo(fifo.toString(), 0777);
- assertTrue(regular.isFile());
- assertFalse(regular.isSpecialFile());
- assertTrue(regular.stat().isFile());
- assertFalse(regular.stat().isSpecialFile());
- assertTrue(fifo.isFile());
- assertTrue(fifo.isSpecialFile());
- assertTrue(fifo.stat().isFile());
- assertTrue(fifo.stat().isSpecialFile());
+ assertThat(regular.isFile()).isTrue();
+ assertThat(regular.isSpecialFile()).isFalse();
+ assertThat(regular.stat().isFile()).isTrue();
+ assertThat(regular.stat().isSpecialFile()).isFalse();
+ assertThat(fifo.isFile()).isTrue();
+ assertThat(fifo.isSpecialFile()).isTrue();
+ assertThat(fifo.stat().isFile()).isTrue();
+ assertThat(fifo.stat().isSpecialFile()).isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/unix/UnixPathEqualityTest.java b/src/test/java/com/google/devtools/build/lib/unix/UnixPathEqualityTest.java
index bf8091a32d..d77b10fd86 100644
--- a/src/test/java/com/google/devtools/build/lib/unix/UnixPathEqualityTest.java
+++ b/src/test/java/com/google/devtools/build/lib/unix/UnixPathEqualityTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.unix;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.testing.EqualsTester;
@@ -41,17 +38,17 @@ public class UnixPathEqualityTest {
public final void initializeFileSystem() throws Exception {
unixFs = new UnixFileSystem();
otherUnixFs = new UnixFileSystem();
- assertTrue(unixFs != otherUnixFs);
+ assertThat(unixFs != otherUnixFs).isTrue();
}
private void assertTwoWayEquals(Object obj1, Object obj2) {
- assertEquals(obj2, obj1);
+ assertThat(obj1).isEqualTo(obj2);
new EqualsTester().addEqualityGroup(obj1, obj2).testEquals();
}
private void assertTwoWayNotEquals(Object obj1, Object obj2) {
- assertFalse(obj1.equals(obj2));
- assertFalse(obj2.equals(obj1));
+ assertThat(obj1.equals(obj2)).isFalse();
+ assertThat(obj2.equals(obj1)).isFalse();
}
@Test
@@ -88,7 +85,7 @@ public class UnixPathEqualityTest {
@Test
public void testCrossFilesystemStartsWithReturnsFalse() {
- assertFalse(unixFs.getPath("/a").startsWith(otherUnixFs.getPath("/b")));
+ assertThat(unixFs.getPath("/a").startsWith(otherUnixFs.getPath("/b"))).isFalse();
}
@Test
@@ -100,21 +97,21 @@ public class UnixPathEqualityTest {
a.renameTo(b);
fail();
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains("different filesystems");
+ assertThat(e).hasMessageThat().contains("different filesystems");
}
try {
a.relativeTo(b);
fail();
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains("different filesystems");
+ assertThat(e).hasMessageThat().contains("different filesystems");
}
try {
a.createSymbolicLink(b);
fail();
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains("different filesystems");
+ assertThat(e).hasMessageThat().contains("different filesystems");
}
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/CommandBuilderTest.java b/src/test/java/com/google/devtools/build/lib/util/CommandBuilderTest.java
index a9e6f15380..5e8c001d29 100644
--- a/src/test/java/com/google/devtools/build/lib/util/CommandBuilderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/CommandBuilderTest.java
@@ -17,13 +17,11 @@ import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
-
+import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Arrays;
-
/**
* Tests for the {@link CommandBuilder} class.
*/
@@ -39,8 +37,10 @@ public class CommandBuilderTest {
}
private void assertArgv(CommandBuilder builder, String... expected) {
- assertThat(Arrays.asList(builder.build().getCommandLineElements())).containsExactlyElementsIn(
- Arrays.asList(expected)).inOrder();
+ assertThat(builder.build().getCommandLineElements())
+ .asList()
+ .containsExactlyElementsIn(Arrays.asList(expected))
+ .inOrder();
}
private void assertWinCmdArgv(CommandBuilder builder, String expected) {
diff --git a/src/test/java/com/google/devtools/build/lib/util/DependencySetTest.java b/src/test/java/com/google/devtools/build/lib/util/DependencySetTest.java
index ad0590186f..d8e2b274d8 100644
--- a/src/test/java/com/google/devtools/build/lib/util/DependencySetTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/DependencySetTest.java
@@ -23,14 +23,12 @@ import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collection;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class DependencySetTest {
@@ -187,7 +185,7 @@ public class DependencySetTest {
newDependencySet().read(dotd);
fail();
} catch (IOException e) {
- assertThat(e.getMessage()).contains("File does not end in a newline");
+ assertThat(e).hasMessageThat().contains("File does not end in a newline");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/FileTypeTest.java b/src/test/java/com/google/devtools/build/lib/util/FileTypeTest.java
index 67bdfe2804..bb13d18bef 100644
--- a/src/test/java/com/google/devtools/build/lib/util/FileTypeTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/FileTypeTest.java
@@ -15,8 +15,6 @@ package com.google.devtools.build.lib.util;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
@@ -26,16 +24,12 @@ import com.google.devtools.build.lib.util.FileType.HasFilename;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
-
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.List;
-
-/**
- * Test for {@link FileType} and {@link FileTypeSet}.
- */
+/** Test for {@link FileType} and {@link FileTypeSet}. */
@RunWith(JUnit4.class)
public class FileTypeTest {
private static final FileType CFG = FileType.of(".cfg");
@@ -65,48 +59,48 @@ public class FileTypeTest {
@Test
public void simpleDotMatch() {
- assertTrue(TEXT.matches("readme.txt"));
+ assertThat(TEXT.matches("readme.txt")).isTrue();
}
@Test
public void doubleDotMatches() {
- assertTrue(TEXT.matches("read.me.txt"));
+ assertThat(TEXT.matches("read.me.txt")).isTrue();
}
@Test
public void noExtensionMatches() {
- assertTrue(FileType.NO_EXTENSION.matches("hello"));
- assertTrue(FileType.NO_EXTENSION.matches("/path/to/hello"));
+ assertThat(FileType.NO_EXTENSION.matches("hello")).isTrue();
+ assertThat(FileType.NO_EXTENSION.matches("/path/to/hello")).isTrue();
}
@Test
public void picksLastExtension() {
- assertTrue(TEXT.matches("server.cfg.txt"));
+ assertThat(TEXT.matches("server.cfg.txt")).isTrue();
}
@Test
public void onlyExtensionStillMatches() {
- assertTrue(TEXT.matches(".txt"));
+ assertThat(TEXT.matches(".txt")).isTrue();
}
@Test
public void handlesPathObjects() {
Path readme = new InMemoryFileSystem().getPath("/readme.txt");
- assertTrue(TEXT.matches(readme));
+ assertThat(TEXT.matches(readme)).isTrue();
}
@Test
public void handlesPathFragmentObjects() {
PathFragment readme = PathFragment.create("some/where/readme.txt");
- assertTrue(TEXT.matches(readme));
+ assertThat(TEXT.matches(readme)).isTrue();
}
@Test
public void fileTypeSetContains() {
FileTypeSet allowedTypes = FileTypeSet.of(TEXT, HTML);
- assertTrue(allowedTypes.matches("readme.txt"));
- assertFalse(allowedTypes.matches("style.css"));
+ assertThat(allowedTypes.matches("readme.txt")).isTrue();
+ assertThat(allowedTypes.matches("style.css")).isFalse();
}
private List<HasFilename> getArtifacts() {
@@ -148,8 +142,8 @@ public class FileTypeTest {
public void checkingSingleWithTypePredicate() throws Exception {
FileType.HasFilename item = filename("config.txt");
- assertTrue(FileType.contains(item, TEXT));
- assertFalse(FileType.contains(item, CFG));
+ assertThat(FileType.contains(item, TEXT)).isTrue();
+ assertThat(FileType.contains(item, CFG)).isFalse();
}
@Test
@@ -159,8 +153,8 @@ public class FileTypeTest {
filename("index.html"),
filename("README.txt"));
- assertTrue(FileType.contains(unfiltered, TEXT));
- assertFalse(FileType.contains(unfiltered, CFG));
+ assertThat(FileType.contains(unfiltered, TEXT)).isTrue();
+ assertThat(FileType.contains(unfiltered, CFG)).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/util/GroupedListTest.java b/src/test/java/com/google/devtools/build/lib/util/GroupedListTest.java
index 8ac5230dac..a260cc7e8b 100644
--- a/src/test/java/com/google/devtools/build/lib/util/GroupedListTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/GroupedListTest.java
@@ -14,9 +14,7 @@
package com.google.devtools.build.lib.util;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@@ -60,7 +58,7 @@ public class GroupedListTest {
list.add("test" + i);
}
Object compressedList = createAndCompress(list);
- assertTrue(Iterables.elementsEqual(iterable(compressedList), list));
+ assertThat(Iterables.elementsEqual(iterable(compressedList), list)).isTrue();
assertElementsEqual(compressedList, list);
}
@@ -70,7 +68,7 @@ public class GroupedListTest {
Object compressedList = createAndCompress(list);
ArrayList<String> reversed = new ArrayList<>(list);
Collections.reverse(reversed);
- assertFalse(elementsEqual(compressedList, reversed));
+ assertThat(elementsEqual(compressedList, reversed)).isFalse();
}
@Test
@@ -86,8 +84,10 @@ public class GroupedListTest {
for (int i = 0; i < size2; i++) {
secondList.add("test" + i);
}
- assertEquals(GroupedList.create(array) + ", " + secondList + ", " + size1 + ", " + size2,
- size1 == size2, elementsEqual(array, secondList));
+ assertWithMessage(
+ GroupedList.create(array) + ", " + secondList + ", " + size1 + ", " + size2)
+ .that(elementsEqual(array, secondList))
+ .isEqualTo(size1 == size2);
}
}
}
@@ -122,7 +122,7 @@ public class GroupedListTest {
@Test
public void group() {
GroupedList<String> groupedList = new GroupedList<>();
- assertTrue(groupedList.isEmpty());
+ assertThat(groupedList.isEmpty()).isTrue();
GroupedListHelper<String> helper = new GroupedListHelper<>();
List<ImmutableList<String>> elements = ImmutableList.of(
ImmutableList.of("1"),
@@ -146,8 +146,8 @@ public class GroupedListTest {
allElts.addAll(group);
}
groupedList.append(helper);
- assertEquals(allElts.size(), groupedList.numElements());
- assertFalse(groupedList.isEmpty());
+ assertThat(groupedList.numElements()).isEqualTo(allElts.size());
+ assertThat(groupedList.isEmpty()).isFalse();
Object compressed = groupedList.compress();
assertElementsEqual(compressed, allElts);
assertElementsEqualInGroups(GroupedList.<String>create(compressed), elements);
@@ -157,7 +157,7 @@ public class GroupedListTest {
@Test
public void singletonAndEmptyGroups() {
GroupedList<String> groupedList = new GroupedList<>();
- assertTrue(groupedList.isEmpty());
+ assertThat(groupedList.isEmpty()).isTrue();
GroupedListHelper<String> helper = new GroupedListHelper<>();
@SuppressWarnings("unchecked") // varargs
List<ImmutableList<String>> elements = Lists.newArrayList(
@@ -176,8 +176,8 @@ public class GroupedListTest {
allElts.addAll(group);
}
groupedList.append(helper);
- assertEquals(allElts.size(), groupedList.numElements());
- assertFalse(groupedList.isEmpty());
+ assertThat(groupedList.numElements()).isEqualTo(allElts.size());
+ assertThat(groupedList.isEmpty()).isFalse();
Object compressed = groupedList.compress();
assertElementsEqual(compressed, allElts);
// Get rid of empty list -- it was not stored in groupedList.
@@ -205,7 +205,7 @@ public class GroupedListTest {
@Test
public void removeMakesEmpty() {
GroupedList<String> groupedList = new GroupedList<>();
- assertTrue(groupedList.isEmpty());
+ assertThat(groupedList.isEmpty()).isTrue();
GroupedListHelper<String> helper = new GroupedListHelper<>();
@SuppressWarnings("unchecked") // varargs
List<List<String>> elements = Lists.newArrayList(
@@ -242,7 +242,7 @@ public class GroupedListTest {
@Test
public void removeGroupFromSmallList() {
GroupedList<String> groupedList = new GroupedList<>();
- assertTrue(groupedList.isEmpty());
+ assertThat(groupedList.isEmpty()).isTrue();
GroupedListHelper<String> helper = new GroupedListHelper<>();
List<List<String>> elements = new ArrayList<>();
List<String> group = Lists.newArrayList("1a", "1b", "1c", "1d");
diff --git a/src/test/java/com/google/devtools/build/lib/util/LongArrayListTest.java b/src/test/java/com/google/devtools/build/lib/util/LongArrayListTest.java
index c0a3bb4006..14befff84d 100644
--- a/src/test/java/com/google/devtools/build/lib/util/LongArrayListTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/LongArrayListTest.java
@@ -13,9 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import org.junit.Before;
import org.junit.Test;
@@ -41,64 +39,64 @@ public class LongArrayListTest {
list.add(i);
}
for (int i = 0; i < 50; i++) {
- assertEquals(list.get(i), i);
+ assertThat(i).isEqualTo(list.get(i));
}
list.add(25, 42);
- assertEquals(42, list.get(25));
- assertEquals(25, list.get(26));
- assertEquals(49, list.get(list.size() - 1));
- assertEquals(51, list.size());
- assertEquals(23, list.indexOf(23));
- assertEquals(29, list.indexOf(28));
+ assertThat(list.get(25)).isEqualTo(42);
+ assertThat(list.get(26)).isEqualTo(25);
+ assertThat(list.get(list.size() - 1)).isEqualTo(49);
+ assertThat(list.size()).isEqualTo(51);
+ assertThat(list.indexOf(23)).isEqualTo(23);
+ assertThat(list.indexOf(28)).isEqualTo(29);
}
@Test
public void testAddAlls() throws Exception {
list.addAll(new long[] {1, 2, 3, 4, 5}, 1, 3);
- assertEquals(2, list.get(0));
- assertEquals(3, list.get(1));
- assertEquals(4, list.get(2));
- assertEquals(3, list.size());
+ assertThat(list.get(0)).isEqualTo(2);
+ assertThat(list.get(1)).isEqualTo(3);
+ assertThat(list.get(2)).isEqualTo(4);
+ assertThat(list.size()).isEqualTo(3);
list.addAll(new long[] {42, 41}, 0, 2, 1);
- assertEquals(42, list.get(1));
- assertEquals(41, list.get(2));
- assertEquals(3, list.get(3));
- assertEquals(4, list.get(4));
- assertEquals(5, list.size());
+ assertThat(list.get(1)).isEqualTo(42);
+ assertThat(list.get(2)).isEqualTo(41);
+ assertThat(list.get(3)).isEqualTo(3);
+ assertThat(list.get(4)).isEqualTo(4);
+ assertThat(list.size()).isEqualTo(5);
LongArrayList other = new LongArrayList(new long[] {5, 6, 7});
list.addAll(other, list.size());
- assertEquals(42, list.get(1));
- assertEquals(4, list.get(4));
- assertEquals(5, list.get(5));
- assertEquals(6, list.get(6));
- assertEquals(7, list.get(7));
- assertEquals(8, list.size());
+ assertThat(list.get(1)).isEqualTo(42);
+ assertThat(list.get(4)).isEqualTo(4);
+ assertThat(list.get(5)).isEqualTo(5);
+ assertThat(list.get(6)).isEqualTo(6);
+ assertThat(list.get(7)).isEqualTo(7);
+ assertThat(list.size()).isEqualTo(8);
list.addAll(new LongArrayList());
- assertEquals(8, list.size());
+ assertThat(list.size()).isEqualTo(8);
list.addAll(new long[] {});
- assertEquals(8, list.size());
+ assertThat(list.size()).isEqualTo(8);
}
@Test
public void testSet() throws Exception {
list.addAll(new long[] {1, 2, 3});
list.set(1, 42);
- assertEquals(42, list.get(1));
- assertEquals(3, list.size());
+ assertThat(list.get(1)).isEqualTo(42);
+ assertThat(list.size()).isEqualTo(3);
}
@Test
public void testSort() throws Exception {
list = new LongArrayList(new long[] {3, 2, 1});
list.sort();
- assertEquals(1, list.get(0));
- assertEquals(2, list.get(1));
- assertEquals(3, list.get(2));
+ assertThat(list.get(0)).isEqualTo(1);
+ assertThat(list.get(1)).isEqualTo(2);
+ assertThat(list.get(2)).isEqualTo(3);
list.addAll(new long[] {-5, -2});
list.sort(2, 5);
- assertEquals(-5, list.get(2));
- assertEquals(-2, list.get(3));
- assertEquals(3, list.get(4));
+ assertThat(list.get(2)).isEqualTo(-5);
+ assertThat(list.get(3)).isEqualTo(-2);
+ assertThat(list.get(4)).isEqualTo(3);
}
@Test
@@ -108,13 +106,13 @@ public class LongArrayListTest {
list.add(i);
}
long removed = list.remove(last);
- assertEquals(last, removed);
- assertEquals(last, list.size());
+ assertThat(removed).isEqualTo(last);
+ assertThat(list.size()).isEqualTo(last);
removed = list.remove(0);
- assertEquals(0, removed);
- assertEquals(1, list.get(0));
- assertEquals(last - 1, list.get(last - 2));
- assertEquals(last - 1, list.size());
+ assertThat(removed).isEqualTo(0);
+ assertThat(list.get(0)).isEqualTo(1);
+ assertThat(list.get(last - 2)).isEqualTo(last - 1);
+ assertThat(list.size()).isEqualTo(last - 1);
}
@Test
@@ -124,17 +122,17 @@ public class LongArrayListTest {
list.add(i);
}
boolean removed = list.remove((long) last);
- assertTrue(removed);
- assertEquals(last, list.size());
- assertEquals(last - 1, list.get(last - 1));
+ assertThat(removed).isTrue();
+ assertThat(list.size()).isEqualTo(last);
+ assertThat(list.get(last - 1)).isEqualTo(last - 1);
removed = list.remove(3L);
- assertTrue(removed);
- assertEquals(0, list.get(0));
- assertEquals(last - 1, list.get(last - 2));
- assertEquals(last - 1, list.size());
+ assertThat(removed).isTrue();
+ assertThat(list.get(0)).isEqualTo(0);
+ assertThat(list.get(last - 2)).isEqualTo(last - 1);
+ assertThat(list.size()).isEqualTo(last - 1);
removed = list.remove(42L);
- assertFalse(removed);
- assertEquals(last - 1, list.size());
+ assertThat(removed).isFalse();
+ assertThat(list.size()).isEqualTo(last - 1);
}
@Test
@@ -144,9 +142,9 @@ public class LongArrayListTest {
list.add(i);
}
list.ensureCapacity(512);
- assertEquals(last + 1, list.size());
- assertEquals(0, list.get(0));
- assertEquals(last, list.get(last));
+ assertThat(list.size()).isEqualTo(last + 1);
+ assertThat(list.get(0)).isEqualTo(0);
+ assertThat(list.get(last)).isEqualTo(last);
}
@Test(expected = IndexOutOfBoundsException.class)
diff --git a/src/test/java/com/google/devtools/build/lib/util/OptionsUtilsTest.java b/src/test/java/com/google/devtools/build/lib/util/OptionsUtilsTest.java
index d1761b8f0b..f7cac8c3fa 100644
--- a/src/test/java/com/google/devtools/build/lib/util/OptionsUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/OptionsUtilsTest.java
@@ -13,12 +13,10 @@
// limitations under the License.
package com.google.devtools.build.lib.util;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.devtools.build.lib.util.OptionsUtils.PathFragmentListConverter;
import com.google.devtools.build.lib.vfs.PathFragment;
@@ -77,7 +75,9 @@ public class OptionsUtilsTest {
OptionsParser parser = OptionsParser.newOptionsParser(IntrospectionExample.class);
parser.parse("--alpha=no", "--gamma=no", "--echo=no");
assertEquals("--alpha=no --gamma=no", OptionsUtils.asShellEscapedString(parser));
- assertEquals(ImmutableList.of("--alpha=no", "--gamma=no"), OptionsUtils.asArgumentList(parser));
+ assertThat(OptionsUtils.asArgumentList(parser))
+ .containsExactly("--alpha=no", "--gamma=no")
+ .inOrder();
}
@Test
@@ -86,7 +86,9 @@ public class OptionsUtilsTest {
parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--alpha=no"));
parser.parse(OptionPriority.COMPUTED_DEFAULT, null, Arrays.asList("--beta=no"));
assertEquals("--beta=no --alpha=no", OptionsUtils.asShellEscapedString(parser));
- assertEquals(ImmutableList.of("--beta=no", "--alpha=no"), OptionsUtils.asArgumentList(parser));
+ assertThat(OptionsUtils.asArgumentList(parser))
+ .containsExactly("--beta=no", "--alpha=no")
+ .inOrder();
}
public static class BooleanOpts extends OptionsBase {
@@ -106,14 +108,18 @@ public class OptionsUtilsTest {
OptionsParser parser = OptionsParser.newOptionsParser(BooleanOpts.class);
parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--b_one", "--nob_two"));
assertEquals("--b_one --nob_two", OptionsUtils.asShellEscapedString(parser));
- assertEquals(ImmutableList.of("--b_one", "--nob_two"), OptionsUtils.asArgumentList(parser));
+ assertThat(OptionsUtils.asArgumentList(parser))
+ .containsExactly("--b_one", "--nob_two")
+ .inOrder();
parser = OptionsParser.newOptionsParser(BooleanOpts.class);
parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--b_one=true", "--b_two=0"));
- assertTrue(parser.getOptions(BooleanOpts.class).bOne);
- assertFalse(parser.getOptions(BooleanOpts.class).bTwo);
+ assertThat(parser.getOptions(BooleanOpts.class).bOne).isTrue();
+ assertThat(parser.getOptions(BooleanOpts.class).bTwo).isFalse();
assertEquals("--b_one --nob_two", OptionsUtils.asShellEscapedString(parser));
- assertEquals(ImmutableList.of("--b_one", "--nob_two"), OptionsUtils.asArgumentList(parser));
+ assertThat(OptionsUtils.asArgumentList(parser))
+ .containsExactly("--b_one", "--nob_two")
+ .inOrder();
}
@Test
@@ -122,8 +128,9 @@ public class OptionsUtilsTest {
parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--alpha=one"));
parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--alpha=two"));
assertEquals("--alpha=one --alpha=two", OptionsUtils.asShellEscapedString(parser));
- assertEquals(
- ImmutableList.of("--alpha=one", "--alpha=two"), OptionsUtils.asArgumentList(parser));
+ assertThat(OptionsUtils.asArgumentList(parser))
+ .containsExactly("--alpha=one", "--alpha=two")
+ .inOrder();
}
private static List<PathFragment> list(PathFragment... fragments) {
diff --git a/src/test/java/com/google/devtools/build/lib/util/PairTest.java b/src/test/java/com/google/devtools/build/lib/util/PairTest.java
index 98bebbc867..2dd9c80cbc 100644
--- a/src/test/java/com/google/devtools/build/lib/util/PairTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/PairTest.java
@@ -13,9 +13,8 @@
// limitations under the License.
package com.google.devtools.build.lib.util;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -32,17 +31,17 @@ public class PairTest {
Object a = new Object();
Object b = new Object();
Pair<Object, Object> p = Pair.of(a, b);
- assertSame(a, p.first);
- assertSame(b, p.second);
+ assertThat(p.first).isSameAs(a);
+ assertThat(p.second).isSameAs(b);
assertEquals(Pair.of(a, b), p);
- assertEquals(31 * a.hashCode() + b.hashCode(), p.hashCode());
+ assertThat(p.hashCode()).isEqualTo(31 * a.hashCode() + b.hashCode());
}
@Test
public void nullable() {
Pair<Object, Object> p = Pair.of(null, null);
- assertNull(p.first);
- assertNull(p.second);
+ assertThat(p.first).isNull();
+ assertThat(p.second).isNull();
p.hashCode(); // Should not throw.
assertEquals(p, p);
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/PathFragmentFilterTest.java b/src/test/java/com/google/devtools/build/lib/util/PathFragmentFilterTest.java
index 3f25414582..2d514340e4 100644
--- a/src/test/java/com/google/devtools/build/lib/util/PathFragmentFilterTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/PathFragmentFilterTest.java
@@ -13,12 +13,10 @@
// limitations under the License.
package com.google.devtools.build.lib.util;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.devtools.build.lib.vfs.PathFragment;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -35,11 +33,11 @@ public class PathFragmentFilterTest {
}
protected void assertIncluded(String path) {
- assertTrue(filter.isIncluded(PathFragment.create(path)));
+ assertThat(filter.isIncluded(PathFragment.create(path))).isTrue();
}
protected void assertExcluded(String path) {
- assertFalse(filter.isIncluded(PathFragment.create(path)));
+ assertThat(filter.isIncluded(PathFragment.create(path))).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/util/PersistentMapTest.java b/src/test/java/com/google/devtools/build/lib/util/PersistentMapTest.java
index 473f855781..8a95366dc3 100644
--- a/src/test/java/com/google/devtools/build/lib/util/PersistentMapTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/PersistentMapTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.util;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.vfs.Path;
@@ -100,7 +97,7 @@ public class PersistentMapTest {
assertThat(map).containsEntry("baz", "bang");
assertThat(map).hasSize(2);
long size = map.save();
- assertEquals(mapFile.getFileSize(), size);
+ assertThat(size).isEqualTo(mapFile.getFileSize());
assertThat(map).containsEntry("foo", "bar");
assertThat(map).containsEntry("baz", "bang");
assertThat(map).hasSize(2);
@@ -117,11 +114,11 @@ public class PersistentMapTest {
map.put("foo", "bar");
map.put("baz", "bang");
long size = map.save();
- assertEquals(mapFile.getFileSize(), size);
- assertFalse(journalFile.exists());
+ assertThat(size).isEqualTo(mapFile.getFileSize());
+ assertThat(journalFile.exists()).isFalse();
map.remove("foo");
assertThat(map).hasSize(1);
- assertTrue(journalFile.exists());
+ assertThat(journalFile.exists()).isTrue();
createMap(); // create a new map
assertThat(map).hasSize(1);
}
@@ -132,12 +129,12 @@ public class PersistentMapTest {
map.put("foo", "bar");
map.put("baz", "bang");
map.save();
- assertTrue(mapFile.exists());
- assertFalse(journalFile.exists());
+ assertThat(mapFile.exists()).isTrue();
+ assertThat(journalFile.exists()).isFalse();
map.clear();
assertThat(map).isEmpty();
- assertTrue(mapFile.exists());
- assertFalse(journalFile.exists());
+ assertThat(mapFile.exists()).isTrue();
+ assertThat(journalFile.exists()).isFalse();
createMap(); // create a new map
assertThat(map).isEmpty();
}
@@ -148,14 +145,14 @@ public class PersistentMapTest {
map.put("foo", "bar");
map.put("baz", "bang");
map.save();
- assertFalse(journalFile.exists());
+ assertThat(journalFile.exists()).isFalse();
// prevent updating the journal
map.updateJournal = false;
// remove an entry
map.remove("foo");
assertThat(map).hasSize(1);
// no journal file written
- assertFalse(journalFile.exists());
+ assertThat(journalFile.exists()).isFalse();
createMap(); // create a new map
// both entries are still in the map on disk
assertThat(map).hasSize(2);
@@ -167,7 +164,7 @@ public class PersistentMapTest {
map.put("foo", "bar");
map.put("baz", "bang");
map.save();
- assertFalse(journalFile.exists());
+ assertThat(journalFile.exists()).isFalse();
// Keep the journal through the save.
map.updateJournal = false;
@@ -177,17 +174,17 @@ public class PersistentMapTest {
map.remove("foo");
assertThat(map).hasSize(1);
// no journal file written
- assertFalse(journalFile.exists());
+ assertThat(journalFile.exists()).isFalse();
long size = map.save();
assertThat(map).hasSize(1);
// The journal must be serialzed on save(), even if !updateJournal.
- assertTrue(journalFile.exists());
- assertEquals(journalFile.getFileSize() + mapFile.getFileSize(), size);
+ assertThat(journalFile.exists()).isTrue();
+ assertThat(size).isEqualTo(journalFile.getFileSize() + mapFile.getFileSize());
map.load();
assertThat(map).hasSize(1);
- assertTrue(journalFile.exists());
+ assertThat(journalFile.exists()).isTrue();
createMap(); // create a new map
assertThat(map).hasSize(1);
@@ -195,7 +192,7 @@ public class PersistentMapTest {
map.keepJournal = false;
map.save();
assertThat(map).hasSize(1);
- assertFalse(journalFile.exists());
+ assertThat(journalFile.exists()).isFalse();
}
@Test
@@ -211,11 +208,11 @@ public class PersistentMapTest {
map.save();
map.remove("baz");
map.save();
- assertThat(map).hasSize(0);
+ assertThat(map).isEmpty();
// Ensure recreating the map loads the correct state.
createMap();
- assertThat(map).hasSize(0);
- assertFalse(journalFile.exists());
+ assertThat(map).isEmpty();
+ assertThat(journalFile.exists()).isFalse();
}
@Test
@@ -223,12 +220,12 @@ public class PersistentMapTest {
createMap();
map.put("foo", "bar");
map.save();
- assertFalse(journalFile.exists());
+ assertThat(journalFile.exists()).isFalse();
// add an entry
map.put("baz", "bang");
assertThat(map).hasSize(2);
// journal file written
- assertTrue(journalFile.exists());
+ assertThat(journalFile.exists()).isTrue();
createMap(); // create a new map
// both entries are still in the map on disk
assertThat(map).hasSize(2);
@@ -236,7 +233,7 @@ public class PersistentMapTest {
map.put("baz2", "bang2");
assertThat(map).hasSize(3);
// journal file written
- assertTrue(journalFile.exists());
+ assertThat(journalFile.exists()).isTrue();
createMap(); // create a new map
// all three entries are still in the map on disk
assertThat(map).hasSize(3);
diff --git a/src/test/java/com/google/devtools/build/lib/util/RegexFilterTest.java b/src/test/java/com/google/devtools/build/lib/util/RegexFilterTest.java
index 7f732fd019..503d065827 100644
--- a/src/test/java/com/google/devtools/build/lib/util/RegexFilterTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/RegexFilterTest.java
@@ -15,13 +15,10 @@ package com.google.devtools.build.lib.util;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.testing.EqualsTester;
import com.google.devtools.common.options.OptionsParsingException;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -39,11 +36,11 @@ public class RegexFilterTest {
}
protected void assertIncluded(String value) {
- assertTrue(filter.isIncluded(value));
+ assertThat(filter.isIncluded(value)).isTrue();
}
protected void assertExcluded(String value) {
- assertFalse(filter.isIncluded(value));
+ assertThat(filter.isIncluded(value)).isFalse();
}
@Test
@@ -120,9 +117,11 @@ public class RegexFilterTest {
createFilter("*a");
fail(); // OptionsParsingException should be thrown.
} catch (OptionsParsingException e) {
- assertThat(e.getMessage())
- .contains("Failed to build valid regular expression: Dangling meta character '*' "
- + "near index");
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "Failed to build valid regular expression: Dangling meta character '*' "
+ + "near index");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/StringCanonicalizerTest.java b/src/test/java/com/google/devtools/build/lib/util/StringCanonicalizerTest.java
index d25f2f4ddf..2874b6dd0f 100644
--- a/src/test/java/com/google/devtools/build/lib/util/StringCanonicalizerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/StringCanonicalizerTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.util;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertSame;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -37,6 +36,6 @@ public class StringCanonicalizerTest {
public void twoSameStringsAreCanonicalized() {
String stringA1 = StringCanonicalizer.intern(new String("A"));
String stringA2 = StringCanonicalizer.intern(new String("A"));
- assertSame(stringA1, stringA2);
+ assertThat(stringA2).isSameAs(stringA1);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/StringIndexerTest.java b/src/test/java/com/google/devtools/build/lib/util/StringIndexerTest.java
index 409b8f2d53..9aeb907b72 100644
--- a/src/test/java/com/google/devtools/build/lib/util/StringIndexerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/StringIndexerTest.java
@@ -15,22 +15,12 @@ package com.google.devtools.build.lib.util;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.devtools.build.lib.testutil.TestUtils;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.List;
import java.util.SortedMap;
import java.util.concurrent.ArrayBlockingQueue;
@@ -38,6 +28,10 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Test for the StringIndexer classes.
@@ -58,26 +52,26 @@ public abstract class StringIndexerTest {
protected abstract StringIndexer newIndexer();
protected void assertSize(int expected) {
- assertEquals(expected, indexer.size());
+ assertThat(indexer.size()).isEqualTo(expected);
}
protected void assertNoIndex(String s) {
int size = indexer.size();
- assertEquals(-1, indexer.getIndex(s));
- assertEquals(size, indexer.size());
+ assertThat(indexer.getIndex(s)).isEqualTo(-1);
+ assertThat(indexer.size()).isEqualTo(size);
}
protected void assertIndex(int expected, String s) {
// System.out.println("Adding " + s + ", expecting " + expected);
int index = indexer.getOrCreateIndex(s);
// System.out.println(csi);
- assertEquals(expected, index);
+ assertThat(index).isEqualTo(expected);
mappings.put(expected, s);
}
protected void assertContent() {
for (int i = 0; i < indexer.size(); i++) {
- assertNotNull(mappings.get(i));
+ assertThat(mappings.get(i)).isNotNull();
assertThat(mappings).containsEntry(i, indexer.getStringForIndex(i));
}
}
@@ -108,8 +102,8 @@ public abstract class StringIndexerTest {
int index = safeIndex.get();
// Retrieve string using random existing index and validate reverse mapping.
String key = indexer.getStringForIndex(index);
- assertNotNull(key);
- assertEquals(index, indexer.getIndex(key));
+ assertThat(key).isNotNull();
+ assertThat(indexer.getIndex(key)).isEqualTo(index);
}
}
} finally {
@@ -176,8 +170,8 @@ public abstract class StringIndexerTest {
assertContent();
indexer.clear();
assertSize(0);
- assertNull(indexer.getStringForIndex(0));
- assertNull(indexer.getStringForIndex(1000));
+ assertThat(indexer.getStringForIndex(0)).isNull();
+ assertThat(indexer.getStringForIndex(1000)).isNull();
}
@Test
@@ -241,10 +235,10 @@ public abstract class StringIndexerTest {
@Test
public void addStringResult() {
assertSize(0);
- assertTrue(indexer.addString("abcdef"));
- assertTrue(indexer.addString("abcdgh"));
- assertFalse(indexer.addString("abcd"));
- assertTrue(indexer.addString("ab"));
+ assertThat(indexer.addString("abcdef")).isTrue();
+ assertThat(indexer.addString("abcdgh")).isTrue();
+ assertThat(indexer.addString("abcd")).isFalse();
+ assertThat(indexer.addString("ab")).isTrue();
}
}
@@ -279,18 +273,18 @@ public abstract class StringIndexerTest {
assertContent();
indexer.clear();
assertSize(0);
- assertNull(indexer.getStringForIndex(0));
- assertNull(indexer.getStringForIndex(1000));
+ assertThat(indexer.getStringForIndex(0)).isNull();
+ assertThat(indexer.getStringForIndex(1000)).isNull();
}
@Test
public void addStringResult() {
assertSize(0);
- assertTrue(indexer.addString("abcdef"));
- assertTrue(indexer.addString("abcdgh"));
- assertTrue(indexer.addString("abcd"));
- assertTrue(indexer.addString("ab"));
- assertFalse(indexer.addString("ab"));
+ assertThat(indexer.addString("abcdef")).isTrue();
+ assertThat(indexer.addString("abcdgh")).isTrue();
+ assertThat(indexer.addString("abcd")).isTrue();
+ assertThat(indexer.addString("ab")).isTrue();
+ assertThat(indexer.addString("ab")).isFalse();
}
protected void setupTestContent() {
diff --git a/src/test/java/com/google/devtools/build/lib/util/StringTrieTest.java b/src/test/java/com/google/devtools/build/lib/util/StringTrieTest.java
index 8c8e03dcca..5f2faf1698 100644
--- a/src/test/java/com/google/devtools/build/lib/util/StringTrieTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/StringTrieTest.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -28,9 +27,9 @@ public class StringTrieTest {
@Test
public void empty() {
StringTrie<Integer> cut = new StringTrie<>();
- assertNull(cut.get(""));
- assertNull(cut.get("a"));
- assertNull(cut.get("ab"));
+ assertThat(cut.get("")).isNull();
+ assertThat(cut.get("a")).isNull();
+ assertThat(cut.get("ab")).isNull();
}
@Test
@@ -39,32 +38,32 @@ public class StringTrieTest {
cut.put("a", 1);
cut.put("b", 2);
- assertNull(cut.get(""));
- assertEquals(1, cut.get("a").intValue());
- assertEquals(1, cut.get("ab").intValue());
- assertEquals(1, cut.get("abc").intValue());
+ assertThat(cut.get("")).isNull();
+ assertThat(cut.get("a").intValue()).isEqualTo(1);
+ assertThat(cut.get("ab").intValue()).isEqualTo(1);
+ assertThat(cut.get("abc").intValue()).isEqualTo(1);
- assertEquals(2, cut.get("b").intValue());
+ assertThat(cut.get("b").intValue()).isEqualTo(2);
}
@Test
public void ancestors() {
StringTrie<Integer> cut = new StringTrie<>();
cut.put("abc", 3);
- assertNull(cut.get(""));
- assertNull(cut.get("a"));
- assertNull(cut.get("ab"));
- assertEquals(3, cut.get("abc").intValue());
- assertEquals(3, cut.get("abcd").intValue());
+ assertThat(cut.get("")).isNull();
+ assertThat(cut.get("a")).isNull();
+ assertThat(cut.get("ab")).isNull();
+ assertThat(cut.get("abc").intValue()).isEqualTo(3);
+ assertThat(cut.get("abcd").intValue()).isEqualTo(3);
cut.put("a", 1);
- assertEquals(1, cut.get("a").intValue());
- assertEquals(1, cut.get("ab").intValue());
- assertEquals(3, cut.get("abc").intValue());
+ assertThat(cut.get("a").intValue()).isEqualTo(1);
+ assertThat(cut.get("ab").intValue()).isEqualTo(1);
+ assertThat(cut.get("abc").intValue()).isEqualTo(3);
cut.put("", 0);
- assertEquals(0, cut.get("").intValue());
- assertEquals(0, cut.get("b").intValue());
- assertEquals(1, cut.get("a").intValue());
+ assertThat(cut.get("").intValue()).isEqualTo(0);
+ assertThat(cut.get("b").intValue()).isEqualTo(0);
+ assertThat(cut.get("a").intValue()).isEqualTo(1);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/StringUtilTest.java b/src/test/java/com/google/devtools/build/lib/util/StringUtilTest.java
index b7ec9b8c68..5331931b02 100644
--- a/src/test/java/com/google/devtools/build/lib/util/StringUtilTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/StringUtilTest.java
@@ -20,22 +20,16 @@ import static com.google.devtools.build.lib.util.StringUtil.joinEnglishList;
import static com.google.devtools.build.lib.util.StringUtil.splitAndInternString;
import static com.google.devtools.build.lib.util.StringUtil.stripSuffix;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
import com.google.common.collect.ImmutableList;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
-/**
- * A test for {@link StringUtil}.
- */
+/** A test for {@link StringUtil}. */
@RunWith(JUnit4.class)
public class StringUtilTest {
@@ -66,9 +60,9 @@ public class StringUtilTest {
assertThat(list1).containsExactly("x", "y", "z", "z").inOrder();
assertThat(list2).containsExactly("a", "z", "c", "z").inOrder();
- assertSame(list1.get(2), list1.get(3));
- assertSame(list1.get(2), list2.get(1));
- assertSame(list2.get(1), list2.get(3));
+ assertThat(list1.get(3)).isSameAs(list1.get(2));
+ assertThat(list2.get(1)).isSameAs(list1.get(2));
+ assertThat(list2.get(3)).isSameAs(list2.get(1));
}
@Test
@@ -95,10 +89,10 @@ public class StringUtilTest {
@Test
public void testStripSuffix() throws Exception {
assertThat(stripSuffix("", "")).isEmpty();
- assertNull(stripSuffix("", "a"));
+ assertThat(stripSuffix("", "a")).isNull();
assertEquals("a", stripSuffix("a", ""));
assertEquals("a", stripSuffix("aa", "a"));
- assertNull(stripSuffix("ab", "c"));
+ assertThat(stripSuffix("ab", "c")).isNull();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/util/StringUtilitiesTest.java b/src/test/java/com/google/devtools/build/lib/util/StringUtilitiesTest.java
index 4b4a554069..c6ed9bff49 100644
--- a/src/test/java/com/google/devtools/build/lib/util/StringUtilitiesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/StringUtilitiesTest.java
@@ -19,23 +19,17 @@ import static com.google.devtools.build.lib.util.StringUtilities.joinLines;
import static com.google.devtools.build.lib.util.StringUtilities.layoutTable;
import static com.google.devtools.build.lib.util.StringUtilities.prettyPrintBytes;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.Maps;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
-/**
- * A test for {@link StringUtilities}.
- */
+/** A test for {@link StringUtilities}. */
@RunWith(JUnit4.class)
public class StringUtilitiesTest {
@@ -172,17 +166,23 @@ public class StringUtilitiesTest {
@Test
public void containsSubarray() {
- assertTrue(StringUtilities.containsSubarray("abcde".toCharArray(), "ab".toCharArray()));
- assertTrue(StringUtilities.containsSubarray("abcde".toCharArray(), "de".toCharArray()));
- assertTrue(StringUtilities.containsSubarray("abcde".toCharArray(), "bc".toCharArray()));
- assertTrue(StringUtilities.containsSubarray("abcde".toCharArray(), "".toCharArray()));
+ assertThat(StringUtilities.containsSubarray("abcde".toCharArray(), "ab".toCharArray()))
+ .isTrue();
+ assertThat(StringUtilities.containsSubarray("abcde".toCharArray(), "de".toCharArray()))
+ .isTrue();
+ assertThat(StringUtilities.containsSubarray("abcde".toCharArray(), "bc".toCharArray()))
+ .isTrue();
+ assertThat(StringUtilities.containsSubarray("abcde".toCharArray(), "".toCharArray())).isTrue();
}
@Test
public void notContainsSubarray() {
- assertFalse(StringUtilities.containsSubarray("abc".toCharArray(), "abcd".toCharArray()));
- assertFalse(StringUtilities.containsSubarray("abc".toCharArray(), "def".toCharArray()));
- assertFalse(StringUtilities.containsSubarray("abcde".toCharArray(), "bd".toCharArray()));
+ assertThat(StringUtilities.containsSubarray("abc".toCharArray(), "abcd".toCharArray()))
+ .isFalse();
+ assertThat(StringUtilities.containsSubarray("abc".toCharArray(), "def".toCharArray()))
+ .isFalse();
+ assertThat(StringUtilities.containsSubarray("abcde".toCharArray(), "bd".toCharArray()))
+ .isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/util/io/AnsiTerminalPrinterTest.java b/src/test/java/com/google/devtools/build/lib/util/io/AnsiTerminalPrinterTest.java
index d6423c6fa2..886737ae81 100644
--- a/src/test/java/com/google/devtools/build/lib/util/io/AnsiTerminalPrinterTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/io/AnsiTerminalPrinterTest.java
@@ -15,7 +15,6 @@ package com.google.devtools.build.lib.util.io;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import com.google.devtools.build.lib.testutil.MoreAsserts;
import com.google.devtools.build.lib.util.io.AnsiTerminalPrinter.Mode;
@@ -82,11 +81,11 @@ public class AnsiTerminalPrinterTest {
assertThat(codes[i]).isNotEmpty();
assertEquals(codes[i], codes[i+4]);
}
- assertFalse(codes[0].equals(codes[1]));
- assertFalse(codes[0].equals(codes[2]));
- assertFalse(codes[0].equals(codes[3]));
- assertFalse(codes[1].equals(codes[2]));
- assertFalse(codes[1].equals(codes[3]));
- assertFalse(codes[2].equals(codes[3]));
+ assertThat(codes[0].equals(codes[1])).isFalse();
+ assertThat(codes[0].equals(codes[2])).isFalse();
+ assertThat(codes[0].equals(codes[3])).isFalse();
+ assertThat(codes[1].equals(codes[2])).isFalse();
+ assertThat(codes[1].equals(codes[3])).isFalse();
+ assertThat(codes[2].equals(codes[3])).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/io/OutErrTest.java b/src/test/java/com/google/devtools/build/lib/util/io/OutErrTest.java
index d3c0ace318..0afcb31dd3 100644
--- a/src/test/java/com/google/devtools/build/lib/util/io/OutErrTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/io/OutErrTest.java
@@ -13,18 +13,15 @@
// limitations under the License.
package com.google.devtools.build.lib.util.io;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
+import java.io.ByteArrayOutputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.ByteArrayOutputStream;
-
-/**
- * Tests {@link OutErr}.
- */
+/** Tests {@link OutErr}. */
@RunWith(JUnit4.class)
public class OutErrTest {
@@ -34,8 +31,8 @@ public class OutErrTest {
@Test
public void testRetainsOutErr() {
- assertSame(out, outErr.getOutputStream());
- assertSame(err, outErr.getErrorStream());
+ assertThat(outErr.getOutputStream()).isSameAs(out);
+ assertThat(outErr.getErrorStream()).isSameAs(err);
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/util/io/PositionAwareAnsiTerminalWriterTest.java b/src/test/java/com/google/devtools/build/lib/util/io/PositionAwareAnsiTerminalWriterTest.java
index ec1c809dc3..2aef6ff45e 100644
--- a/src/test/java/com/google/devtools/build/lib/util/io/PositionAwareAnsiTerminalWriterTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/io/PositionAwareAnsiTerminalWriterTest.java
@@ -13,17 +13,15 @@
// limitations under the License.
package com.google.devtools.build.lib.util.io;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
+import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.io.IOException;
-
-/**
- * Tests {@link PositionAwareAnsiTerminalWriter}.
- */
+/** Tests {@link PositionAwareAnsiTerminalWriter}. */
@RunWith(JUnit4.class)
public class PositionAwareAnsiTerminalWriterTest {
static final String NL = LoggingTerminalWriter.NEWLINE;
@@ -40,7 +38,7 @@ public class PositionAwareAnsiTerminalWriterTest {
terminalWriter.append(sample);
- assertEquals(sample.length(), terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(sample.length());
assertEquals(sample, loggingTerminalWriter.getTranscript());
}
@@ -54,13 +52,13 @@ public class PositionAwareAnsiTerminalWriterTest {
new PositionAwareAnsiTerminalWriter(loggingTerminalWriter);
terminalWriter.append(firstLine);
- assertEquals(firstLine.length(), terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(firstLine.length());
terminalWriter.newline();
- assertEquals(0, terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(0);
terminalWriter.append(secondLine);
- assertEquals(secondLine.length(), terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(secondLine.length());
terminalWriter.newline();
- assertEquals(0, terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(0);
assertEquals(firstLine + NL + secondLine + NL, loggingTerminalWriter.getTranscript());
}
@@ -74,9 +72,9 @@ public class PositionAwareAnsiTerminalWriterTest {
new PositionAwareAnsiTerminalWriter(loggingTerminalWriter);
terminalWriter.append(firstLine + "\n" + secondLine);
- assertEquals(secondLine.length(), terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(secondLine.length());
terminalWriter.append("\n");
- assertEquals(0, terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(0);
assertEquals(firstLine + NL + secondLine + NL, loggingTerminalWriter.getTranscript());
}
@@ -108,9 +106,9 @@ public class PositionAwareAnsiTerminalWriterTest {
new PositionAwareAnsiTerminalWriter(loggingTerminalWriter);
terminalWriter.failStatus();
- assertEquals(0, terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(0);
terminalWriter.append(sample);
- assertEquals(sample.length(), terminalWriter.getPosition());
+ assertThat(terminalWriter.getPosition()).isEqualTo(sample.length());
assertEquals(FAIL + sample, loggingTerminalWriter.getTranscript());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/io/RecordingOutErrTest.java b/src/test/java/com/google/devtools/build/lib/util/io/RecordingOutErrTest.java
index 54309ac29d..435ffb5433 100644
--- a/src/test/java/com/google/devtools/build/lib/util/io/RecordingOutErrTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/io/RecordingOutErrTest.java
@@ -13,9 +13,8 @@
// limitations under the License.
package com.google.devtools.build.lib.util.io;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import java.io.PrintWriter;
import org.junit.Test;
@@ -51,13 +50,13 @@ public class RecordingOutErrTest {
assertEquals("Testout1\nTestout2\n", outErr.outAsLatin1());
assertEquals("Testerr1\nTesterr2\n", outErr.errAsLatin1());
- assertTrue(outErr.hasRecordedOutput());
+ assertThat(outErr.hasRecordedOutput()).isTrue();
outErr.reset();
- assertEquals("", outErr.outAsLatin1());
- assertEquals("", outErr.errAsLatin1());
- assertFalse(outErr.hasRecordedOutput());
+ assertThat(outErr.outAsLatin1()).isEmpty();
+ assertThat(outErr.errAsLatin1()).isEmpty();
+ assertThat(outErr.hasRecordedOutput()).isFalse();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/io/StreamDemultiplexerTest.java b/src/test/java/com/google/devtools/build/lib/util/io/StreamDemultiplexerTest.java
index 786eb6c42b..ba06bb8917 100644
--- a/src/test/java/com/google/devtools/build/lib/util/io/StreamDemultiplexerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/io/StreamDemultiplexerTest.java
@@ -13,18 +13,17 @@
// limitations under the License.
package com.google.devtools.build.lib.util.io;
-import static org.junit.Assert.assertArrayEquals;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Random;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests {@link StreamDemultiplexer}.
@@ -109,9 +108,9 @@ public class StreamDemultiplexerTest {
muxOuts[streamId].write(buffer);
muxOuts[streamId].flush();
}
- assertArrayEquals(expectedOuts[0].toByteArray(), out.toByteArray());
- assertArrayEquals(expectedOuts[1].toByteArray(), err.toByteArray());
- assertArrayEquals(expectedOuts[2].toByteArray(), ctl.toByteArray());
+ assertThat(out.toByteArray()).isEqualTo(expectedOuts[0].toByteArray());
+ assertThat(err.toByteArray()).isEqualTo(expectedOuts[1].toByteArray());
+ assertThat(ctl.toByteArray()).isEqualTo(expectedOuts[2].toByteArray());
}
private static byte[] chunk(int stream, String payload) {
diff --git a/src/test/java/com/google/devtools/build/lib/util/io/StreamMultiplexerTest.java b/src/test/java/com/google/devtools/build/lib/util/io/StreamMultiplexerTest.java
index 6d3f2c3292..6fd7e2ee3e 100644
--- a/src/test/java/com/google/devtools/build/lib/util/io/StreamMultiplexerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/io/StreamMultiplexerTest.java
@@ -14,21 +14,17 @@
package com.google.devtools.build.lib.util.io;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
import com.google.common.io.ByteStreams;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Test for {@link StreamMultiplexer}.
@@ -55,7 +51,7 @@ public class StreamMultiplexerTest {
out.flush();
err.flush();
ctl.flush();
- assertEquals(0, multiplexed.toByteArray().length);
+ assertThat(multiplexed.toByteArray()).isEmpty();
}
private static byte[] getLatin(String string)
@@ -98,13 +94,13 @@ public class StreamMultiplexerTest {
throws Exception {
out.write(getLatin("There are no newline characters in here, so it won't" +
" get written just yet."));
- assertArrayEquals(multiplexed.toByteArray(), new byte[0]);
+ assertThat(new byte[0]).isEqualTo(multiplexed.toByteArray());
}
@Test
public void testNewlineTriggersFlush() throws Exception {
out.write(getLatin("No newline just yet, so no flushing. "));
- assertArrayEquals(multiplexed.toByteArray(), new byte[0]);
+ assertThat(new byte[0]).isEqualTo(multiplexed.toByteArray());
out.write(getLatin("OK, here we go:\nAnd more to come."));
assertMessage(
multiplexed.toByteArray(), 0, "No newline just yet, so no flushing. OK, here we go:\n");
@@ -116,7 +112,7 @@ public class StreamMultiplexerTest {
@Test
public void testFlush() throws Exception {
out.write(getLatin("Don't forget to flush!"));
- assertArrayEquals(new byte[0], multiplexed.toByteArray());
+ assertThat(multiplexed.toByteArray()).isEqualTo(new byte[0]);
out.flush(); // now the output will appear in multiplexed.
assertStartsWith(multiplexed.toByteArray(), 1, 0, 0, 0);
assertMessage(multiplexed.toByteArray(), 0, "Don't forget to flush!");
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/FileSystemTest.java b/src/test/java/com/google/devtools/build/lib/vfs/FileSystemTest.java
index e15fe52d01..64b8a69375 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/FileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/FileSystemTest.java
@@ -14,12 +14,8 @@
package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.io.BaseEncoding;
@@ -124,7 +120,7 @@ public abstract class FileSystemTest {
@SuppressWarnings("unused") // Subclasses may throw.
protected void expectNotFound(Path path) throws IOException {
try {
- assertNull(path.statIfFound());
+ assertThat(path.statIfFound()).isNull();
} catch (IOException e) {
// May be because of a non-directory path component. Parse exception to check this.
Matcher matcher = STAT_SUBDIR_ERROR.matcher(e.getMessage());
@@ -255,25 +251,25 @@ public abstract class FileSystemTest {
@Test
public void testIsFileForNonexistingPath() {
Path nonExistingPath = testFS.getPath("/something/strange");
- assertFalse(nonExistingPath.isFile());
+ assertThat(nonExistingPath.isFile()).isFalse();
}
@Test
public void testIsDirectoryForNonexistingPath() {
Path nonExistingPath = testFS.getPath("/something/strange");
- assertFalse(nonExistingPath.isDirectory());
+ assertThat(nonExistingPath.isDirectory()).isFalse();
}
@Test
public void testIsLinkForNonexistingPath() {
Path nonExistingPath = testFS.getPath("/something/strange");
- assertFalse(nonExistingPath.isSymbolicLink());
+ assertThat(nonExistingPath.isSymbolicLink()).isFalse();
}
@Test
public void testExistsForNonexistingPath() throws Exception {
Path nonExistingPath = testFS.getPath("/something/strange");
- assertFalse(nonExistingPath.exists());
+ assertThat(nonExistingPath.exists()).isFalse();
expectNotFound(nonExistingPath);
}
@@ -284,7 +280,7 @@ public abstract class FileSystemTest {
Path child = inaccessible.getChild("child");
FileSystemUtils.createEmptyFile(child);
inaccessible.setExecutable(false);
- assertFalse(child.exists());
+ assertThat(child.exists()).isFalse();
try {
child.statIfFound();
fail();
@@ -299,7 +295,7 @@ public abstract class FileSystemTest {
foo.createDirectory();
Path nonDir = foo.getRelative("bar");
FileSystemUtils.createEmptyFile(nonDir);
- assertNull(nonDir.getRelative("file").statIfFound());
+ assertThat(nonDir.getRelative("file").statIfFound()).isNull();
}
// The following tests check the handling of the current working directory.
@@ -308,20 +304,20 @@ public abstract class FileSystemTest {
Path relativeCreatedPath = absolutize("some-file");
Path expectedResult = workingDir.getRelative(PathFragment.create("some-file"));
- assertEquals(expectedResult, relativeCreatedPath);
+ assertThat(relativeCreatedPath).isEqualTo(expectedResult);
}
// The following tests check the handling of the root directory
@Test
public void testRootIsDirectory() {
Path rootPath = testFS.getPath("/");
- assertTrue(rootPath.isDirectory());
+ assertThat(rootPath.isDirectory()).isTrue();
}
@Test
public void testRootHasNoParent() {
Path rootPath = testFS.getPath("/");
- assertNull(rootPath.getParentDirectory());
+ assertThat(rootPath.getParentDirectory()).isNull();
}
// The following functions test the creation of files/links/directories.
@@ -329,58 +325,58 @@ public abstract class FileSystemTest {
public void testFileExists() throws Exception {
Path someFile = absolutize("some-file");
FileSystemUtils.createEmptyFile(someFile);
- assertTrue(someFile.exists());
- assertNotNull(someFile.statIfFound());
+ assertThat(someFile.exists()).isTrue();
+ assertThat(someFile.statIfFound()).isNotNull();
}
@Test
public void testFileIsFile() throws Exception {
Path someFile = absolutize("some-file");
FileSystemUtils.createEmptyFile(someFile);
- assertTrue(someFile.isFile());
+ assertThat(someFile.isFile()).isTrue();
}
@Test
public void testFileIsNotDirectory() throws Exception {
Path someFile = absolutize("some-file");
FileSystemUtils.createEmptyFile(someFile);
- assertFalse(someFile.isDirectory());
+ assertThat(someFile.isDirectory()).isFalse();
}
@Test
public void testFileIsNotSymbolicLink() throws Exception {
Path someFile = absolutize("some-file");
FileSystemUtils.createEmptyFile(someFile);
- assertFalse(someFile.isSymbolicLink());
+ assertThat(someFile.isSymbolicLink()).isFalse();
}
@Test
public void testDirectoryExists() throws Exception {
Path someDirectory = absolutize("some-dir");
someDirectory.createDirectory();
- assertTrue(someDirectory.exists());
- assertNotNull(someDirectory.statIfFound());
+ assertThat(someDirectory.exists()).isTrue();
+ assertThat(someDirectory.statIfFound()).isNotNull();
}
@Test
public void testDirectoryIsDirectory() throws Exception {
Path someDirectory = absolutize("some-dir");
someDirectory.createDirectory();
- assertTrue(someDirectory.isDirectory());
+ assertThat(someDirectory.isDirectory()).isTrue();
}
@Test
public void testDirectoryIsNotFile() throws Exception {
Path someDirectory = absolutize("some-dir");
someDirectory.createDirectory();
- assertFalse(someDirectory.isFile());
+ assertThat(someDirectory.isFile()).isFalse();
}
@Test
public void testDirectoryIsNotSymbolicLink() throws Exception {
Path someDirectory = absolutize("some-dir");
someDirectory.createDirectory();
- assertFalse(someDirectory.isSymbolicLink());
+ assertThat(someDirectory.isSymbolicLink()).isFalse();
}
@Test
@@ -388,8 +384,8 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
Path someLink = absolutize("some-link");
someLink.createSymbolicLink(xFile);
- assertTrue(someLink.exists());
- assertNotNull(someLink.statIfFound());
+ assertThat(someLink.exists()).isTrue();
+ assertThat(someLink.statIfFound()).isNotNull();
}
}
@@ -398,7 +394,7 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
Path someLink = absolutize("some-link");
someLink.createSymbolicLink(xFile);
- assertTrue(someLink.isSymbolicLink());
+ assertThat(someLink.isSymbolicLink()).isTrue();
}
}
@@ -407,7 +403,7 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
Path someLink = absolutize("some-link");
someLink.createSymbolicLink(xFile);
- assertTrue(someLink.isFile());
+ assertThat(someLink.isFile()).isTrue();
}
}
@@ -416,7 +412,7 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
Path someLink = absolutize("some-link");
someLink.createSymbolicLink(xFile);
- assertFalse(someLink.isDirectory());
+ assertThat(someLink.isDirectory()).isFalse();
}
}
@@ -425,8 +421,8 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
Path someLink = absolutize("some-link");
someLink.createSymbolicLink(xEmptyDirectory);
- assertTrue(someLink.exists());
- assertNotNull(someLink.statIfFound());
+ assertThat(someLink.exists()).isTrue();
+ assertThat(someLink.statIfFound()).isNotNull();
}
}
@@ -435,7 +431,7 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
Path someLink = absolutize("some-link");
someLink.createSymbolicLink(xEmptyDirectory);
- assertTrue(someLink.isSymbolicLink());
+ assertThat(someLink.isSymbolicLink()).isTrue();
}
}
@@ -444,7 +440,7 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
Path someLink = absolutize("some-link");
someLink.createSymbolicLink(xEmptyDirectory);
- assertTrue(someLink.isDirectory());
+ assertThat(someLink.isDirectory()).isTrue();
}
}
@@ -453,7 +449,7 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
Path someLink = absolutize("some-link");
someLink.createSymbolicLink(xEmptyDirectory);
- assertFalse(someLink.isFile());
+ assertThat(someLink.isFile()).isFalse();
}
}
@@ -462,7 +458,7 @@ public abstract class FileSystemTest {
Path somePath = absolutize("file-name");
FileSystemUtils.createEmptyFile(somePath);
Path childOfNonDir = somePath.getChild("child");
- assertFalse(childOfNonDir.exists());
+ assertThat(childOfNonDir.exists()).isFalse();
expectNotFound(childOfNonDir);
}
@@ -470,7 +466,7 @@ public abstract class FileSystemTest {
public void testCreateDirectoryIsEmpty() throws Exception {
Path newPath = xEmptyDirectory.getChild("new-dir");
newPath.createDirectory();
- assertEquals(0, newPath.getDirectoryEntries().size());
+ assertThat(newPath.getDirectoryEntries()).isEmpty();
}
@Test
@@ -484,35 +480,35 @@ public abstract class FileSystemTest {
@Test
public void testCreateDirectories() throws Exception {
Path newPath = absolutize("new-dir/sub/directory");
- assertTrue(FileSystemUtils.createDirectoryAndParents(newPath));
+ assertThat(FileSystemUtils.createDirectoryAndParents(newPath)).isTrue();
}
@Test
public void testCreateDirectoriesIsDirectory() throws Exception {
Path newPath = absolutize("new-dir/sub/directory");
FileSystemUtils.createDirectoryAndParents(newPath);
- assertTrue(newPath.isDirectory());
+ assertThat(newPath.isDirectory()).isTrue();
}
@Test
public void testCreateDirectoriesIsNotFile() throws Exception {
Path newPath = absolutize("new-dir/sub/directory");
FileSystemUtils.createDirectoryAndParents(newPath);
- assertFalse(newPath.isFile());
+ assertThat(newPath.isFile()).isFalse();
}
@Test
public void testCreateDirectoriesIsNotSymbolicLink() throws Exception {
Path newPath = absolutize("new-dir/sub/directory");
FileSystemUtils.createDirectoryAndParents(newPath);
- assertFalse(newPath.isSymbolicLink());
+ assertThat(newPath.isSymbolicLink()).isFalse();
}
@Test
public void testCreateDirectoriesIsEmpty() throws Exception {
Path newPath = absolutize("new-dir/sub/directory");
FileSystemUtils.createDirectoryAndParents(newPath);
- assertEquals(0, newPath.getDirectoryEntries().size());
+ assertThat(newPath.getDirectoryEntries()).isEmpty();
}
@Test
@@ -528,7 +524,7 @@ public abstract class FileSystemTest {
Path newPath = xEmptyDirectory.getChild("new-file");
FileSystemUtils.createEmptyFile(newPath);
- assertEquals(0, newPath.getFileSize());
+ assertThat(newPath.getFileSize()).isEqualTo(0);
}
@Test
@@ -543,7 +539,7 @@ public abstract class FileSystemTest {
// creation of files/links/directories.
@Test
public void testCreateDirectoryWhereDirectoryAlreadyExists() throws Exception {
- assertFalse(xEmptyDirectory.createDirectory());
+ assertThat(xEmptyDirectory.createDirectory()).isFalse();
}
@Test
@@ -563,7 +559,7 @@ public abstract class FileSystemTest {
newPath.createDirectory();
fail();
} catch (FileNotFoundException e) {
- assertThat(e.getMessage()).endsWith(" (No such file or directory)");
+ assertThat(e).hasMessageThat().endsWith(" (No such file or directory)");
}
}
@@ -586,7 +582,7 @@ public abstract class FileSystemTest {
FileSystemUtils.createEmptyFile(newPath);
fail();
} catch (FileNotFoundException e) {
- assertThat(e.getMessage()).endsWith(" (No such file or directory)");
+ assertThat(e).hasMessageThat().endsWith(" (No such file or directory)");
}
}
@@ -611,7 +607,7 @@ public abstract class FileSystemTest {
FileSystemUtils.createEmptyFile(wrongPath);
fail();
} catch (IOException e) {
- assertThat(e.getMessage()).endsWith(" (Not a directory)");
+ assertThat(e).hasMessageThat().endsWith(" (Not a directory)");
}
}
@@ -624,7 +620,7 @@ public abstract class FileSystemTest {
wrongPath.createDirectory();
fail();
} catch (IOException e) {
- assertThat(e.getMessage()).endsWith(" (Not a directory)");
+ assertThat(e).hasMessageThat().endsWith(" (Not a directory)");
}
}
@@ -671,38 +667,38 @@ public abstract class FileSystemTest {
// Test the removal of items
@Test
public void testDeleteDirectory() throws Exception {
- assertTrue(xEmptyDirectory.delete());
+ assertThat(xEmptyDirectory.delete()).isTrue();
}
@Test
public void testDeleteDirectoryIsNotDirectory() throws Exception {
xEmptyDirectory.delete();
- assertFalse(xEmptyDirectory.isDirectory());
+ assertThat(xEmptyDirectory.isDirectory()).isFalse();
}
@Test
public void testDeleteDirectoryParentSize() throws Exception {
int parentSize = workingDir.getDirectoryEntries().size();
xEmptyDirectory.delete();
- assertEquals(workingDir.getDirectoryEntries().size(), parentSize - 1);
+ assertThat(parentSize - 1).isEqualTo(workingDir.getDirectoryEntries().size());
}
@Test
public void testDeleteFile() throws Exception {
- assertTrue(xFile.delete());
+ assertThat(xFile.delete()).isTrue();
}
@Test
public void testDeleteFileIsNotFile() throws Exception {
xFile.delete();
- assertFalse(xEmptyDirectory.isFile());
+ assertThat(xEmptyDirectory.isFile()).isFalse();
}
@Test
public void testDeleteFileParentSize() throws Exception {
int parentSize = workingDir.getDirectoryEntries().size();
xFile.delete();
- assertEquals(workingDir.getDirectoryEntries().size(), parentSize - 1);
+ assertThat(parentSize - 1).isEqualTo(workingDir.getDirectoryEntries().size());
}
@Test
@@ -715,20 +711,20 @@ public abstract class FileSystemTest {
FileSystemUtils.createEmptyFile(newPath2);
FileSystemUtils.createEmptyFile(newPath3);
- assertTrue(newPath2.delete());
+ assertThat(newPath2.delete()).isTrue();
assertThat(xEmptyDirectory.getDirectoryEntries()).containsExactly(newPath1, newPath3);
}
@Test
public void testDeleteNonExistingDir() throws Exception {
Path path = xEmptyDirectory.getRelative("non-existing-dir");
- assertFalse(path.delete());
+ assertThat(path.delete()).isFalse();
}
@Test
public void testDeleteNotADirectoryPath() throws Exception {
Path path = xFile.getChild("new-file");
- assertFalse(path.delete());
+ assertThat(path.delete()).isFalse();
}
// Here we test the situations where delete should throw exceptions.
@@ -751,7 +747,7 @@ public abstract class FileSystemTest {
// Expected
}
- assertTrue(xNonEmptyDirectory.isDirectory());
+ assertThat(xNonEmptyDirectory.isDirectory()).isTrue();
}
@Test
@@ -763,7 +759,7 @@ public abstract class FileSystemTest {
// Expected
}
- assertTrue(xNonEmptyDirectoryFoo.isFile());
+ assertThat(xNonEmptyDirectoryFoo.isFile()).isTrue();
}
@Test
@@ -774,10 +770,12 @@ public abstract class FileSystemTest {
fail();
} catch (IOException e) {
String msg = e.getMessage();
- assertTrue(String.format("got %s want EBUSY or ENOTEMPTY", msg),
- msg.endsWith(" (Directory not empty)")
- || msg.endsWith(" (Device or resource busy)")
- || msg.endsWith(" (Is a directory)")); // Happens on OS X.
+ assertWithMessage(String.format("got %s want EBUSY or ENOTEMPTY", msg))
+ .that(
+ msg.endsWith(" (Directory not empty)")
+ || msg.endsWith(" (Device or resource busy)")
+ || msg.endsWith(" (Is a directory)"))
+ .isTrue(); // Happens on OS X.
}
}
@@ -787,7 +785,7 @@ public abstract class FileSystemTest {
storeReferenceTime(workingDir.getLastModifiedTime());
Path newPath = absolutize("new-file");
FileSystemUtils.createEmptyFile(newPath);
- assertTrue(isLaterThanreferenceTime(workingDir.getLastModifiedTime()));
+ assertThat(isLaterThanreferenceTime(workingDir.getLastModifiedTime())).isTrue();
}
@Test
@@ -796,7 +794,7 @@ public abstract class FileSystemTest {
FileSystemUtils.createEmptyFile(newPath);
storeReferenceTime(workingDir.getLastModifiedTime());
newPath.delete();
- assertTrue(isLaterThanreferenceTime(workingDir.getLastModifiedTime()));
+ assertThat(isLaterThanreferenceTime(workingDir.getLastModifiedTime())).isTrue();
}
// This test is a little bit strange, as we cannot test the progression
@@ -811,7 +809,7 @@ public abstract class FileSystemTest {
Path newFile = absolutize("new-file");
storeReferenceTime(syncFile.getLastModifiedTime());
FileSystemUtils.createEmptyFile(newFile);
- assertTrue(isLaterThanreferenceTime(newFile.getLastModifiedTime()));
+ assertThat(isLaterThanreferenceTime(newFile.getLastModifiedTime())).isTrue();
}
@Test
@@ -821,15 +819,15 @@ public abstract class FileSystemTest {
Path newPath = absolutize("new-dir");
storeReferenceTime(syncFile.getLastModifiedTime());
- assertTrue(newPath.createDirectory());
- assertTrue(isLaterThanreferenceTime(newPath.getLastModifiedTime()));
+ assertThat(newPath.createDirectory()).isTrue();
+ assertThat(isLaterThanreferenceTime(newPath.getLastModifiedTime())).isTrue();
}
@Test
public void testWriteChangesModifiedTime() throws Exception {
storeReferenceTime(xFile.getLastModifiedTime());
FileSystemUtils.writeContentAsLatin1(xFile, "abc19");
- assertTrue(isLaterThanreferenceTime(xFile.getLastModifiedTime()));
+ assertThat(isLaterThanreferenceTime(xFile.getLastModifiedTime())).isTrue();
}
@Test
@@ -860,7 +858,7 @@ public abstract class FileSystemTest {
String testData = "abc19";
FileSystemUtils.writeContentAsLatin1(xFile, testData);
- assertEquals(testData.length(), xFile.getFileSize());
+ assertThat(xFile.getFileSize()).isEqualTo(testData.length());
}
// Testing the input/output routines
@@ -871,7 +869,7 @@ public abstract class FileSystemTest {
FileSystemUtils.writeContentAsLatin1(xFile, testData);
String resultData = new String(FileSystemUtils.readContentAsLatin1(xFile));
- assertEquals(testData,resultData);
+ assertThat(resultData).isEqualTo(testData);
}
@Test
@@ -882,7 +880,7 @@ public abstract class FileSystemTest {
try (InputStream inStream = xFile.getInputStream()) {
inStream.read();
- assertEquals(-1, inStream.read());
+ assertThat(inStream.read()).isEqualTo(-1);
}
}
@@ -897,7 +895,7 @@ public abstract class FileSystemTest {
try (InputStream inStream = xFile.getInputStream()) {
for (int i = 33; i < 126; i++) {
int readValue = inStream.read();
- assertEquals(i, readValue);
+ assertThat(readValue).isEqualTo(i);
}
}
}
@@ -919,7 +917,7 @@ public abstract class FileSystemTest {
try (InputStream inStream = xFile.getInputStream()) {
for (int i = 33; i < 155; i++) {
int readValue = inStream.read();
- assertEquals(i, readValue);
+ assertThat(readValue).isEqualTo(i);
}
}
}
@@ -934,7 +932,7 @@ public abstract class FileSystemTest {
}
try (InputStream inStream = xFile.getInputStream()) {
- assertEquals(-1, inStream.read());
+ assertThat(inStream.read()).isEqualTo(-1);
}
}
@@ -946,7 +944,7 @@ public abstract class FileSystemTest {
out.write(42);
}
- assertTrue(newFile.isFile());
+ assertThat(newFile.isFile()).isTrue();
}
@Test
@@ -973,8 +971,8 @@ public abstract class FileSystemTest {
@Test
public void testCanRenameToUnusedName() throws Exception {
xFile.renameTo(xNothing);
- assertFalse(xFile.exists());
- assertTrue(xNothing.isFile());
+ assertThat(xFile.exists()).isFalse();
+ assertThat(xNothing.isFile()).isTrue();
}
@Test
@@ -982,15 +980,15 @@ public abstract class FileSystemTest {
Path otherFile = absolutize("otherFile");
FileSystemUtils.createEmptyFile(otherFile);
xFile.renameTo(otherFile); // succeeds
- assertFalse(xFile.exists());
- assertTrue(otherFile.isFile());
+ assertThat(xFile.exists()).isFalse();
+ assertThat(otherFile.isFile()).isTrue();
}
@Test
public void testCanRenameDirToExistingEmptyDir() throws Exception {
xNonEmptyDirectory.renameTo(xEmptyDirectory); // succeeds
- assertFalse(xNonEmptyDirectory.exists());
- assertTrue(xEmptyDirectory.isDirectory());
+ assertThat(xNonEmptyDirectory.exists()).isFalse();
+ assertThat(xEmptyDirectory.isDirectory()).isTrue();
assertThat(xEmptyDirectory.getDirectoryEntries()).isNotEmpty();
}
@@ -1000,7 +998,7 @@ public abstract class FileSystemTest {
xEmptyDirectory.renameTo(xNonEmptyDirectory);
fail();
} catch (IOException e) {
- assertThat(e.getMessage()).endsWith(" (Directory not empty)");
+ assertThat(e).hasMessageThat().endsWith(" (Directory not empty)");
}
}
@@ -1013,8 +1011,8 @@ public abstract class FileSystemTest {
// Expected
}
- assertTrue(xNonEmptyDirectory.isDirectory());
- assertTrue(xEmptyDirectory.isDirectory());
+ assertThat(xNonEmptyDirectory.isDirectory()).isTrue();
+ assertThat(xEmptyDirectory.isDirectory()).isTrue();
assertThat(xEmptyDirectory.getDirectoryEntries()).isEmpty();
assertThat(xNonEmptyDirectory.getDirectoryEntries()).isNotEmpty();
}
@@ -1038,8 +1036,8 @@ public abstract class FileSystemTest {
// Expected
}
- assertTrue(xEmptyDirectory.isDirectory());
- assertTrue(xFile.isFile());
+ assertThat(xEmptyDirectory.isDirectory()).isTrue();
+ assertThat(xFile.isFile()).isTrue();
}
@Test
@@ -1061,8 +1059,8 @@ public abstract class FileSystemTest {
// Expected
}
- assertTrue(xEmptyDirectory.isDirectory());
- assertTrue(xFile.isFile());
+ assertThat(xEmptyDirectory.isDirectory()).isTrue();
+ assertThat(xFile.isFile()).isTrue();
}
@Test
@@ -1073,7 +1071,7 @@ public abstract class FileSystemTest {
nonExistingPath.renameTo(targetPath);
fail();
} catch (FileNotFoundException e) {
- assertThat(e.getMessage()).endsWith(" (No such file or directory)");
+ assertThat(e).hasMessageThat().endsWith(" (No such file or directory)");
}
}
@@ -1101,27 +1099,27 @@ public abstract class FileSystemTest {
// Test the access permissions
@Test
public void testNewFilesAreWritable() throws Exception {
- assertTrue(xFile.isWritable());
+ assertThat(xFile.isWritable()).isTrue();
}
@Test
public void testNewFilesAreReadable() throws Exception {
- assertTrue(xFile.isReadable());
+ assertThat(xFile.isReadable()).isTrue();
}
@Test
public void testNewDirsAreWritable() throws Exception {
- assertTrue(xEmptyDirectory.isWritable());
+ assertThat(xEmptyDirectory.isWritable()).isTrue();
}
@Test
public void testNewDirsAreReadable() throws Exception {
- assertTrue(xEmptyDirectory.isReadable());
+ assertThat(xEmptyDirectory.isReadable()).isTrue();
}
@Test
public void testNewDirsAreExecutable() throws Exception {
- assertTrue(xEmptyDirectory.isExecutable());
+ assertThat(xEmptyDirectory.isExecutable()).isTrue();
}
@Test
@@ -1167,25 +1165,25 @@ public abstract class FileSystemTest {
@Test
public void testSetReadableOnFile() throws Exception {
xFile.setReadable(false);
- assertFalse(xFile.isReadable());
+ assertThat(xFile.isReadable()).isFalse();
xFile.setReadable(true);
- assertTrue(xFile.isReadable());
+ assertThat(xFile.isReadable()).isTrue();
}
@Test
public void testSetWritableOnFile() throws Exception {
xFile.setWritable(false);
- assertFalse(xFile.isWritable());
+ assertThat(xFile.isWritable()).isFalse();
xFile.setWritable(true);
- assertTrue(xFile.isWritable());
+ assertThat(xFile.isWritable()).isTrue();
}
@Test
public void testSetExecutableOnFile() throws Exception {
xFile.setExecutable(true);
- assertTrue(xFile.isExecutable());
+ assertThat(xFile.isExecutable()).isTrue();
xFile.setExecutable(false);
- assertFalse(xFile.isExecutable());
+ assertThat(xFile.isExecutable()).isFalse();
}
@Test
@@ -1197,7 +1195,7 @@ public abstract class FileSystemTest {
xNonEmptyDirectoryFoo.isWritable(); // i.e. stat
fail();
} catch (IOException e) {
- assertThat(e.getMessage()).endsWith(" (Permission denied)");
+ assertThat(e).hasMessageThat().endsWith(" (Permission denied)");
}
}
@@ -1259,7 +1257,7 @@ public abstract class FileSystemTest {
xFile.renameTo(xNonEmptyDirectoryBar);
fail("No exception thrown.");
} catch (IOException e) {
- assertThat(e.getMessage()).endsWith(" (Permission denied)");
+ assertThat(e).hasMessageThat().endsWith(" (Permission denied)");
}
}
@@ -1271,7 +1269,7 @@ public abstract class FileSystemTest {
xNonEmptyDirectoryFoo.renameTo(xNothing);
fail("No exception thrown.");
} catch (IOException e) {
- assertThat(e.getMessage()).endsWith(" (Permission denied)");
+ assertThat(e).hasMessageThat().endsWith(" (Permission denied)");
}
}
@@ -1306,8 +1304,8 @@ public abstract class FileSystemTest {
public void testGetMD5DigestForEmptyFile() throws Exception {
Fingerprint fp = new Fingerprint();
fp.addBytes(new byte[0]);
- assertEquals(BaseEncoding.base16().lowerCase().encode(xFile.getMD5Digest()),
- fp.hexDigestAndReset());
+ assertThat(fp.hexDigestAndReset())
+ .isEqualTo(BaseEncoding.base16().lowerCase().encode(xFile.getMD5Digest()));
}
@Test
@@ -1319,8 +1317,8 @@ public abstract class FileSystemTest {
FileSystemUtils.writeContent(xFile, buffer);
Fingerprint fp = new Fingerprint();
fp.addBytes(buffer);
- assertEquals(BaseEncoding.base16().lowerCase().encode(xFile.getMD5Digest()),
- fp.hexDigestAndReset());
+ assertThat(fp.hexDigestAndReset())
+ .isEqualTo(BaseEncoding.base16().lowerCase().encode(xFile.getMD5Digest()));
}
@Test
@@ -1335,7 +1333,7 @@ public abstract class FileSystemTest {
@Test
public void testStatNullableFailsFastOnNonExistingFiles() throws Exception {
- assertNull(xNothing.statNullable());
+ assertThat(xNothing.statNullable()).isNull();
}
@Test
@@ -1343,8 +1341,8 @@ public abstract class FileSystemTest {
if (supportsSymlinks) {
createSymbolicLink(xLink, xFile);
FileSystemUtils.createEmptyFile(xFile);
- assertEquals(xFile.asFragment(), testFS.resolveOneLink(xLink));
- assertEquals(xFile, xLink.resolveSymbolicLinks());
+ assertThat(testFS.resolveOneLink(xLink)).isEqualTo(xFile.asFragment());
+ assertThat(xLink.resolveSymbolicLinks()).isEqualTo(xFile);
}
}
@@ -1352,7 +1350,7 @@ public abstract class FileSystemTest {
public void testResolveDanglingSymlinks() throws Exception {
if (supportsSymlinks) {
createSymbolicLink(xLink, xNothing);
- assertEquals(xNothing.asFragment(), testFS.resolveOneLink(xLink));
+ assertThat(testFS.resolveOneLink(xLink)).isEqualTo(xNothing.asFragment());
try {
xLink.resolveSymbolicLinks();
fail();
@@ -1364,8 +1362,8 @@ public abstract class FileSystemTest {
@Test
public void testResolveNonSymlinks() throws Exception {
if (supportsSymlinks) {
- assertNull(testFS.resolveOneLink(xFile));
- assertEquals(xFile, xFile.resolveSymbolicLinks());
+ assertThat(testFS.resolveOneLink(xFile)).isNull();
+ assertThat(xFile.resolveSymbolicLinks()).isEqualTo(xFile);
}
}
@@ -1375,11 +1373,11 @@ public abstract class FileSystemTest {
return;
}
xFile.createHardLink(xLink);
- assertTrue(xFile.exists());
- assertTrue(xLink.exists());
- assertTrue(xFile.isFile());
- assertTrue(xLink.isFile());
- assertTrue(isHardLinked(xFile, xLink));
+ assertThat(xFile.exists()).isTrue();
+ assertThat(xLink.exists()).isTrue();
+ assertThat(xFile.isFile()).isTrue();
+ assertThat(xLink.isFile()).isTrue();
+ assertThat(isHardLinked(xFile, xLink)).isTrue();
}
@Test
@@ -1396,8 +1394,8 @@ public abstract class FileSystemTest {
} catch (FileNotFoundException expected) {
assertThat(expected).hasMessage("File \"xFile\" linked from \"xLink\" does not exist");
}
- assertFalse(xFile.exists());
- assertFalse(xLink.exists());
+ assertThat(xFile.exists()).isFalse();
+ assertThat(xLink.exists()).isFalse();
}
@Test
@@ -1417,8 +1415,8 @@ public abstract class FileSystemTest {
} catch (FileNotFoundException expected) {
assertThat(expected).hasMessage("File \"xFile\" linked from \"xLink\" does not exist");
}
- assertFalse(xFile.exists());
- assertTrue(xLink.exists());
+ assertThat(xFile.exists()).isFalse();
+ assertThat(xLink.exists()).isTrue();
}
@Test
@@ -1436,9 +1434,9 @@ public abstract class FileSystemTest {
} catch (FileAlreadyExistsException expected) {
assertThat(expected).hasMessage("New link file \"xLink\" already exists");
}
- assertTrue(xFile.exists());
- assertTrue(xLink.exists());
- assertFalse(isHardLinked(xFile, xLink));
+ assertThat(xFile.exists()).isTrue();
+ assertThat(xLink.exists()).isTrue();
+ assertThat(isHardLinked(xFile, xLink)).isFalse();
}
protected boolean isHardLinked(Path a, Path b) throws IOException {
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/FileSystemUtilsTest.java b/src/test/java/com/google/devtools/build/lib/vfs/FileSystemUtilsTest.java
index cd553bbcf2..f6898ad070 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/FileSystemUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/FileSystemUtilsTest.java
@@ -27,11 +27,6 @@ import static com.google.devtools.build.lib.vfs.FileSystemUtils.touchFile;
import static com.google.devtools.build.lib.vfs.FileSystemUtils.traverseTree;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Predicate;
@@ -119,35 +114,35 @@ public class FileSystemUtilsTest {
private void checkTestDirectoryTreesBelow(Path toPath) throws IOException {
Path copiedFile1 = toPath.getChild("file-1");
- assertTrue(copiedFile1.exists());
- assertTrue(copiedFile1.isFile());
+ assertThat(copiedFile1.exists()).isTrue();
+ assertThat(copiedFile1.isFile()).isTrue();
Path copiedFile2 = toPath.getChild("file-2");
- assertTrue(copiedFile2.exists());
- assertTrue(copiedFile2.isFile());
+ assertThat(copiedFile2.exists()).isTrue();
+ assertThat(copiedFile2.isFile()).isTrue();
Path copiedADir = toPath.getChild("a-dir");
- assertTrue(copiedADir.exists());
- assertTrue(copiedADir.isDirectory());
+ assertThat(copiedADir.exists()).isTrue();
+ assertThat(copiedADir.isDirectory()).isTrue();
Collection<Path> aDirEntries = copiedADir.getDirectoryEntries();
assertThat(aDirEntries).hasSize(2);
Path copiedFile3 = copiedADir.getChild("file-3");
- assertTrue(copiedFile3.exists());
- assertTrue(copiedFile3.isFile());
+ assertThat(copiedFile3.exists()).isTrue();
+ assertThat(copiedFile3.isFile()).isTrue();
Path copiedInnerDir = copiedADir.getChild("inner-dir");
- assertTrue(copiedInnerDir.exists());
- assertTrue(copiedInnerDir.isDirectory());
+ assertThat(copiedInnerDir.exists()).isTrue();
+ assertThat(copiedInnerDir.isDirectory()).isTrue();
Path copiedLink1 = copiedInnerDir.getChild("link-1");
- assertTrue(copiedLink1.exists());
- assertFalse(copiedLink1.isSymbolicLink());
+ assertThat(copiedLink1.exists()).isTrue();
+ assertThat(copiedLink1.isSymbolicLink()).isFalse();
Path copiedDirLink = copiedInnerDir.getChild("dir-link");
- assertTrue(copiedDirLink.exists());
- assertTrue(copiedDirLink.isDirectory());
- assertTrue(copiedDirLink.getChild("file-5").exists());
+ assertThat(copiedDirLink.exists()).isTrue();
+ assertThat(copiedDirLink.isDirectory()).isTrue();
+ assertThat(copiedDirLink.getChild("file-5").exists()).isTrue();
}
// tests
@@ -164,33 +159,33 @@ public class FileSystemUtilsTest {
FileSystemUtils.createEmptyFile(file);
long prevMtime = file.getLastModifiedTime();
BlazeTestUtils.changeModtime(file);
- assertFalse(prevMtime == file.getLastModifiedTime());
+ assertThat(prevMtime == file.getLastModifiedTime()).isFalse();
}
@Test
public void testCommonAncestor() {
- assertEquals(topDir, commonAncestor(topDir, topDir));
- assertEquals(topDir, commonAncestor(file1, file3));
- assertEquals(topDir, commonAncestor(file1, dirLink));
+ assertThat(commonAncestor(topDir, topDir)).isEqualTo(topDir);
+ assertThat(commonAncestor(file1, file3)).isEqualTo(topDir);
+ assertThat(commonAncestor(file1, dirLink)).isEqualTo(topDir);
}
@Test
public void testRelativePath() throws IOException {
createTestDirectoryTree();
- assertEquals("file-1", relativePath(topDir, file1).getPathString());
- assertEquals(".", relativePath(topDir, topDir).getPathString());
- assertEquals("a-dir/inner-dir/dir-link", relativePath(topDir, dirLink).getPathString());
- assertEquals("../file-4", relativePath(topDir, file4).getPathString());
- assertEquals("../../../file-4", relativePath(innerDir, file4).getPathString());
+ assertThat(relativePath(topDir, file1).getPathString()).isEqualTo("file-1");
+ assertThat(relativePath(topDir, topDir).getPathString()).isEqualTo(".");
+ assertThat(relativePath(topDir, dirLink).getPathString()).isEqualTo("a-dir/inner-dir/dir-link");
+ assertThat(relativePath(topDir, file4).getPathString()).isEqualTo("../file-4");
+ assertThat(relativePath(innerDir, file4).getPathString()).isEqualTo("../../../file-4");
}
@Test
public void testRemoveExtension_Strings() throws Exception {
- assertEquals("foo", removeExtension("foo.c"));
- assertEquals("a/foo", removeExtension("a/foo.c"));
- assertEquals("a.b/foo", removeExtension("a.b/foo"));
- assertEquals("foo", removeExtension("foo"));
- assertEquals("foo", removeExtension("foo."));
+ assertThat(removeExtension("foo.c")).isEqualTo("foo");
+ assertThat(removeExtension("a/foo.c")).isEqualTo("a/foo");
+ assertThat(removeExtension("a.b/foo")).isEqualTo("a.b/foo");
+ assertThat(removeExtension("foo")).isEqualTo("foo");
+ assertThat(removeExtension("foo.")).isEqualTo("foo");
}
@Test
@@ -203,11 +198,11 @@ public class FileSystemUtilsTest {
}
private static void assertPath(String expected, PathFragment actual) {
- assertEquals(expected, actual.getPathString());
+ assertThat(actual.getPathString()).isEqualTo(expected);
}
private static void assertPath(String expected, Path actual) {
- assertEquals(expected, actual.getPathString());
+ assertThat(actual.getPathString()).isEqualTo(expected);
}
@Test
@@ -222,7 +217,7 @@ public class FileSystemUtilsTest {
assertPath("/foo.baz", FileSystemUtils.replaceExtension(fileSystem.getPath("/foo"), ".baz"));
assertPath("/foo.baz", FileSystemUtils.replaceExtension(fileSystem.getPath("/foo.cc"), ".baz"));
assertPath("/.baz", FileSystemUtils.replaceExtension(fileSystem.getPath("/.cc"), ".baz"));
- assertNull(FileSystemUtils.replaceExtension(fileSystem.getPath("/"), ".baz"));
+ assertThat(FileSystemUtils.replaceExtension(fileSystem.getPath("/"), ".baz")).isNull();
}
@Test
@@ -246,15 +241,17 @@ public class FileSystemUtilsTest {
assertPath("/foo.baz",
FileSystemUtils.replaceExtension(PathFragment.create("/foo.cc"), ".baz"));
assertPath(".baz", FileSystemUtils.replaceExtension(PathFragment.create(".cc"), ".baz"));
- assertNull(FileSystemUtils.replaceExtension(PathFragment.create("/"), ".baz"));
- assertNull(FileSystemUtils.replaceExtension(PathFragment.create(""), ".baz"));
+ assertThat(FileSystemUtils.replaceExtension(PathFragment.create("/"), ".baz")).isNull();
+ assertThat(FileSystemUtils.replaceExtension(PathFragment.create(""), ".baz")).isNull();
assertPath("foo/bar.baz",
FileSystemUtils.replaceExtension(PathFragment.create("foo/bar.pony"), ".baz", ".pony"));
assertPath("foo/bar.baz",
FileSystemUtils.replaceExtension(PathFragment.create("foo/bar"), ".baz", ""));
- assertNull(FileSystemUtils.replaceExtension(PathFragment.create(""), ".baz", ".pony"));
- assertNull(
- FileSystemUtils.replaceExtension(PathFragment.create("foo/bar.pony"), ".baz", ".unicorn"));
+ assertThat(FileSystemUtils.replaceExtension(PathFragment.create(""), ".baz", ".pony")).isNull();
+ assertThat(
+ FileSystemUtils.replaceExtension(
+ PathFragment.create("foo/bar.pony"), ".baz", ".unicorn"))
+ .isNull();
}
@Test
@@ -273,8 +270,8 @@ public class FileSystemUtilsTest {
appendWithoutExtension(PathFragment.create("libfoo.jar/"), "-src"));
assertPath("libfoo.src.jar",
appendWithoutExtension(PathFragment.create("libfoo.jar"), ".src"));
- assertNull(appendWithoutExtension(PathFragment.create("/"), "-src"));
- assertNull(appendWithoutExtension(PathFragment.create(""), "-src"));
+ assertThat(appendWithoutExtension(PathFragment.create("/"), "-src")).isNull();
+ assertThat(appendWithoutExtension(PathFragment.create(""), "-src")).isNull();
}
@Test
@@ -298,12 +295,12 @@ public class FileSystemUtilsTest {
public void testGetWorkingDirectory() {
String userDir = System.getProperty("user.dir");
- assertEquals(FileSystemUtils.getWorkingDirectory(fileSystem),
- fileSystem.getPath(System.getProperty("user.dir", "/")));
+ assertThat(fileSystem.getPath(System.getProperty("user.dir", "/")))
+ .isEqualTo(FileSystemUtils.getWorkingDirectory(fileSystem));
System.setProperty("user.dir", "/blah/blah/blah");
- assertEquals(FileSystemUtils.getWorkingDirectory(fileSystem),
- fileSystem.getPath("/blah/blah/blah"));
+ assertThat(fileSystem.getPath("/blah/blah/blah"))
+ .isEqualTo(FileSystemUtils.getWorkingDirectory(fileSystem));
System.setProperty("user.dir", userDir);
}
@@ -311,22 +308,21 @@ public class FileSystemUtilsTest {
@Test
public void testResolveRelativeToFilesystemWorkingDir() {
PathFragment relativePath = PathFragment.create("relative/path");
- assertEquals(workingDir.getRelative(relativePath),
- workingDir.getRelative(relativePath));
+ assertThat(workingDir.getRelative(relativePath))
+ .isEqualTo(workingDir.getRelative(relativePath));
PathFragment absolutePath = PathFragment.create("/absolute/path");
- assertEquals(fileSystem.getPath(absolutePath),
- workingDir.getRelative(absolutePath));
+ assertThat(workingDir.getRelative(absolutePath)).isEqualTo(fileSystem.getPath(absolutePath));
}
@Test
public void testTouchFileCreatesFile() throws IOException {
createTestDirectoryTree();
Path nonExistingFile = fileSystem.getPath("/previously-non-existing");
- assertFalse(nonExistingFile.exists());
+ assertThat(nonExistingFile.exists()).isFalse();
touchFile(nonExistingFile);
- assertTrue(nonExistingFile.exists());
+ assertThat(nonExistingFile.exists()).isTrue();
}
@Test
@@ -351,7 +347,7 @@ public class FileSystemUtilsTest {
copyFile(originalFile, copyTarget);
- assertTrue(Arrays.equals(content, FileSystemUtils.readContent(copyTarget)));
+ assertThat(FileSystemUtils.readContent(copyTarget)).isEqualTo(content);
}
@Test
@@ -365,8 +361,8 @@ public class FileSystemUtilsTest {
moveFile(originalFile, moveTarget);
- assertTrue(Arrays.equals(content, FileSystemUtils.readContent(moveTarget)));
- assertFalse(originalFile.exists());
+ assertThat(FileSystemUtils.readContent(moveTarget)).isEqualTo(content);
+ assertThat(originalFile.exists()).isFalse();
}
@Test
@@ -374,9 +370,9 @@ public class FileSystemUtilsTest {
createTestDirectoryTree();
String str = "this is a test of readContentWithLimit method";
FileSystemUtils.writeContent(file1, StandardCharsets.ISO_8859_1, str);
- assertEquals("", readStringFromFile(file1, 0));
- assertEquals(readStringFromFile(file1, 10), str.substring(0, 10));
- assertEquals(readStringFromFile(file1, 1000000), str);
+ assertThat(readStringFromFile(file1, 0)).isEmpty();
+ assertThat(str.substring(0, 10)).isEqualTo(readStringFromFile(file1, 10));
+ assertThat(str).isEqualTo(readStringFromFile(file1, 1000000));
}
private String readStringFromFile(Path file, int limit) throws IOException {
@@ -390,9 +386,8 @@ public class FileSystemUtilsTest {
FileSystemUtils.writeIsoLatin1(file1, "nobody says ");
FileSystemUtils.writeIsoLatin1(file1, "mary had");
FileSystemUtils.appendIsoLatin1(file1, "a little lamb");
- assertEquals(
- "mary had\na little lamb\n",
- new String(FileSystemUtils.readContentAsLatin1(file1)));
+ assertThat(new String(FileSystemUtils.readContentAsLatin1(file1)))
+ .isEqualTo("mary had\na little lamb\n");
}
@Test
@@ -408,19 +403,18 @@ public class FileSystemUtilsTest {
Path copyTarget = file2;
copyFile(originalFile, copyTarget);
- assertEquals(12345L, file2.getLastModifiedTime());
- assertFalse(file2.isExecutable());
- assertFalse(file2.isWritable());
+ assertThat(file2.getLastModifiedTime()).isEqualTo(12345L);
+ assertThat(file2.isExecutable()).isFalse();
+ assertThat(file2.isWritable()).isFalse();
file1.setWritable(true);
file1.setExecutable(true);
copyFile(originalFile, copyTarget);
- assertEquals(12345L, file2.getLastModifiedTime());
- assertTrue(file2.isExecutable());
- assertTrue(file2.isWritable());
-
+ assertThat(file2.getLastModifiedTime()).isEqualTo(12345L);
+ assertThat(file2.isExecutable()).isTrue();
+ assertThat(file2.isWritable()).isTrue();
}
@Test
@@ -448,10 +442,10 @@ public class FileSystemUtilsTest {
Path copyTarget = copyTool(topDir.getRelative("file-1"), aDir.getRelative("file-1"));
- assertTrue(Arrays.equals(content, FileSystemUtils.readContent(copyTarget)));
- assertEquals(file1.isWritable(), copyTarget.isWritable());
- assertEquals(file1.isExecutable(), copyTarget.isExecutable());
- assertEquals(file1.getLastModifiedTime(), copyTarget.getLastModifiedTime());
+ assertThat(FileSystemUtils.readContent(copyTarget)).isEqualTo(content);
+ assertThat(copyTarget.isWritable()).isEqualTo(file1.isWritable());
+ assertThat(copyTarget.isExecutable()).isEqualTo(file1.isExecutable());
+ assertThat(copyTarget.getLastModifiedTime()).isEqualTo(file1.getLastModifiedTime());
}
@Test
@@ -585,12 +579,12 @@ public class FileSystemUtilsTest {
Path toDelete = topDir;
deleteTree(toDelete);
- assertTrue(file4.exists());
- assertFalse(topDir.exists());
- assertFalse(file1.exists());
- assertFalse(file2.exists());
- assertFalse(aDir.exists());
- assertFalse(file3.exists());
+ assertThat(file4.exists()).isTrue();
+ assertThat(topDir.exists()).isFalse();
+ assertThat(file1.exists()).isFalse();
+ assertThat(file2.exists()).isFalse();
+ assertThat(aDir.exists()).isFalse();
+ assertThat(file3.exists()).isFalse();
}
@Test
@@ -608,9 +602,8 @@ public class FileSystemUtilsTest {
}
deleteTree(toDelete);
- assertFalse(topDir.exists());
- assertFalse(aDir.exists());
-
+ assertThat(topDir.exists()).isFalse();
+ assertThat(aDir.exists()).isFalse();
}
@Test
@@ -622,26 +615,26 @@ public class FileSystemUtilsTest {
deleteTree(toDelete);
- assertTrue(file4.exists());
- assertFalse(topDir.exists());
- assertFalse(file1.exists());
- assertFalse(file2.exists());
- assertFalse(aDir.exists());
- assertFalse(file3.exists());
+ assertThat(file4.exists()).isTrue();
+ assertThat(topDir.exists()).isFalse();
+ assertThat(file1.exists()).isFalse();
+ assertThat(file2.exists()).isFalse();
+ assertThat(aDir.exists()).isFalse();
+ assertThat(file3.exists()).isFalse();
}
@Test
public void testCreateDirectories() throws IOException {
Path mainPath = fileSystem.getPath("/some/where/deep/in/the/hierarchy");
- assertTrue(createDirectoryAndParents(mainPath));
- assertTrue(mainPath.exists());
- assertFalse(createDirectoryAndParents(mainPath));
+ assertThat(createDirectoryAndParents(mainPath)).isTrue();
+ assertThat(mainPath.exists()).isTrue();
+ assertThat(createDirectoryAndParents(mainPath)).isFalse();
}
@Test
public void testCreateDirectoriesWhenAncestorIsFile() throws IOException {
Path somewhereDeepIn = fileSystem.getPath("/somewhere/deep/in");
- assertTrue(createDirectoryAndParents(somewhereDeepIn.getParentDirectory()));
+ assertThat(createDirectoryAndParents(somewhereDeepIn.getParentDirectory())).isTrue();
FileSystemUtils.createEmptyFile(somewhereDeepIn);
Path theHierarchy = somewhereDeepIn.getChild("the-hierarchy");
try {
@@ -655,28 +648,28 @@ public class FileSystemUtilsTest {
@Test
public void testCreateDirectoriesWhenSymlinkToDir() throws IOException {
Path somewhereDeepIn = fileSystem.getPath("/somewhere/deep/in");
- assertTrue(createDirectoryAndParents(somewhereDeepIn));
+ assertThat(createDirectoryAndParents(somewhereDeepIn)).isTrue();
Path realDir = fileSystem.getPath("/real/dir");
- assertTrue(createDirectoryAndParents(realDir));
+ assertThat(createDirectoryAndParents(realDir)).isTrue();
Path theHierarchy = somewhereDeepIn.getChild("the-hierarchy");
theHierarchy.createSymbolicLink(realDir);
- assertFalse(createDirectoryAndParents(theHierarchy));
+ assertThat(createDirectoryAndParents(theHierarchy)).isFalse();
}
@Test
public void testCreateDirectoriesWhenSymlinkEmbedded() throws IOException {
Path somewhereDeepIn = fileSystem.getPath("/somewhere/deep/in");
- assertTrue(createDirectoryAndParents(somewhereDeepIn));
+ assertThat(createDirectoryAndParents(somewhereDeepIn)).isTrue();
Path realDir = fileSystem.getPath("/real/dir");
- assertTrue(createDirectoryAndParents(realDir));
+ assertThat(createDirectoryAndParents(realDir)).isTrue();
Path the = somewhereDeepIn.getChild("the");
the.createSymbolicLink(realDir);
Path theHierarchy = somewhereDeepIn.getChild("hierarchy");
- assertTrue(createDirectoryAndParents(theHierarchy));
+ assertThat(createDirectoryAndParents(theHierarchy)).isTrue();
}
@@ -686,7 +679,7 @@ public class FileSystemUtilsTest {
FileSystemUtils.writeIsoLatin1(file, "Line 1", "Line 2", "Line 3");
String expected = "Line 1\nLine 2\nLine 3\n";
String actual = new String(FileSystemUtils.readContentAsLatin1(file));
- assertEquals(expected, actual);
+ assertThat(actual).isEqualTo(expected);
}
@Test
@@ -695,7 +688,7 @@ public class FileSystemUtilsTest {
FileSystemUtils.writeLinesAs(file, UTF_8, "\u00F6"); // an oe umlaut
byte[] expected = new byte[] {(byte) 0xC3, (byte) 0xB6, 0x0A};//"\u00F6\n";
byte[] actual = FileSystemUtils.readContent(file);
- assertArrayEquals(expected, actual);
+ assertThat(actual).isEqualTo(expected);
}
@Test
@@ -707,19 +700,19 @@ public class FileSystemUtilsTest {
byte[] content = new byte[] { 'a', 'b', 'c', 23, 42 };
FileSystemUtils.maybeUpdateContent(file, content);
byte[] actual = FileSystemUtils.readContent(file);
- assertArrayEquals(content, actual);
+ assertThat(actual).isEqualTo(content);
FileStatus stat = file.stat();
- assertEquals(1000, stat.getLastChangeTime());
- assertEquals(1000, stat.getLastModifiedTime());
+ assertThat(stat.getLastChangeTime()).isEqualTo(1000);
+ assertThat(stat.getLastModifiedTime()).isEqualTo(1000);
clock.advanceMillis(1000);
// Update with same contents; should not write anything.
FileSystemUtils.maybeUpdateContent(file, content);
- assertArrayEquals(content, actual);
+ assertThat(actual).isEqualTo(content);
stat = file.stat();
- assertEquals(1000, stat.getLastChangeTime());
- assertEquals(1000, stat.getLastModifiedTime());
+ assertThat(stat.getLastChangeTime()).isEqualTo(1000);
+ assertThat(stat.getLastModifiedTime()).isEqualTo(1000);
clock.advanceMillis(1000);
@@ -728,10 +721,10 @@ public class FileSystemUtilsTest {
file.chmod(0400); // Protect the file to ensure we can rewrite it.
FileSystemUtils.maybeUpdateContent(file, content);
actual = FileSystemUtils.readContent(file);
- assertArrayEquals(content, actual);
+ assertThat(actual).isEqualTo(content);
stat = file.stat();
- assertEquals(3000, stat.getLastChangeTime());
- assertEquals(3000, stat.getLastModifiedTime());
+ assertThat(stat.getLastChangeTime()).isEqualTo(3000);
+ assertThat(stat.getLastModifiedTime()).isEqualTo(3000);
}
@Test
@@ -748,67 +741,71 @@ public class FileSystemUtilsTest {
"proc proc proc rw,noexec,nosuid,nodev 0 0");
Path path = fileSystem.getPath("/usr/local/google/_blaze");
FileSystemUtils.createDirectoryAndParents(path);
- assertEquals("ext3", FileSystemUtils.getFileSystem(path));
+ assertThat(FileSystemUtils.getFileSystem(path)).isEqualTo("ext3");
// Should match the root "/"
path = fileSystem.getPath("/usr/local/tmp");
FileSystemUtils.createDirectoryAndParents(path);
- assertEquals("ext2", FileSystemUtils.getFileSystem(path));
+ assertThat(FileSystemUtils.getFileSystem(path)).isEqualTo("ext2");
// Make sure we don't consider /foobar matches /foo
path = fileSystem.getPath("/foo");
FileSystemUtils.createDirectoryAndParents(path);
- assertEquals("dummy_foo", FileSystemUtils.getFileSystem(path));
+ assertThat(FileSystemUtils.getFileSystem(path)).isEqualTo("dummy_foo");
path = fileSystem.getPath("/foobar");
FileSystemUtils.createDirectoryAndParents(path);
- assertEquals("dummy_foobar", FileSystemUtils.getFileSystem(path));
+ assertThat(FileSystemUtils.getFileSystem(path)).isEqualTo("dummy_foobar");
path = fileSystem.getPath("/dev/shm/blaze");
FileSystemUtils.createDirectoryAndParents(path);
- assertEquals("tmpfs", FileSystemUtils.getFileSystem(path));
+ assertThat(FileSystemUtils.getFileSystem(path)).isEqualTo("tmpfs");
Path fusePath = fileSystem.getPath("/fuse/mnt/tmp");
FileSystemUtils.createDirectoryAndParents(fusePath);
- assertEquals("fuse", FileSystemUtils.getFileSystem(fusePath));
+ assertThat(FileSystemUtils.getFileSystem(fusePath)).isEqualTo("fuse");
// Create a symlink and make sure it gives the file system of the symlink target.
path = fileSystem.getPath("/usr/local/google/_blaze/out");
path.createSymbolicLink(fusePath);
- assertEquals("fuse", FileSystemUtils.getFileSystem(path));
+ assertThat(FileSystemUtils.getFileSystem(path)).isEqualTo("fuse");
// Non existent path should return "unknown"
path = fileSystem.getPath("/does/not/exist");
- assertEquals("unknown", FileSystemUtils.getFileSystem(path));
+ assertThat(FileSystemUtils.getFileSystem(path)).isEqualTo("unknown");
}
@Test
public void testStartsWithAnySuccess() throws Exception {
PathFragment a = PathFragment.create("a");
- assertTrue(FileSystemUtils.startsWithAny(a,
- Arrays.asList(PathFragment.create("b"), PathFragment.create("a"))));
+ assertThat(
+ FileSystemUtils.startsWithAny(
+ a, Arrays.asList(PathFragment.create("b"), PathFragment.create("a"))))
+ .isTrue();
}
@Test
public void testStartsWithAnyNotFound() throws Exception {
PathFragment a = PathFragment.create("a");
- assertFalse(FileSystemUtils.startsWithAny(a,
- Arrays.asList(PathFragment.create("b"), PathFragment.create("c"))));
+ assertThat(
+ FileSystemUtils.startsWithAny(
+ a, Arrays.asList(PathFragment.create("b"), PathFragment.create("c"))))
+ .isFalse();
}
@Test
public void testIterateLines() throws Exception {
Path file = fileSystem.getPath("/test.txt");
FileSystemUtils.writeContent(file, ISO_8859_1, "a\nb");
- assertEquals(Arrays.asList("a", "b"),
- Lists.newArrayList(FileSystemUtils.iterateLinesAsLatin1(file)));
+ assertThat(Lists.newArrayList(FileSystemUtils.iterateLinesAsLatin1(file)))
+ .isEqualTo(Arrays.asList("a", "b"));
FileSystemUtils.writeContent(file, ISO_8859_1, "a\rb");
- assertEquals(Arrays.asList("a", "b"),
- Lists.newArrayList(FileSystemUtils.iterateLinesAsLatin1(file)));
+ assertThat(Lists.newArrayList(FileSystemUtils.iterateLinesAsLatin1(file)))
+ .isEqualTo(Arrays.asList("a", "b"));
FileSystemUtils.writeContent(file, ISO_8859_1, "a\r\nb");
- assertEquals(Arrays.asList("a", "b"),
- Lists.newArrayList(FileSystemUtils.iterateLinesAsLatin1(file)));
+ assertThat(Lists.newArrayList(FileSystemUtils.iterateLinesAsLatin1(file)))
+ .isEqualTo(Arrays.asList("a", "b"));
}
@Test
@@ -820,7 +817,7 @@ public class FileSystemUtilsTest {
clock.advanceMillis(1000);
FileSystemUtils.ensureSymbolicLink(file, target);
long timestamp = file.getLastModifiedTime(Symlinks.NOFOLLOW);
- assertEquals(prevTimeMillis, timestamp);
+ assertThat(timestamp).isEqualTo(prevTimeMillis);
}
@Test
@@ -831,11 +828,10 @@ public class FileSystemUtilsTest {
Path linkPath = workingDir.getRelative("link");
FileSystemUtils.createEmptyFile(originalPath);
FileSystemUtils.createHardLink(linkPath, originalPath);
- assertTrue(originalPath.exists());
- assertTrue(linkPath.exists());
- assertEquals(
- fileSystem.stat(originalPath, false).getNodeId(),
- fileSystem.stat(linkPath, false).getNodeId());
+ assertThat(originalPath.exists()).isTrue();
+ assertThat(linkPath.exists()).isTrue();
+ assertThat(fileSystem.stat(linkPath, false).getNodeId())
+ .isEqualTo(fileSystem.stat(originalPath, false).getNodeId());
}
@Test
@@ -848,7 +844,7 @@ public class FileSystemUtilsTest {
/* Original directory is empty, no link to be created. */
FileSystemUtils.createHardLink(linkPath, originalDir);
- assertFalse(linkPath.exists());
+ assertThat(linkPath.exists()).isFalse();
}
@Test
@@ -871,18 +867,15 @@ public class FileSystemUtilsTest {
/* Three link files created under linkPath */
FileSystemUtils.createHardLink(linkPath, originalDir);
- assertTrue(linkPath.exists());
- assertTrue(linkPath1.exists());
- assertTrue(linkPath2.exists());
- assertTrue(linkPath3.exists());
- assertEquals(
- fileSystem.stat(originalPath1, false).getNodeId(),
- fileSystem.stat(linkPath1, false).getNodeId());
- assertEquals(
- fileSystem.stat(originalPath2, false).getNodeId(),
- fileSystem.stat(linkPath2, false).getNodeId());
- assertEquals(
- fileSystem.stat(originalPath3, false).getNodeId(),
- fileSystem.stat(linkPath3, false).getNodeId());
+ assertThat(linkPath.exists()).isTrue();
+ assertThat(linkPath1.exists()).isTrue();
+ assertThat(linkPath2.exists()).isTrue();
+ assertThat(linkPath3.exists()).isTrue();
+ assertThat(fileSystem.stat(linkPath1, false).getNodeId())
+ .isEqualTo(fileSystem.stat(originalPath1, false).getNodeId());
+ assertThat(fileSystem.stat(linkPath2, false).getNodeId())
+ .isEqualTo(fileSystem.stat(originalPath2, false).getNodeId());
+ assertThat(fileSystem.stat(linkPath3, false).getNodeId())
+ .isEqualTo(fileSystem.stat(originalPath3, false).getNodeId());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/FileSystemsTest.java b/src/test/java/com/google/devtools/build/lib/vfs/FileSystemsTest.java
index 1e250a01ab..f52d9599aa 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/FileSystemsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/FileSystemsTest.java
@@ -13,11 +13,9 @@
// limitations under the License.
package com.google.devtools.build.lib.vfs;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.vfs.util.FileSystems;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -30,19 +28,16 @@ public class FileSystemsTest {
@Test
public void testFileSystemsCreatesOnlyOneDefaultNative() {
- assertSame(FileSystems.getNativeFileSystem(),
- FileSystems.getNativeFileSystem());
+ assertThat(FileSystems.getNativeFileSystem()).isSameAs(FileSystems.getNativeFileSystem());
}
@Test
public void testFileSystemsCreatesOnlyOneDefaultJavaIo() {
- assertSame(FileSystems.getJavaIoFileSystem(),
- FileSystems.getJavaIoFileSystem());
+ assertThat(FileSystems.getJavaIoFileSystem()).isSameAs(FileSystems.getJavaIoFileSystem());
}
@Test
public void testFileSystemsCanSwitchDefaults() {
- assertNotSame(FileSystems.getNativeFileSystem(),
- FileSystems.getJavaIoFileSystem());
+ assertThat(FileSystems.getJavaIoFileSystem()).isNotSameAs(FileSystems.getNativeFileSystem());
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/GlobTest.java b/src/test/java/com/google/devtools/build/lib/vfs/GlobTest.java
index c74e61d3b1..138ff7a94b 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/GlobTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/GlobTest.java
@@ -14,8 +14,6 @@
package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Predicate;
@@ -24,12 +22,6 @@ import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.devtools.build.lib.testutil.TestUtils;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
@@ -45,6 +37,10 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests {@link UnixGlob}
@@ -228,7 +224,7 @@ public class GlobTest {
.addPattern("foo/bar/wiz/file")
.setFilesystemCalls(new AtomicReference<>(syscalls))
.glob())
- .containsExactlyElementsIn(ImmutableList.of(tmpPath.getRelative("foo/bar/wiz/file")));
+ .containsExactly(tmpPath.getRelative("foo/bar/wiz/file"));
}
@Test
@@ -264,7 +260,7 @@ public class GlobTest {
@Test
public void testMatchesCallWithNoCache() {
- assertTrue(UnixGlob.matches("*a*b", "CaCb", null));
+ assertThat(UnixGlob.matches("*a*b", "CaCb", null)).isTrue();
}
@Test
@@ -276,11 +272,11 @@ public class GlobTest {
public void testMatcherMethodRecursiveBelowDir() throws Exception {
FileSystemUtils.createEmptyFile(tmpPath.getRelative("foo/file"));
String pattern = "foo/**/*";
- assertTrue(UnixGlob.matches(pattern, "foo/bar"));
- assertTrue(UnixGlob.matches(pattern, "foo/bar/baz"));
- assertFalse(UnixGlob.matches(pattern, "foo"));
- assertFalse(UnixGlob.matches(pattern, "foob"));
- assertTrue(UnixGlob.matches("**/foo", "foo"));
+ assertThat(UnixGlob.matches(pattern, "foo/bar")).isTrue();
+ assertThat(UnixGlob.matches(pattern, "foo/bar/baz")).isTrue();
+ assertThat(UnixGlob.matches(pattern, "foo")).isFalse();
+ assertThat(UnixGlob.matches(pattern, "foob")).isFalse();
+ assertThat(UnixGlob.matches("**/foo", "foo")).isTrue();
}
@Test
@@ -307,7 +303,7 @@ public class GlobTest {
.globInterruptible();
fail();
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).containsMatch("in glob pattern");
+ assertThat(e).hasMessageThat().containsMatch("in glob pattern");
}
}
@@ -370,9 +366,10 @@ public class GlobTest {
}
Thread.interrupted();
- assertFalse(executor.isShutdown());
+ assertThat(executor.isShutdown()).isFalse();
executor.shutdown();
- assertTrue(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
+ .isTrue();
}
@Test
@@ -397,7 +394,7 @@ public class GlobTest {
// In the non-interruptible case, the interrupt bit should be set, but the
// glob should return the correct set of full results.
- assertTrue(Thread.interrupted());
+ assertThat(Thread.interrupted()).isTrue();
assertThat(result)
.containsExactlyElementsIn(
resolvePaths(
@@ -415,8 +412,9 @@ public class GlobTest {
"fool/barnacle",
"fool/barnacle/wiz"));
- assertFalse(executor.isShutdown());
+ assertThat(executor.isShutdown()).isFalse();
executor.shutdown();
- assertTrue(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
+ .isTrue();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/JavaIoFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/vfs/JavaIoFileSystemTest.java
index 75bbe93571..80c1981fcd 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/JavaIoFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/JavaIoFileSystemTest.java
@@ -13,7 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.vfs;
-import static org.junit.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.testutil.ManualClock;
import java.io.IOException;
@@ -54,13 +54,13 @@ public class JavaIoFileSystemTest extends SymlinkAwareFileSystemTest {
FileSystemUtils.createEmptyFile(file);
file.setLastModifiedTime(1000L);
- assertEquals(1000L, file.getLastModifiedTime());
+ assertThat(file.getLastModifiedTime()).isEqualTo(1000L);
file.setLastModifiedTime(0L);
- assertEquals(0L, file.getLastModifiedTime());
+ assertThat(file.getLastModifiedTime()).isEqualTo(0L);
clock.advanceMillis(42000L);
file.setLastModifiedTime(-1L);
- assertEquals(42000L, file.getLastModifiedTime());
+ assertThat(file.getLastModifiedTime()).isEqualTo(42000L);
}
@Override
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/NativePathTest.java b/src/test/java/com/google/devtools/build/lib/vfs/NativePathTest.java
index 15a18428b5..6d112853fd 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/NativePathTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/NativePathTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.Lists;
@@ -31,7 +27,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
-import java.util.HashSet;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
@@ -67,21 +62,17 @@ public class NativePathTest {
@Test
public void testExists() {
- assertTrue(fs.getPath(aDirectory.getPath()).exists());
- assertTrue(fs.getPath(aFile.getPath()).exists());
- assertFalse(fs.getPath("/does/not/exist").exists());
+ assertThat(fs.getPath(aDirectory.getPath()).exists()).isTrue();
+ assertThat(fs.getPath(aFile.getPath()).exists()).isTrue();
+ assertThat(fs.getPath("/does/not/exist").exists()).isFalse();
}
@Test
public void testDirectoryEntriesForDirectory() throws IOException {
- Collection<Path> entries =
- fs.getPath(tmpDir.getPath()).getDirectoryEntries();
- List<Path> expectedEntries = Arrays.asList(
+ assertThat(fs.getPath(tmpDir.getPath()).getDirectoryEntries()).containsExactly(
fs.getPath(tmpDir.getPath() + "/a_file"),
fs.getPath(tmpDir.getPath() + "/a_directory"));
- assertEquals(new HashSet<Object>(expectedEntries),
- new HashSet<Object>(entries));
}
@Test
@@ -96,36 +87,36 @@ public class NativePathTest {
@Test
public void testIsFileIsTrueForFile() {
- assertTrue(fs.getPath(aFile.getPath()).isFile());
+ assertThat(fs.getPath(aFile.getPath()).isFile()).isTrue();
}
@Test
public void testIsFileIsFalseForDirectory() {
- assertFalse(fs.getPath(aDirectory.getPath()).isFile());
+ assertThat(fs.getPath(aDirectory.getPath()).isFile()).isFalse();
}
@Test
public void testBaseName() {
- assertEquals("base", fs.getPath("/foo/base").getBaseName());
+ assertThat(fs.getPath("/foo/base").getBaseName()).isEqualTo("base");
}
@Test
public void testBaseNameRunsAfterDotDotInterpretation() {
- assertEquals("base", fs.getPath("/base/foo/..").getBaseName());
+ assertThat(fs.getPath("/base/foo/..").getBaseName()).isEqualTo("base");
}
@Test
public void testParentOfRootIsRoot() {
- assertEquals(fs.getPath("/"), fs.getPath("/.."));
- assertEquals(fs.getPath("/"), fs.getPath("/../../../../../.."));
- assertEquals(fs.getPath("/foo"), fs.getPath("/../../../foo"));
+ assertThat(fs.getPath("/..")).isEqualTo(fs.getPath("/"));
+ assertThat(fs.getPath("/../../../../../..")).isEqualTo(fs.getPath("/"));
+ assertThat(fs.getPath("/../../../foo")).isEqualTo(fs.getPath("/foo"));
}
@Test
public void testIsDirectory() {
- assertTrue(fs.getPath(aDirectory.getPath()).isDirectory());
- assertFalse(fs.getPath(aFile.getPath()).isDirectory());
- assertFalse(fs.getPath("/does/not/exist").isDirectory());
+ assertThat(fs.getPath(aDirectory.getPath()).isDirectory()).isTrue();
+ assertThat(fs.getPath(aFile.getPath()).isDirectory()).isFalse();
+ assertThat(fs.getPath("/does/not/exist").isDirectory()).isFalse();
}
@Test
@@ -155,7 +146,7 @@ public class NativePathTest {
.globInterruptible();
assertThat(textFiles).hasSize(1);
Path onlyFile = textFiles.iterator().next();
- assertEquals(fs.getPath(anotherFile.getPath()), onlyFile);
+ assertThat(onlyFile).isEqualTo(fs.getPath(anotherFile.getPath()));
Collection<Path> onlyFiles =
UnixGlob.forPath(fs.getPath(tmpDir.getPath()))
@@ -176,7 +167,7 @@ public class NativePathTest {
public void testGetRelative() {
Path relative = fs.getPath("/foo").getChild("bar");
Path expected = fs.getPath("/foo/bar");
- assertEquals(expected, relative);
+ assertThat(relative).isEqualTo(expected);
}
@Test
@@ -187,8 +178,8 @@ public class NativePathTest {
Object differentType = new Object();
new EqualsTester().addEqualityGroup(path, equalPath).testEquals();
- assertFalse(path.equals(differentPath));
- assertFalse(path.equals(differentType));
+ assertThat(path.equals(differentPath)).isFalse();
+ assertThat(path.equals(differentType)).isFalse();
}
@Test
@@ -201,7 +192,7 @@ public class NativePathTest {
String latin1String = new String(allLatin1Chars);
FileSystemUtils.writeContentAsLatin1(path, latin1String);
String fileContent = new String(FileSystemUtils.readContentAsLatin1(path));
- assertEquals(fileContent, latin1String);
+ assertThat(latin1String).isEqualTo(fileContent);
}
/**
@@ -219,7 +210,7 @@ public class NativePathTest {
String latin1String = new String(allLatin1Chars);
FileSystemUtils.writeContentAsLatin1(path, latin1String);
byte[] bytes = FileSystemUtils.readContent(path);
- assertEquals(new String(bytes, "ISO-8859-1"), latin1String);
+ assertThat(latin1String).isEqualTo(new String(bytes, "ISO-8859-1"));
}
@Test
@@ -229,9 +220,9 @@ public class NativePathTest {
Path path = fs.getPath(aFile.getPath());
FileSystemUtils.writeContent(path, bytes);
byte[] content = FileSystemUtils.readContent(path);
- assertEquals(bytes.length, content.length);
+ assertThat(content).hasLength(bytes.length);
for (int i = 0; i < bytes.length; i++) {
- assertEquals(bytes[i], content[i]);
+ assertThat(content[i]).isEqualTo(bytes[i]);
}
}
@@ -245,9 +236,9 @@ public class NativePathTest {
out.close();
InputStream in = path.getInputStream();
for (int i = 0; i < 256; i++) {
- assertEquals(i, in.read());
+ assertThat(in.read()).isEqualTo(i);
}
- assertEquals(-1, in.read());
+ assertThat(in.read()).isEqualTo(-1);
in.close();
}
@@ -258,6 +249,6 @@ public class NativePathTest {
Path derivedNode = absoluteSegment.getChild("derivedSegment");
Path otherDerivedNode = absoluteSegment.getChild("derivedSegment");
- assertSame(derivedNode, otherDerivedNode);
+ assertThat(otherDerivedNode).isSameAs(derivedNode);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/PathFragmentTest.java b/src/test/java/com/google/devtools/build/lib/vfs/PathFragmentTest.java
index 4b84903601..bce569f887 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/PathFragmentTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/PathFragmentTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -40,13 +36,13 @@ import org.junit.runners.JUnit4;
public class PathFragmentTest {
@Test
public void testMergeFourPathsWithAbsolute() {
- assertEquals(
- PathFragment.create("x/y/z/a/b/c/d/e"),
- PathFragment.create(
- PathFragment.create("x/y"),
- PathFragment.create("z/a"),
- PathFragment.create("/b/c"),
- PathFragment.create("d/e")));
+ assertThat(
+ PathFragment.create(
+ PathFragment.create("x/y"),
+ PathFragment.create("z/a"),
+ PathFragment.create("/b/c"),
+ PathFragment.create("d/e")))
+ .isEqualTo(PathFragment.create("x/y/z/a/b/c/d/e"));
}
@Test
@@ -91,15 +87,14 @@ public class PathFragmentTest {
int oldResult = relativePath.hashCode();
int rootResult = rootPath.hashCode();
- assertEquals(oldResult, relativePath.hashCode());
- assertEquals(rootResult, rootPath.hashCode());
+ assertThat(relativePath.hashCode()).isEqualTo(oldResult);
+ assertThat(rootPath.hashCode()).isEqualTo(rootResult);
}
private void checkRelativeTo(String path, String base) {
PathFragment relative = PathFragment.create(path).relativeTo(base);
- assertEquals(
- PathFragment.create(path),
- PathFragment.create(base).getRelative(relative).normalize());
+ assertThat(PathFragment.create(base).getRelative(relative).normalize())
+ .isEqualTo(PathFragment.create(path));
}
@Test
@@ -123,49 +118,48 @@ public class PathFragmentTest {
@Test
public void testIsAbsolute() {
- assertTrue(PathFragment.create("/absolute/test").isAbsolute());
- assertFalse(PathFragment.create("relative/test").isAbsolute());
- assertTrue(PathFragment.create(new File("/absolute/test")).isAbsolute());
- assertFalse(PathFragment.create(new File("relative/test")).isAbsolute());
+ assertThat(PathFragment.create("/absolute/test").isAbsolute()).isTrue();
+ assertThat(PathFragment.create("relative/test").isAbsolute()).isFalse();
+ assertThat(PathFragment.create(new File("/absolute/test")).isAbsolute()).isTrue();
+ assertThat(PathFragment.create(new File("relative/test")).isAbsolute()).isFalse();
}
@Test
public void testIsNormalized() {
- assertTrue(PathFragment.create("/absolute/path").isNormalized());
- assertTrue(PathFragment.create("some//path").isNormalized());
- assertFalse(PathFragment.create("some/./path").isNormalized());
- assertFalse(PathFragment.create("../some/path").isNormalized());
- assertFalse(PathFragment.create("some/other/../path").isNormalized());
- assertTrue(PathFragment.create("some/other//tricky..path..").isNormalized());
- assertTrue(PathFragment.create("/some/other//tricky..path..").isNormalized());
+ assertThat(PathFragment.create("/absolute/path").isNormalized()).isTrue();
+ assertThat(PathFragment.create("some//path").isNormalized()).isTrue();
+ assertThat(PathFragment.create("some/./path").isNormalized()).isFalse();
+ assertThat(PathFragment.create("../some/path").isNormalized()).isFalse();
+ assertThat(PathFragment.create("some/other/../path").isNormalized()).isFalse();
+ assertThat(PathFragment.create("some/other//tricky..path..").isNormalized()).isTrue();
+ assertThat(PathFragment.create("/some/other//tricky..path..").isNormalized()).isTrue();
}
@Test
public void testRootNodeReturnsRootString() {
PathFragment rootFragment = PathFragment.create("/");
- assertEquals("/", rootFragment.getPathString());
+ assertThat(rootFragment.getPathString()).isEqualTo("/");
}
@Test
public void testGetPathFragmentDoesNotNormalize() {
String nonCanonicalPath = "/a/weird/noncanonical/../path/.";
- assertEquals(nonCanonicalPath,
- PathFragment.create(nonCanonicalPath).getPathString());
+ assertThat(PathFragment.create(nonCanonicalPath).getPathString()).isEqualTo(nonCanonicalPath);
}
@Test
public void testGetRelative() {
- assertEquals("a/b", PathFragment.create("a").getRelative("b").getPathString());
- assertEquals("a/b/c/d", PathFragment.create("a/b").getRelative("c/d").getPathString());
- assertEquals("/a/b", PathFragment.create("c/d").getRelative("/a/b").getPathString());
- assertEquals("a", PathFragment.create("a").getRelative("").getPathString());
- assertEquals("/", PathFragment.create("/").getRelative("").getPathString());
+ assertThat(PathFragment.create("a").getRelative("b").getPathString()).isEqualTo("a/b");
+ assertThat(PathFragment.create("a/b").getRelative("c/d").getPathString()).isEqualTo("a/b/c/d");
+ assertThat(PathFragment.create("c/d").getRelative("/a/b").getPathString()).isEqualTo("/a/b");
+ assertThat(PathFragment.create("a").getRelative("").getPathString()).isEqualTo("a");
+ assertThat(PathFragment.create("/").getRelative("").getPathString()).isEqualTo("/");
}
@Test
public void testGetChildWorks() {
PathFragment pf = PathFragment.create("../some/path");
- assertEquals(PathFragment.create("../some/path/hi"), pf.getChild("hi"));
+ assertThat(pf.getChild("hi")).isEqualTo(PathFragment.create("../some/path/hi"));
}
@Test
@@ -189,13 +183,9 @@ public class PathFragmentTest {
// Tests after here test the canonicalization
private void assertRegular(String expected, String actual) {
// compare string forms
- assertEquals(
- expected,
- PathFragment.create(actual).getPathString());
+ assertThat(PathFragment.create(actual).getPathString()).isEqualTo(expected);
// compare fragment forms
- assertEquals(
- PathFragment.create(expected),
- PathFragment.create(actual));
+ assertThat(PathFragment.create(actual)).isEqualTo(PathFragment.create(expected));
}
@Test
@@ -234,60 +224,59 @@ public class PathFragmentTest {
PathFragment fooBar = PathFragment.create("foo/bar");
PathFragment foo = PathFragment.create("foo");
PathFragment empty = PathFragment.create("");
- assertEquals(fooBar, fooBarWiz.getParentDirectory());
- assertEquals(foo, fooBar.getParentDirectory());
- assertEquals(empty, foo.getParentDirectory());
- assertNull(empty.getParentDirectory());
+ assertThat(fooBarWiz.getParentDirectory()).isEqualTo(fooBar);
+ assertThat(fooBar.getParentDirectory()).isEqualTo(foo);
+ assertThat(foo.getParentDirectory()).isEqualTo(empty);
+ assertThat(empty.getParentDirectory()).isNull();
PathFragment fooBarWizAbs = PathFragment.create("/foo/bar/wiz");
PathFragment fooBarAbs = PathFragment.create("/foo/bar");
PathFragment fooAbs = PathFragment.create("/foo");
PathFragment rootAbs = PathFragment.create("/");
- assertEquals(fooBarAbs, fooBarWizAbs.getParentDirectory());
- assertEquals(fooAbs, fooBarAbs.getParentDirectory());
- assertEquals(rootAbs, fooAbs.getParentDirectory());
- assertNull(rootAbs.getParentDirectory());
+ assertThat(fooBarWizAbs.getParentDirectory()).isEqualTo(fooBarAbs);
+ assertThat(fooBarAbs.getParentDirectory()).isEqualTo(fooAbs);
+ assertThat(fooAbs.getParentDirectory()).isEqualTo(rootAbs);
+ assertThat(rootAbs.getParentDirectory()).isNull();
// Note, this is surprising but correct behavior:
- assertEquals(fooBarAbs,
- PathFragment.create("/foo/bar/..").getParentDirectory());
+ assertThat(PathFragment.create("/foo/bar/..").getParentDirectory()).isEqualTo(fooBarAbs);
}
@Test
public void testSegmentsCount() {
- assertEquals(2, PathFragment.create("foo/bar").segmentCount());
- assertEquals(2, PathFragment.create("/foo/bar").segmentCount());
- assertEquals(2, PathFragment.create("foo//bar").segmentCount());
- assertEquals(2, PathFragment.create("/foo//bar").segmentCount());
- assertEquals(1, PathFragment.create("foo/").segmentCount());
- assertEquals(1, PathFragment.create("/foo/").segmentCount());
- assertEquals(1, PathFragment.create("foo").segmentCount());
- assertEquals(1, PathFragment.create("/foo").segmentCount());
- assertEquals(0, PathFragment.create("/").segmentCount());
- assertEquals(0, PathFragment.create("").segmentCount());
+ assertThat(PathFragment.create("foo/bar").segmentCount()).isEqualTo(2);
+ assertThat(PathFragment.create("/foo/bar").segmentCount()).isEqualTo(2);
+ assertThat(PathFragment.create("foo//bar").segmentCount()).isEqualTo(2);
+ assertThat(PathFragment.create("/foo//bar").segmentCount()).isEqualTo(2);
+ assertThat(PathFragment.create("foo/").segmentCount()).isEqualTo(1);
+ assertThat(PathFragment.create("/foo/").segmentCount()).isEqualTo(1);
+ assertThat(PathFragment.create("foo").segmentCount()).isEqualTo(1);
+ assertThat(PathFragment.create("/foo").segmentCount()).isEqualTo(1);
+ assertThat(PathFragment.create("/").segmentCount()).isEqualTo(0);
+ assertThat(PathFragment.create("").segmentCount()).isEqualTo(0);
}
@Test
public void testGetSegment() {
- assertEquals("foo", PathFragment.create("foo/bar").getSegment(0));
- assertEquals("bar", PathFragment.create("foo/bar").getSegment(1));
- assertEquals("foo", PathFragment.create("/foo/bar").getSegment(0));
- assertEquals("bar", PathFragment.create("/foo/bar").getSegment(1));
- assertEquals("foo", PathFragment.create("foo/").getSegment(0));
- assertEquals("foo", PathFragment.create("/foo/").getSegment(0));
- assertEquals("foo", PathFragment.create("foo").getSegment(0));
- assertEquals("foo", PathFragment.create("/foo").getSegment(0));
+ assertThat(PathFragment.create("foo/bar").getSegment(0)).isEqualTo("foo");
+ assertThat(PathFragment.create("foo/bar").getSegment(1)).isEqualTo("bar");
+ assertThat(PathFragment.create("/foo/bar").getSegment(0)).isEqualTo("foo");
+ assertThat(PathFragment.create("/foo/bar").getSegment(1)).isEqualTo("bar");
+ assertThat(PathFragment.create("foo/").getSegment(0)).isEqualTo("foo");
+ assertThat(PathFragment.create("/foo/").getSegment(0)).isEqualTo("foo");
+ assertThat(PathFragment.create("foo").getSegment(0)).isEqualTo("foo");
+ assertThat(PathFragment.create("/foo").getSegment(0)).isEqualTo("foo");
}
@Test
public void testBasename() throws Exception {
- assertEquals("bar", PathFragment.create("foo/bar").getBaseName());
- assertEquals("bar", PathFragment.create("/foo/bar").getBaseName());
- assertEquals("foo", PathFragment.create("foo/").getBaseName());
- assertEquals("foo", PathFragment.create("/foo/").getBaseName());
- assertEquals("foo", PathFragment.create("foo").getBaseName());
- assertEquals("foo", PathFragment.create("/foo").getBaseName());
+ assertThat(PathFragment.create("foo/bar").getBaseName()).isEqualTo("bar");
+ assertThat(PathFragment.create("/foo/bar").getBaseName()).isEqualTo("bar");
+ assertThat(PathFragment.create("foo/").getBaseName()).isEqualTo("foo");
+ assertThat(PathFragment.create("/foo/").getBaseName()).isEqualTo("foo");
+ assertThat(PathFragment.create("foo").getBaseName()).isEqualTo("foo");
+ assertThat(PathFragment.create("/foo").getBaseName()).isEqualTo("foo");
assertThat(PathFragment.create("/").getBaseName()).isEmpty();
assertThat(PathFragment.create("").getBaseName()).isEmpty();
}
@@ -307,7 +296,7 @@ public class PathFragmentTest {
}
private static void assertPath(String expected, PathFragment actual) {
- assertEquals(expected, actual.getPathString());
+ assertThat(actual.getPathString()).isEqualTo(expected);
}
@Test
@@ -319,10 +308,10 @@ public class PathFragmentTest {
assertPath("/baz", PathFragment.create("/foo/").replaceName("baz"));
assertPath("baz", PathFragment.create("foo").replaceName("baz"));
assertPath("/baz", PathFragment.create("/foo").replaceName("baz"));
- assertNull(PathFragment.create("/").replaceName("baz"));
- assertNull(PathFragment.create("/").replaceName(""));
- assertNull(PathFragment.create("").replaceName("baz"));
- assertNull(PathFragment.create("").replaceName(""));
+ assertThat(PathFragment.create("/").replaceName("baz")).isNull();
+ assertThat(PathFragment.create("/").replaceName("")).isNull();
+ assertThat(PathFragment.create("").replaceName("baz")).isNull();
+ assertThat(PathFragment.create("").replaceName("")).isNull();
assertPath("foo/bar/baz", PathFragment.create("foo/bar").replaceName("bar/baz"));
assertPath("foo/bar/baz", PathFragment.create("foo/bar").replaceName("bar/baz/"));
@@ -363,36 +352,37 @@ public class PathFragmentTest {
PathFragment foobarRelative = PathFragment.create("foo/bar");
// (path, prefix) => true
- assertTrue(foobar.startsWith(foobar));
- assertTrue(foobar.startsWith(PathFragment.create("/")));
- assertTrue(foobar.startsWith(PathFragment.create("/foo")));
- assertTrue(foobar.startsWith(PathFragment.create("/foo/")));
- assertTrue(foobar.startsWith(PathFragment.create("/foo/bar/"))); // Includes trailing slash.
+ assertThat(foobar.startsWith(foobar)).isTrue();
+ assertThat(foobar.startsWith(PathFragment.create("/"))).isTrue();
+ assertThat(foobar.startsWith(PathFragment.create("/foo"))).isTrue();
+ assertThat(foobar.startsWith(PathFragment.create("/foo/"))).isTrue();
+ assertThat(foobar.startsWith(PathFragment.create("/foo/bar/")))
+ .isTrue(); // Includes trailing slash.
// (prefix, path) => false
- assertFalse(PathFragment.create("/foo").startsWith(foobar));
- assertFalse(PathFragment.create("/").startsWith(foobar));
+ assertThat(PathFragment.create("/foo").startsWith(foobar)).isFalse();
+ assertThat(PathFragment.create("/").startsWith(foobar)).isFalse();
// (absolute, relative) => false
- assertFalse(foobar.startsWith(foobarRelative));
- assertFalse(foobarRelative.startsWith(foobar));
+ assertThat(foobar.startsWith(foobarRelative)).isFalse();
+ assertThat(foobarRelative.startsWith(foobar)).isFalse();
// (relative path, relative prefix) => true
- assertTrue(foobarRelative.startsWith(foobarRelative));
- assertTrue(foobarRelative.startsWith(PathFragment.create("foo")));
- assertTrue(foobarRelative.startsWith(PathFragment.create("")));
+ assertThat(foobarRelative.startsWith(foobarRelative)).isTrue();
+ assertThat(foobarRelative.startsWith(PathFragment.create("foo"))).isTrue();
+ assertThat(foobarRelative.startsWith(PathFragment.create(""))).isTrue();
// (path, sibling) => false
- assertFalse(PathFragment.create("/foo/wiz").startsWith(foobar));
- assertFalse(foobar.startsWith(PathFragment.create("/foo/wiz")));
+ assertThat(PathFragment.create("/foo/wiz").startsWith(foobar)).isFalse();
+ assertThat(foobar.startsWith(PathFragment.create("/foo/wiz"))).isFalse();
// Does not normalize.
PathFragment foodotbar = PathFragment.create("foo/./bar");
- assertTrue(foodotbar.startsWith(foodotbar));
- assertTrue(foodotbar.startsWith(PathFragment.create("foo/.")));
- assertTrue(foodotbar.startsWith(PathFragment.create("foo/./")));
- assertTrue(foodotbar.startsWith(PathFragment.create("foo/./bar")));
- assertFalse(foodotbar.startsWith(PathFragment.create("foo/bar")));
+ assertThat(foodotbar.startsWith(foodotbar)).isTrue();
+ assertThat(foodotbar.startsWith(PathFragment.create("foo/."))).isTrue();
+ assertThat(foodotbar.startsWith(PathFragment.create("foo/./"))).isTrue();
+ assertThat(foodotbar.startsWith(PathFragment.create("foo/./bar"))).isTrue();
+ assertThat(foodotbar.startsWith(PathFragment.create("foo/bar"))).isFalse();
}
@Test
@@ -456,35 +446,35 @@ public class PathFragmentTest {
PathFragment foobarRelative = PathFragment.create("foo/bar");
// (path, suffix) => true
- assertTrue(foobar.endsWith(foobar));
- assertTrue(foobar.endsWith(PathFragment.create("bar")));
- assertTrue(foobar.endsWith(PathFragment.create("foo/bar")));
- assertTrue(foobar.endsWith(PathFragment.create("/foo/bar")));
- assertFalse(foobar.endsWith(PathFragment.create("/bar")));
+ assertThat(foobar.endsWith(foobar)).isTrue();
+ assertThat(foobar.endsWith(PathFragment.create("bar"))).isTrue();
+ assertThat(foobar.endsWith(PathFragment.create("foo/bar"))).isTrue();
+ assertThat(foobar.endsWith(PathFragment.create("/foo/bar"))).isTrue();
+ assertThat(foobar.endsWith(PathFragment.create("/bar"))).isFalse();
// (prefix, path) => false
- assertFalse(PathFragment.create("/foo").endsWith(foobar));
- assertFalse(PathFragment.create("/").endsWith(foobar));
+ assertThat(PathFragment.create("/foo").endsWith(foobar)).isFalse();
+ assertThat(PathFragment.create("/").endsWith(foobar)).isFalse();
// (suffix, path) => false
- assertFalse(PathFragment.create("/bar").endsWith(foobar));
- assertFalse(PathFragment.create("bar").endsWith(foobar));
- assertFalse(PathFragment.create("").endsWith(foobar));
+ assertThat(PathFragment.create("/bar").endsWith(foobar)).isFalse();
+ assertThat(PathFragment.create("bar").endsWith(foobar)).isFalse();
+ assertThat(PathFragment.create("").endsWith(foobar)).isFalse();
// (absolute, relative) => true
- assertTrue(foobar.endsWith(foobarRelative));
+ assertThat(foobar.endsWith(foobarRelative)).isTrue();
// (relative, absolute) => false
- assertFalse(foobarRelative.endsWith(foobar));
+ assertThat(foobarRelative.endsWith(foobar)).isFalse();
// (relative path, relative prefix) => true
- assertTrue(foobarRelative.endsWith(foobarRelative));
- assertTrue(foobarRelative.endsWith(PathFragment.create("bar")));
- assertTrue(foobarRelative.endsWith(PathFragment.create("")));
+ assertThat(foobarRelative.endsWith(foobarRelative)).isTrue();
+ assertThat(foobarRelative.endsWith(PathFragment.create("bar"))).isTrue();
+ assertThat(foobarRelative.endsWith(PathFragment.create(""))).isTrue();
// (path, sibling) => false
- assertFalse(PathFragment.create("/foo/wiz").endsWith(foobar));
- assertFalse(foobar.endsWith(PathFragment.create("/foo/wiz")));
+ assertThat(PathFragment.create("/foo/wiz").endsWith(foobar)).isFalse();
+ assertThat(foobar.endsWith(PathFragment.create("/foo/wiz"))).isFalse();
}
static List<PathFragment> toPaths(List<String> strs) {
@@ -513,18 +503,17 @@ public class PathFragmentTest {
for (PathFragment y : paths) {
for (PathFragment z : paths) {
// Anti-symmetry
- assertEquals(Integer.signum(x.compareTo(y)),
- -1 * Integer.signum(y.compareTo(x)));
+ assertThat(-1 * Integer.signum(y.compareTo(x))).isEqualTo(Integer.signum(x.compareTo(y)));
// Transitivity
if (x.compareTo(y) > 0 && y.compareTo(z) > 0) {
assertThat(x.compareTo(z)).isGreaterThan(0);
}
// "Substitutability"
if (x.compareTo(y) == 0) {
- assertEquals(Integer.signum(x.compareTo(z)), Integer.signum(y.compareTo(z)));
+ assertThat(Integer.signum(y.compareTo(z))).isEqualTo(Integer.signum(x.compareTo(z)));
}
// Consistency with equals
- assertEquals((x.compareTo(y) == 0), x.equals(y));
+ assertThat(x.equals(y)).isEqualTo((x.compareTo(y) == 0));
}
}
}
@@ -535,29 +524,29 @@ public class PathFragmentTest {
Collections.sort(paths);
List<PathFragment> expectedOrder = toPaths(ImmutableList.of(
"/", "//", "/./", "/foo", "", ".", "Foo/bar", "foo", "foo/.//bar", "foo/Bar", "foo/bar"));
- assertEquals(expectedOrder, paths);
+ assertThat(paths).isEqualTo(expectedOrder);
}
@Test
public void testGetSafePathString() {
- assertEquals("/", PathFragment.create("/").getSafePathString());
- assertEquals("/abc", PathFragment.create("/abc").getSafePathString());
- assertEquals(".", PathFragment.create("").getSafePathString());
- assertEquals(".", PathFragment.EMPTY_FRAGMENT.getSafePathString());
- assertEquals("abc/def", PathFragment.create("abc/def").getSafePathString());
+ assertThat(PathFragment.create("/").getSafePathString()).isEqualTo("/");
+ assertThat(PathFragment.create("/abc").getSafePathString()).isEqualTo("/abc");
+ assertThat(PathFragment.create("").getSafePathString()).isEqualTo(".");
+ assertThat(PathFragment.EMPTY_FRAGMENT.getSafePathString()).isEqualTo(".");
+ assertThat(PathFragment.create("abc/def").getSafePathString()).isEqualTo("abc/def");
}
@Test
public void testNormalize() {
- assertEquals(PathFragment.create("/a/b"), PathFragment.create("/a/b").normalize());
- assertEquals(PathFragment.create("/a/b"), PathFragment.create("/a/./b").normalize());
- assertEquals(PathFragment.create("/b"), PathFragment.create("/a/../b").normalize());
- assertEquals(PathFragment.create("a/b"), PathFragment.create("a/b").normalize());
- assertEquals(PathFragment.create("../b"), PathFragment.create("a/../../b").normalize());
- assertEquals(PathFragment.create(".."), PathFragment.create("a/../..").normalize());
- assertEquals(PathFragment.create("b"), PathFragment.create("a/../b").normalize());
- assertEquals(PathFragment.create("a/b"), PathFragment.create("a/b/../b").normalize());
- assertEquals(PathFragment.create("/.."), PathFragment.create("/..").normalize());
+ assertThat(PathFragment.create("/a/b").normalize()).isEqualTo(PathFragment.create("/a/b"));
+ assertThat(PathFragment.create("/a/./b").normalize()).isEqualTo(PathFragment.create("/a/b"));
+ assertThat(PathFragment.create("/a/../b").normalize()).isEqualTo(PathFragment.create("/b"));
+ assertThat(PathFragment.create("a/b").normalize()).isEqualTo(PathFragment.create("a/b"));
+ assertThat(PathFragment.create("a/../../b").normalize()).isEqualTo(PathFragment.create("../b"));
+ assertThat(PathFragment.create("a/../..").normalize()).isEqualTo(PathFragment.create(".."));
+ assertThat(PathFragment.create("a/../b").normalize()).isEqualTo(PathFragment.create("b"));
+ assertThat(PathFragment.create("a/b/../b").normalize()).isEqualTo(PathFragment.create("a/b"));
+ assertThat(PathFragment.create("/..").normalize()).isEqualTo(PathFragment.create("/.."));
}
@Test
@@ -578,9 +567,9 @@ public class PathFragmentTest {
private void checkSerialization(String pathFragmentString, int expectedSize) throws Exception {
PathFragment a = PathFragment.create(pathFragmentString);
byte[] sa = TestUtils.serializeObject(a);
- assertEquals(expectedSize, sa.length);
+ assertThat(sa).hasLength(expectedSize);
PathFragment a2 = (PathFragment) TestUtils.deserializeObject(sa);
- assertEquals(a, a2);
+ assertThat(a2).isEqualTo(a);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/PathFragmentWindowsTest.java b/src/test/java/com/google/devtools/build/lib/vfs/PathFragmentWindowsTest.java
index 90cc615836..d75c1bd2c9 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/PathFragmentWindowsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/PathFragmentWindowsTest.java
@@ -15,10 +15,6 @@ package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Assert;
@@ -34,22 +30,22 @@ public class PathFragmentWindowsTest {
@Test
public void testWindowsSeparator() {
- assertEquals("bar/baz", PathFragment.create("bar\\baz").toString());
- assertEquals("C:/bar/baz", PathFragment.create("c:\\bar\\baz").toString());
+ assertThat(PathFragment.create("bar\\baz").toString()).isEqualTo("bar/baz");
+ assertThat(PathFragment.create("c:\\bar\\baz").toString()).isEqualTo("C:/bar/baz");
}
@Test
public void testIsAbsoluteWindows() {
- assertTrue(PathFragment.create("C:/").isAbsolute());
- assertTrue(PathFragment.create("C:/").isAbsolute());
- assertTrue(PathFragment.create("C:/foo").isAbsolute());
- assertTrue(PathFragment.create("d:/foo/bar").isAbsolute());
+ assertThat(PathFragment.create("C:/").isAbsolute()).isTrue();
+ assertThat(PathFragment.create("C:/").isAbsolute()).isTrue();
+ assertThat(PathFragment.create("C:/foo").isAbsolute()).isTrue();
+ assertThat(PathFragment.create("d:/foo/bar").isAbsolute()).isTrue();
- assertFalse(PathFragment.create("*:/").isAbsolute());
+ assertThat(PathFragment.create("*:/").isAbsolute()).isFalse();
// C: is not an absolute path, it points to the current active directory on drive C:.
- assertFalse(PathFragment.create("C:").isAbsolute());
- assertFalse(PathFragment.create("C:foo").isAbsolute());
+ assertThat(PathFragment.create("C:").isAbsolute()).isFalse();
+ assertThat(PathFragment.create("C:foo").isAbsolute()).isFalse();
}
@Test
@@ -90,34 +86,37 @@ public class PathFragmentWindowsTest {
@Test
public void testIsAbsoluteWindowsBackslash() {
- assertTrue(PathFragment.create(new File("C:\\blah")).isAbsolute());
- assertTrue(PathFragment.create(new File("C:\\")).isAbsolute());
- assertTrue(PathFragment.create(new File("\\blah")).isAbsolute());
- assertTrue(PathFragment.create(new File("\\")).isAbsolute());
+ assertThat(PathFragment.create(new File("C:\\blah")).isAbsolute()).isTrue();
+ assertThat(PathFragment.create(new File("C:\\")).isAbsolute()).isTrue();
+ assertThat(PathFragment.create(new File("\\blah")).isAbsolute()).isTrue();
+ assertThat(PathFragment.create(new File("\\")).isAbsolute()).isTrue();
}
@Test
public void testIsNormalizedWindows() {
- assertTrue(PathFragment.create("C:/").isNormalized());
- assertTrue(PathFragment.create("C:/absolute/path").isNormalized());
- assertFalse(PathFragment.create("C:/absolute/./path").isNormalized());
- assertFalse(PathFragment.create("C:/absolute/../path").isNormalized());
+ assertThat(PathFragment.create("C:/").isNormalized()).isTrue();
+ assertThat(PathFragment.create("C:/absolute/path").isNormalized()).isTrue();
+ assertThat(PathFragment.create("C:/absolute/./path").isNormalized()).isFalse();
+ assertThat(PathFragment.create("C:/absolute/../path").isNormalized()).isFalse();
}
@Test
public void testRootNodeReturnsRootStringWindows() {
PathFragment rootFragment = PathFragment.create("C:/");
- assertEquals("C:/", rootFragment.getPathString());
+ assertThat(rootFragment.getPathString()).isEqualTo("C:/");
}
@Test
public void testGetRelativeWindows() {
- assertEquals("C:/a/b", PathFragment.create("C:/a").getRelative("b").getPathString());
- assertEquals("C:/a/b/c/d", PathFragment.create("C:/a/b").getRelative("c/d").getPathString());
- assertEquals("C:/b", PathFragment.create("C:/a").getRelative("C:/b").getPathString());
- assertEquals("C:/c/d", PathFragment.create("C:/a/b").getRelative("C:/c/d").getPathString());
- assertEquals("C:/b", PathFragment.create("a").getRelative("C:/b").getPathString());
- assertEquals("C:/c/d", PathFragment.create("a/b").getRelative("C:/c/d").getPathString());
+ assertThat(PathFragment.create("C:/a").getRelative("b").getPathString()).isEqualTo("C:/a/b");
+ assertThat(PathFragment.create("C:/a/b").getRelative("c/d").getPathString())
+ .isEqualTo("C:/a/b/c/d");
+ assertThat(PathFragment.create("C:/a").getRelative("C:/b").getPathString()).isEqualTo("C:/b");
+ assertThat(PathFragment.create("C:/a/b").getRelative("C:/c/d").getPathString())
+ .isEqualTo("C:/c/d");
+ assertThat(PathFragment.create("a").getRelative("C:/b").getPathString()).isEqualTo("C:/b");
+ assertThat(PathFragment.create("a/b").getRelative("C:/c/d").getPathString())
+ .isEqualTo("C:/c/d");
}
private void assertGetRelative(String path, String relative, PathFragment expected)
@@ -144,7 +143,7 @@ public class PathFragmentWindowsTest {
PathFragment.create(path).relativeTo(relativeTo);
Assert.fail("expected failure");
} catch (Exception e) {
- assertThat(e.getMessage()).contains("is not beneath");
+ assertThat(e).hasMessageThat().contains("is not beneath");
}
}
@@ -194,7 +193,7 @@ public class PathFragmentWindowsTest {
@Test
public void testGetChildWorks() {
PathFragment pf = PathFragment.create("../some/path");
- assertEquals(PathFragment.create("../some/path/hi"), pf.getChild("hi"));
+ assertThat(pf.getChild("hi")).isEqualTo(PathFragment.create("../some/path/hi"));
}
// Tests after here test the canonicalization
@@ -300,81 +299,84 @@ public class PathFragmentWindowsTest {
PathFragment fooBarAbs = PathFragment.create("C:/foo/bar");
PathFragment fooAbs = PathFragment.create("C:/foo");
PathFragment rootAbs = PathFragment.create("C:/");
- assertEquals(fooBarAbs, fooBarWizAbs.getParentDirectory());
- assertEquals(fooAbs, fooBarAbs.getParentDirectory());
- assertEquals(rootAbs, fooAbs.getParentDirectory());
- assertNull(rootAbs.getParentDirectory());
+ assertThat(fooBarWizAbs.getParentDirectory()).isEqualTo(fooBarAbs);
+ assertThat(fooBarAbs.getParentDirectory()).isEqualTo(fooAbs);
+ assertThat(fooAbs.getParentDirectory()).isEqualTo(rootAbs);
+ assertThat(rootAbs.getParentDirectory()).isNull();
// Note, this is suprising but correct behaviour:
- assertEquals(fooBarAbs,
- PathFragment.create("C:/foo/bar/..").getParentDirectory());
+ assertThat(PathFragment.create("C:/foo/bar/..").getParentDirectory()).isEqualTo(fooBarAbs);
}
@Test
public void testSegmentsCountWindows() {
- assertEquals(1, PathFragment.create("C:/foo").segmentCount());
- assertEquals(0, PathFragment.create("C:/").segmentCount());
+ assertThat(PathFragment.create("C:/foo").segmentCount()).isEqualTo(1);
+ assertThat(PathFragment.create("C:/").segmentCount()).isEqualTo(0);
}
@Test
public void testGetSegmentWindows() {
- assertEquals("foo", PathFragment.create("C:/foo/bar").getSegment(0));
- assertEquals("bar", PathFragment.create("C:/foo/bar").getSegment(1));
- assertEquals("foo", PathFragment.create("C:/foo/").getSegment(0));
- assertEquals("foo", PathFragment.create("C:/foo").getSegment(0));
+ assertThat(PathFragment.create("C:/foo/bar").getSegment(0)).isEqualTo("foo");
+ assertThat(PathFragment.create("C:/foo/bar").getSegment(1)).isEqualTo("bar");
+ assertThat(PathFragment.create("C:/foo/").getSegment(0)).isEqualTo("foo");
+ assertThat(PathFragment.create("C:/foo").getSegment(0)).isEqualTo("foo");
}
@Test
public void testBasenameWindows() throws Exception {
- assertEquals("bar", PathFragment.create("C:/foo/bar").getBaseName());
- assertEquals("foo", PathFragment.create("C:/foo").getBaseName());
+ assertThat(PathFragment.create("C:/foo/bar").getBaseName()).isEqualTo("bar");
+ assertThat(PathFragment.create("C:/foo").getBaseName()).isEqualTo("foo");
// Never return the drive name as a basename.
assertThat(PathFragment.create("C:/").getBaseName()).isEmpty();
}
private static void assertPath(String expected, PathFragment actual) {
- assertEquals(expected, actual.getPathString());
+ assertThat(actual.getPathString()).isEqualTo(expected);
}
@Test
public void testReplaceNameWindows() throws Exception {
assertPath("C:/foo/baz", PathFragment.create("C:/foo/bar").replaceName("baz"));
- assertNull(PathFragment.create("C:/").replaceName("baz"));
+ assertThat(PathFragment.create("C:/").replaceName("baz")).isNull();
}
@Test
public void testStartsWithWindows() {
- assertTrue(PathFragment.create("C:/foo/bar").startsWith(PathFragment.create("C:/foo")));
- assertTrue(PathFragment.create("C:/foo/bar").startsWith(PathFragment.create("C:/")));
- assertTrue(PathFragment.create("C:foo/bar").startsWith(PathFragment.create("C:")));
- assertTrue(PathFragment.create("C:/").startsWith(PathFragment.create("C:/")));
- assertTrue(PathFragment.create("C:").startsWith(PathFragment.create("C:")));
+ assertThat(PathFragment.create("C:/foo/bar").startsWith(PathFragment.create("C:/foo")))
+ .isTrue();
+ assertThat(PathFragment.create("C:/foo/bar").startsWith(PathFragment.create("C:/"))).isTrue();
+ assertThat(PathFragment.create("C:foo/bar").startsWith(PathFragment.create("C:"))).isTrue();
+ assertThat(PathFragment.create("C:/").startsWith(PathFragment.create("C:/"))).isTrue();
+ assertThat(PathFragment.create("C:").startsWith(PathFragment.create("C:"))).isTrue();
// The first path is absolute, the second is not.
- assertFalse(PathFragment.create("C:/foo/bar").startsWith(PathFragment.create("C:")));
- assertFalse(PathFragment.create("C:/").startsWith(PathFragment.create("C:")));
+ assertThat(PathFragment.create("C:/foo/bar").startsWith(PathFragment.create("C:"))).isFalse();
+ assertThat(PathFragment.create("C:/").startsWith(PathFragment.create("C:"))).isFalse();
}
@Test
public void testEndsWithWindows() {
- assertTrue(PathFragment.create("C:/foo/bar").endsWith(PathFragment.create("bar")));
- assertTrue(PathFragment.create("C:/foo/bar").endsWith(PathFragment.create("foo/bar")));
- assertTrue(PathFragment.create("C:/foo/bar").endsWith(PathFragment.create("C:/foo/bar")));
- assertTrue(PathFragment.create("C:/").endsWith(PathFragment.create("C:/")));
+ assertThat(PathFragment.create("C:/foo/bar").endsWith(PathFragment.create("bar"))).isTrue();
+ assertThat(PathFragment.create("C:/foo/bar").endsWith(PathFragment.create("foo/bar"))).isTrue();
+ assertThat(PathFragment.create("C:/foo/bar").endsWith(PathFragment.create("C:/foo/bar")))
+ .isTrue();
+ assertThat(PathFragment.create("C:/").endsWith(PathFragment.create("C:/"))).isTrue();
}
@Test
public void testGetSafePathStringWindows() {
- assertEquals("C:/", PathFragment.create("C:/").getSafePathString());
- assertEquals("C:/abc", PathFragment.create("C:/abc").getSafePathString());
- assertEquals("C:/abc/def", PathFragment.create("C:/abc/def").getSafePathString());
+ assertThat(PathFragment.create("C:/").getSafePathString()).isEqualTo("C:/");
+ assertThat(PathFragment.create("C:/abc").getSafePathString()).isEqualTo("C:/abc");
+ assertThat(PathFragment.create("C:/abc/def").getSafePathString()).isEqualTo("C:/abc/def");
}
@Test
public void testNormalizeWindows() {
- assertEquals(PathFragment.create("C:/a/b"), PathFragment.create("C:/a/b").normalize());
- assertEquals(PathFragment.create("C:/a/b"), PathFragment.create("C:/a/./b").normalize());
- assertEquals(PathFragment.create("C:/b"), PathFragment.create("C:/a/../b").normalize());
- assertEquals(PathFragment.create("C:/../b"), PathFragment.create("C:/../b").normalize());
+ assertThat(PathFragment.create("C:/a/b").normalize()).isEqualTo(PathFragment.create("C:/a/b"));
+ assertThat(PathFragment.create("C:/a/./b").normalize())
+ .isEqualTo(PathFragment.create("C:/a/b"));
+ assertThat(PathFragment.create("C:/a/../b").normalize()).isEqualTo(PathFragment.create("C:/b"));
+ assertThat(PathFragment.create("C:/../b").normalize())
+ .isEqualTo(PathFragment.create("C:/../b"));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/PathGetParentTest.java b/src/test/java/com/google/devtools/build/lib/vfs/PathGetParentTest.java
index 5681ba2ab1..04def1c086 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/PathGetParentTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/PathGetParentTest.java
@@ -13,8 +13,7 @@
// limitations under the License.
package com.google.devtools.build.lib.vfs;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.testutil.TestUtils;
import com.google.devtools.build.lib.vfs.util.FileSystems;
@@ -52,17 +51,17 @@ public class PathGetParentTest {
@Test
public void testAbsoluteRootHasNoParent() {
- assertNull(getParent("/"));
+ assertThat(getParent("/")).isNull();
}
@Test
public void testParentOfSimpleDirectory() {
- assertEquals("/foo", getParent("/foo/bar").getPathString());
+ assertThat(getParent("/foo/bar").getPathString()).isEqualTo("/foo");
}
@Test
public void testParentOfDotDotInMiddleOfPathname() {
- assertEquals("/", getParent("/foo/../bar").getPathString());
+ assertThat(getParent("/foo/../bar").getPathString()).isEqualTo("/");
}
@Test
@@ -75,12 +74,12 @@ public class PathGetParentTest {
// ln -sf /tmp /tmp/wiz
tmpWiz.createSymbolicLink(tmp);
- assertEquals(testRoot, tmp.getParentDirectory());
+ assertThat(tmp.getParentDirectory()).isEqualTo(testRoot);
- assertEquals(tmp, tmpWiz.getParentDirectory());
+ assertThat(tmpWiz.getParentDirectory()).isEqualTo(tmp);
// Under UNIX, inode(/tmp/wiz/..) == inode(/). However getPath() does not
// perform I/O, only string operations, so it disagrees:
- assertEquals(tmp, tmp.getRelative(PathFragment.create("wiz/..")));
+ assertThat(tmp.getRelative(PathFragment.create("wiz/.."))).isEqualTo(tmp);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/PathTest.java b/src/test/java/com/google/devtools/build/lib/vfs/PathTest.java
index de1a47cb4c..3d5763ec7f 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/PathTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/PathTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.Lists;
@@ -105,7 +101,7 @@ public class PathTest {
String descendant) {
Path parent = filesystem.getPath(ancestor);
Path child = filesystem.getPath(descendant);
- assertEquals(expected, child.startsWith(parent));
+ assertThat(child.startsWith(parent)).isEqualTo(expected);
}
@Test
@@ -116,8 +112,8 @@ public class PathTest {
}
private void assertGetChildWorks(String childName) {
- assertEquals(filesystem.getPath("/first/" + childName),
- filesystem.getPath("/first").getChild(childName));
+ assertThat(filesystem.getPath("/first").getChild(childName))
+ .isEqualTo(filesystem.getPath("/first/" + childName));
}
@Test
@@ -178,26 +174,21 @@ public class PathTest {
@Test
public void testGetRelativeWithFragmentWorks() {
Path dir = filesystem.getPath("/first/x");
- assertEquals("/first/x/y",
- dir.getRelative(PathFragment.create("y")).toString());
- assertEquals("/first/x/x",
- dir.getRelative(PathFragment.create("./x")).toString());
- assertEquals("/first/y",
- dir.getRelative(PathFragment.create("../y")).toString());
-
+ assertThat(dir.getRelative(PathFragment.create("y")).toString()).isEqualTo("/first/x/y");
+ assertThat(dir.getRelative(PathFragment.create("./x")).toString()).isEqualTo("/first/x/x");
+ assertThat(dir.getRelative(PathFragment.create("../y")).toString()).isEqualTo("/first/y");
}
@Test
public void testGetRelativeWithAbsoluteFragmentWorks() {
Path root = filesystem.getPath("/first/x");
- assertEquals("/x/y",
- root.getRelative(PathFragment.create("/x/y")).toString());
+ assertThat(root.getRelative(PathFragment.create("/x/y")).toString()).isEqualTo("/x/y");
}
@Test
public void testGetRelativeWithAbsoluteStringWorks() {
Path root = filesystem.getPath("/first/x");
- assertEquals("/x/y", root.getRelative("/x/y").toString());
+ assertThat(root.getRelative("/x/y").toString()).isEqualTo("/x/y");
}
@Test
@@ -215,31 +206,26 @@ public class PathTest {
@Test
public void testParentOfRootIsRoot() {
- assertSame(root, root.getRelative(".."));
+ assertThat(root.getRelative("..")).isSameAs(root);
- assertSame(root.getRelative("dots"),
- root.getRelative("broken/../../dots"));
+ assertThat(root.getRelative("broken/../../dots")).isSameAs(root.getRelative("dots"));
}
@Test
public void testSingleSegmentEquivalence() {
- assertSame(
- root.getRelative("aSingleSegment"),
- root.getRelative("aSingleSegment"));
+ assertThat(root.getRelative("aSingleSegment")).isSameAs(root.getRelative("aSingleSegment"));
}
@Test
public void testSiblingNonEquivalenceString() {
- assertNotSame(
- root.getRelative("aSingleSegment"),
- root.getRelative("aDifferentSegment"));
+ assertThat(root.getRelative("aDifferentSegment"))
+ .isNotSameAs(root.getRelative("aSingleSegment"));
}
@Test
public void testSiblingNonEquivalenceFragment() {
- assertNotSame(
- root.getRelative(PathFragment.create("aSingleSegment")),
- root.getRelative(PathFragment.create("aDifferentSegment")));
+ assertThat(root.getRelative(PathFragment.create("aDifferentSegment")))
+ .isNotSameAs(root.getRelative(PathFragment.create("aSingleSegment")));
}
@Test
@@ -249,11 +235,11 @@ public class PathTest {
Path child = parent.getRelative(childFragment);
WeakReference<Path> childRef = new WeakReference<>(child);
int childHashCode1 = childRef.get().hashCode();
- assertEquals(childHashCode1, parent.getRelative(childFragment).hashCode());
+ assertThat(parent.getRelative(childFragment).hashCode()).isEqualTo(childHashCode1);
child = null;
GcFinalization.awaitClear(childRef);
int childHashCode2 = parent.getRelative(childFragment).hashCode();
- assertEquals(childHashCode1, childHashCode2);
+ assertThat(childHashCode2).isEqualTo(childHashCode1);
}
@Test
@@ -285,18 +271,19 @@ public class PathTest {
.addEqualityGroup(p2, dsP2)
.testEquals();
- assertTrue(p2.startsWith(p1));
- assertTrue(p2.startsWith(dsP1));
- assertTrue(dsP2.startsWith(p1));
- assertTrue(dsP2.startsWith(dsP1));
+ assertThat(p2.startsWith(p1)).isTrue();
+ assertThat(p2.startsWith(dsP1)).isTrue();
+ assertThat(dsP2.startsWith(p1)).isTrue();
+ assertThat(dsP2.startsWith(dsP1)).isTrue();
// Regression test for a very specific bug in compareTo involving our incorrect usage of
// reference equality rather than logical equality.
String relativePathStringA = "child/grandchildA";
String relativePathStringB = "child/grandchildB";
- assertEquals(
- p1.getRelative(relativePathStringA).compareTo(p1.getRelative(relativePathStringB)),
- p1.getRelative(relativePathStringA).compareTo(dsP1.getRelative(relativePathStringB)));
+ assertThat(
+ p1.getRelative(relativePathStringA).compareTo(dsP1.getRelative(relativePathStringB)))
+ .isEqualTo(
+ p1.getRelative(relativePathStringA).compareTo(p1.getRelative(relativePathStringB)));
} finally {
Path.setFileSystemForSerialization(oldFileSystem);
}
@@ -304,27 +291,27 @@ public class PathTest {
@Test
public void testAbsolutePathRoot() {
- assertEquals("/", new Path(null).toString());
+ assertThat(new Path(null).toString()).isEqualTo("/");
}
@Test
public void testAbsolutePath() {
Path segment = new Path(null, "bar.txt",
new Path(null, "foo", new Path(null)));
- assertEquals("/foo/bar.txt", segment.toString());
+ assertThat(segment.toString()).isEqualTo("/foo/bar.txt");
}
private void assertAsFragmentWorks(String expected) {
- assertEquals(PathFragment.create(expected), filesystem.getPath(expected).asFragment());
+ assertThat(filesystem.getPath(expected).asFragment()).isEqualTo(PathFragment.create(expected));
}
private void assertGetRelativeWorks(String expected, String relative) {
- assertEquals(filesystem.getPath(expected),
- filesystem.getPath("/first/x").getRelative(relative));
+ assertThat(filesystem.getPath("/first/x").getRelative(relative))
+ .isEqualTo(filesystem.getPath(expected));
}
private void assertRelativeToWorks(String expected, String relative, String original) {
- assertEquals(PathFragment.create(expected),
- filesystem.getPath(relative).relativeTo(filesystem.getPath(original)));
+ assertThat(filesystem.getPath(relative).relativeTo(filesystem.getPath(original)))
+ .isEqualTo(PathFragment.create(expected));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/RecursiveGlobTest.java b/src/test/java/com/google/devtools/build/lib/vfs/RecursiveGlobTest.java
index 4b3b697150..1d81efb924 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/RecursiveGlobTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/RecursiveGlobTest.java
@@ -20,19 +20,15 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.devtools.build.lib.util.BlazeClock;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
-
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Tests {@link UnixGlob} recursive globs.
- */
+/** Tests {@link UnixGlob} recursive globs. */
@RunWith(JUnit4.class)
public class RecursiveGlobTest {
@@ -161,7 +157,7 @@ public class RecursiveGlobTest {
.globInterruptible();
fail();
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).containsMatch("recursive wildcard must be its own segment");
+ assertThat(e).hasMessageThat().containsMatch("recursive wildcard must be its own segment");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/ScopeEscapableFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/vfs/ScopeEscapableFileSystemTest.java
index da471cd104..1474756b94 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/ScopeEscapableFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/ScopeEscapableFileSystemTest.java
@@ -15,12 +15,6 @@ package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -168,20 +162,20 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
// Checks that the semi-resolved path passed to the delegator matches the expected value.
private void checkPath(TestDelegator delegator, PathFragment expectedDelegatedPath) {
- assertEquals(expectedDelegatedPath, delegator.lastPath());
+ assertThat(delegator.lastPath()).isEqualTo(expectedDelegatedPath);
}
// Asserts that the condition is false and checks that the expected path was delegated.
private void assertFalseWithPathCheck(boolean result, TestDelegator delegator,
PathFragment expectedDelegatedPath) {
- assertFalse(result);
+ assertThat(result).isFalse();
checkPath(delegator, expectedDelegatedPath);
}
// Asserts that the condition is true and checks that the expected path was delegated.
private void assertTrueWithPathCheck(boolean result, TestDelegator delegator,
PathFragment expectedDelegatedPath) {
- assertTrue(result);
+ assertThat(result).isTrue();
checkPath(delegator, expectedDelegatedPath);
}
@@ -313,8 +307,8 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
// We shouldn't follow final-segment links, so they should never invoke the delegator.
delegator.setState(false);
- assertTrue(fileLink.isSymbolicLink());
- assertNull(delegator.lastPath());
+ assertThat(fileLink.isSymbolicLink()).isTrue();
+ assertThat(delegator.lastPath()).isNull();
assertFalseWithPathCheck(dirLink.getRelative("a").isSymbolicLink(), delegator,
dirLinkTarget.getRelative("a"));
@@ -392,8 +386,8 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
scopedFS().setDelegator(delegator);
delegator.setState(false);
- assertTrue(fileLink.delete());
- assertNull(delegator.lastPath()); // Deleting a link shouldn't require delegation.
+ assertThat(fileLink.delete()).isTrue();
+ assertThat(delegator.lastPath()).isNull(); // Deleting a link shouldn't require delegation.
assertFalseWithPathCheck(dirLink.getRelative("a").delete(), delegator,
dirLinkTarget.getRelative("a"));
@@ -415,16 +409,16 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
final int state1 = 10;
delegator.setState(state1);
- assertEquals(state1, fileLink.getFileSize());
+ assertThat(fileLink.getFileSize()).isEqualTo(state1);
checkPath(delegator, fileLinkTarget);
- assertEquals(state1, dirLink.getRelative("a").getFileSize());
+ assertThat(dirLink.getRelative("a").getFileSize()).isEqualTo(state1);
checkPath(delegator, dirLinkTarget.getRelative("a"));
final int state2 = 10;
delegator.setState(state2);
- assertEquals(state2, fileLink.getFileSize());
+ assertThat(fileLink.getFileSize()).isEqualTo(state2);
checkPath(delegator, fileLinkTarget);
- assertEquals(state2, dirLink.getRelative("a").getFileSize());
+ assertThat(dirLink.getRelative("a").getFileSize()).isEqualTo(state2);
checkPath(delegator, dirLinkTarget.getRelative("a"));
}
@@ -440,16 +434,16 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
final int state1 = 10;
delegator.setState(state1);
- assertEquals(state1, fileLink.getLastModifiedTime());
+ assertThat(fileLink.getLastModifiedTime()).isEqualTo(state1);
checkPath(delegator, fileLinkTarget);
- assertEquals(state1, dirLink.getRelative("a").getLastModifiedTime());
+ assertThat(dirLink.getRelative("a").getLastModifiedTime()).isEqualTo(state1);
checkPath(delegator, dirLinkTarget.getRelative("a"));
final int state2 = 10;
delegator.setState(state2);
- assertEquals(state2, fileLink.getLastModifiedTime());
+ assertThat(fileLink.getLastModifiedTime()).isEqualTo(state2);
checkPath(delegator, fileLinkTarget);
- assertEquals(state2, dirLink.getRelative("a").getLastModifiedTime());
+ assertThat(dirLink.getRelative("a").getLastModifiedTime()).isEqualTo(state2);
checkPath(delegator, dirLinkTarget.getRelative("a"));
}
@@ -465,18 +459,18 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
delegator.setState(false);
fileLink.setReadable(true);
- assertTrue(delegator.booleanState());
+ assertThat(delegator.booleanState()).isTrue();
checkPath(delegator, fileLinkTarget);
fileLink.setReadable(false);
- assertFalse(delegator.booleanState());
+ assertThat(delegator.booleanState()).isFalse();
checkPath(delegator, fileLinkTarget);
delegator.setState(false);
dirLink.getRelative("a").setReadable(true);
- assertTrue(delegator.booleanState());
+ assertThat(delegator.booleanState()).isTrue();
checkPath(delegator, dirLinkTarget.getRelative("a"));
dirLink.getRelative("a").setReadable(false);
- assertFalse(delegator.booleanState());
+ assertThat(delegator.booleanState()).isFalse();
checkPath(delegator, dirLinkTarget.getRelative("a"));
}
@@ -492,18 +486,18 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
delegator.setState(false);
fileLink.setWritable(true);
- assertTrue(delegator.booleanState());
+ assertThat(delegator.booleanState()).isTrue();
checkPath(delegator, fileLinkTarget);
fileLink.setWritable(false);
- assertFalse(delegator.booleanState());
+ assertThat(delegator.booleanState()).isFalse();
checkPath(delegator, fileLinkTarget);
delegator.setState(false);
dirLink.getRelative("a").setWritable(true);
- assertTrue(delegator.booleanState());
+ assertThat(delegator.booleanState()).isTrue();
checkPath(delegator, dirLinkTarget.getRelative("a"));
dirLink.getRelative("a").setWritable(false);
- assertFalse(delegator.booleanState());
+ assertThat(delegator.booleanState()).isFalse();
checkPath(delegator, dirLinkTarget.getRelative("a"));
}
@@ -519,18 +513,18 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
delegator.setState(false);
fileLink.setReadable(true);
- assertTrue(delegator.booleanState());
+ assertThat(delegator.booleanState()).isTrue();
checkPath(delegator, fileLinkTarget);
fileLink.setReadable(false);
- assertFalse(delegator.booleanState());
+ assertThat(delegator.booleanState()).isFalse();
checkPath(delegator, fileLinkTarget);
delegator.setState(false);
dirLink.getRelative("a").setReadable(true);
- assertTrue(delegator.booleanState());
+ assertThat(delegator.booleanState()).isTrue();
checkPath(delegator, dirLinkTarget.getRelative("a"));
dirLink.getRelative("a").setReadable(false);
- assertFalse(delegator.booleanState());
+ assertThat(delegator.booleanState()).isFalse();
checkPath(delegator, dirLinkTarget.getRelative("a"));
}
@@ -546,17 +540,17 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
delegator.setState(0);
fileLink.setLastModifiedTime(10);
- assertEquals(10, delegator.longState());
+ assertThat(delegator.longState()).isEqualTo(10);
checkPath(delegator, fileLinkTarget);
fileLink.setLastModifiedTime(15);
- assertEquals(15, delegator.longState());
+ assertThat(delegator.longState()).isEqualTo(15);
checkPath(delegator, fileLinkTarget);
dirLink.getRelative("a").setLastModifiedTime(20);
- assertEquals(20, delegator.longState());
+ assertThat(delegator.longState()).isEqualTo(20);
checkPath(delegator, dirLinkTarget.getRelative("a"));
dirLink.getRelative("a").setLastModifiedTime(25);
- assertEquals(25, delegator.longState());
+ assertThat(delegator.longState()).isEqualTo(25);
checkPath(delegator, dirLinkTarget.getRelative("a"));
}
@@ -574,8 +568,8 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
// Renaming a link should work fine.
delegator.setState(null);
fileLink.renameTo(testFS.getPath(SCOPE_ROOT).getRelative("newname"));
- assertNull(delegator.lastPath()); // Renaming a link shouldn't require delegation.
- assertNull(delegator.objectState());
+ assertThat(delegator.lastPath()).isNull(); // Renaming a link shouldn't require delegation.
+ assertThat(delegator.objectState()).isNull();
// Renaming an out-of-scope path to an in-scope path should fail due to filesystem mismatch
// errors.
@@ -590,8 +584,9 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
// Renaming an out-of-scope path to another out-of-scope path can be valid.
newPath = dirLink.getRelative("b");
dirLink.getRelative("a").renameTo(newPath);
- assertEquals(dirLinkTarget.getRelative("a"), delegator.lastPath());
- assertEquals(dirLinkTarget.getRelative("b"), ((Path) delegator.objectState()).asFragment());
+ assertThat(delegator.lastPath()).isEqualTo(dirLinkTarget.getRelative("a"));
+ assertThat(((Path) delegator.objectState()).asFragment())
+ .isEqualTo(dirLinkTarget.getRelative("b"));
}
@Test
@@ -607,8 +602,8 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
PathFragment newLinkTarget = PathFragment.create("/something/else");
dirLink.getRelative("a").createSymbolicLink(newLinkTarget);
- assertEquals(dirLinkTarget.getRelative("a"), delegator.lastPath());
- assertSame(newLinkTarget, delegator.objectState());
+ assertThat(delegator.lastPath()).isEqualTo(dirLinkTarget.getRelative("a"));
+ assertThat(delegator.objectState()).isSameAs(newLinkTarget);
}
@Test
@@ -625,13 +620,13 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
// Since we're not following the link, this shouldn't invoke delegation.
delegator.setState(PathFragment.create("whatever"));
PathFragment p = fileLink.readSymbolicLink();
- assertNull(delegator.lastPath());
- assertNotSame(delegator.objectState(), p);
+ assertThat(delegator.lastPath()).isNull();
+ assertThat(p).isNotSameAs(delegator.objectState());
// This should.
p = dirLink.getRelative("a").readSymbolicLink();
- assertEquals(dirLinkTarget.getRelative("a"), delegator.lastPath());
- assertSame(delegator.objectState(), p);
+ assertThat(delegator.lastPath()).isEqualTo(dirLinkTarget.getRelative("a"));
+ assertThat(p).isSameAs(delegator.objectState());
}
@Test
@@ -646,13 +641,13 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
delegator.setState(new ByteArrayInputStream("blah".getBytes(UTF_8)));
InputStream is = fileLink.getInputStream();
- assertEquals(fileLinkTarget, delegator.lastPath());
- assertSame(delegator.objectState(), is);
+ assertThat(delegator.lastPath()).isEqualTo(fileLinkTarget);
+ assertThat(is).isSameAs(delegator.objectState());
delegator.setState(new ByteArrayInputStream("blah2".getBytes(UTF_8)));
is = dirLink.getInputStream();
- assertEquals(dirLinkTarget, delegator.lastPath());
- assertSame(delegator.objectState(), is);
+ assertThat(delegator.lastPath()).isEqualTo(dirLinkTarget);
+ assertThat(is).isSameAs(delegator.objectState());
}
@Test
@@ -668,13 +663,13 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
delegator.setState(new ByteArrayOutputStream());
OutputStream os = fileLink.getOutputStream();
- assertEquals(fileLinkTarget, delegator.lastPath());
- assertSame(delegator.objectState(), os);
+ assertThat(delegator.lastPath()).isEqualTo(fileLinkTarget);
+ assertThat(os).isSameAs(delegator.objectState());
delegator.setState(new ByteArrayOutputStream());
os = dirLink.getOutputStream();
- assertEquals(dirLinkTarget, delegator.lastPath());
- assertSame(delegator.objectState(), os);
+ assertThat(delegator.lastPath()).isEqualTo(dirLinkTarget);
+ assertThat(os).isSameAs(delegator.objectState());
}
@Test
@@ -690,9 +685,9 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
delegator.setState(testFS.getPath("/anything"));
Collection<Path> entries = dirLink.getDirectoryEntries();
- assertEquals(dirLinkTarget, delegator.lastPath());
+ assertThat(delegator.lastPath()).isEqualTo(dirLinkTarget);
assertThat(entries).hasSize(1);
- assertSame(delegator.objectState(), entries.iterator().next());
+ assertThat(entries.iterator().next()).isSameAs(delegator.objectState());
}
/**
@@ -707,7 +702,7 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
Path l = testFS.getPath(SCOPE_ROOT.getRelative(link));
testFS.createSymbolicLink(l, PathFragment.create(target));
l.exists();
- assertNull(d.lastPath());
+ assertThat(d.lastPath()).isNull();
}
/**
@@ -719,7 +714,7 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
Path l = testFS.getPath(SCOPE_ROOT.getRelative(link));
testFS.createSymbolicLink(l, PathFragment.create(target));
l.exists();
- assertEquals(expectedPath, d.lastPath().getPathString());
+ assertThat(d.lastPath().getPathString()).isEqualTo(expectedPath);
}
/**
@@ -764,13 +759,13 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
Path iDirLink = testFS.getPath(SCOPE_ROOT.getRelative("ilinkdir"));
testFS.createSymbolicLink(iDirLink, SCOPE_ROOT.getRelative("dir"));
iDirLink.getRelative("file").exists();
- assertNull(d.lastPath());
+ assertThat(d.lastPath()).isNull();
// Out-of-scope symlink that's not the final segment in a query.
Path oDirLink = testFS.getPath(SCOPE_ROOT.getRelative("olinkdir"));
testFS.createSymbolicLink(oDirLink, PathFragment.create("/some/other/dir"));
oDirLink.getRelative("file").exists();
- assertEquals("/some/other/dir/file", d.lastPath().getPathString());
+ assertThat(d.lastPath().getPathString()).isEqualTo("/some/other/dir/file");
}
/**
@@ -809,12 +804,12 @@ public abstract class ScopeEscapableFileSystemTest extends SymlinkAwareFileSyste
Path iDirLink = testFS.getPath(SCOPE_ROOT.getRelative("dir/dir2/ilinkdir"));
testFS.createSymbolicLink(iDirLink, PathFragment.create("../../dir"));
iDirLink.getRelative("file").exists();
- assertNull(d.lastPath());
+ assertThat(d.lastPath()).isNull();
// Out-of-scope symlink that's not the final segment in a query.
Path oDirLink = testFS.getPath(SCOPE_ROOT.getRelative("dir/dir2/olinkdir"));
testFS.createSymbolicLink(oDirLink, PathFragment.create("../../../other/dir"));
oDirLink.getRelative("file").exists();
- assertEquals(chopScopeRoot(1) + "/other/dir/file", d.lastPath().getPathString());
+ assertThat(d.lastPath().getPathString()).isEqualTo(chopScopeRoot(1) + "/other/dir/file");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/SearchPathTest.java b/src/test/java/com/google/devtools/build/lib/vfs/SearchPathTest.java
index 39fb2852bf..6c545ac790 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/SearchPathTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/SearchPathTest.java
@@ -17,20 +17,18 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
-
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.List;
-
@RunWith(JUnit4.class)
public class SearchPathTest {
private FileSystem fs = new InMemoryFileSystem();
@Test
public void testNull() throws Exception {
- assertThat(SearchPath.parse(fs, null)).isEqualTo(ImmutableList.of());
+ assertThat(SearchPath.parse(fs, null)).isEmpty();
}
@Test
@@ -42,12 +40,12 @@ public class SearchPathTest {
fs.getOutputStream(fs.getPath("/bin/exe")).write(new byte[5]);
- assertThat(SearchPath.which(searchPath, "exe")).isEqualTo(null);
+ assertThat(SearchPath.which(searchPath, "exe")).isNull();
fs.getPath("/bin/exe").setExecutable(true);
assertThat(SearchPath.which(searchPath, "exe")).isEqualTo(fs.getPath("/bin/exe"));
- assertThat(SearchPath.which(searchPath, "bin/exe")).isEqualTo(null);
- assertThat(SearchPath.which(searchPath, "/bin/exe")).isEqualTo(null);
+ assertThat(SearchPath.which(searchPath, "bin/exe")).isNull();
+ assertThat(SearchPath.which(searchPath, "/bin/exe")).isNull();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/SymlinkAwareFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/vfs/SymlinkAwareFileSystemTest.java
index 5352f486db..82f8d727aa 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/SymlinkAwareFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/SymlinkAwareFileSystemTest.java
@@ -14,11 +14,6 @@
package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.vfs.FileSystem.NotASymlinkException;
@@ -73,19 +68,19 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
createSymbolicLink(linkPath, newPath);
- assertTrue(linkPath.isSymbolicLink());
+ assertThat(linkPath.isSymbolicLink()).isTrue();
- assertTrue(linkPath.isFile());
- assertFalse(linkPath.isFile(Symlinks.NOFOLLOW));
- assertTrue(linkPath.isFile(Symlinks.FOLLOW));
+ assertThat(linkPath.isFile()).isTrue();
+ assertThat(linkPath.isFile(Symlinks.NOFOLLOW)).isFalse();
+ assertThat(linkPath.isFile(Symlinks.FOLLOW)).isTrue();
- assertFalse(linkPath.isDirectory());
- assertFalse(linkPath.isDirectory(Symlinks.NOFOLLOW));
- assertFalse(linkPath.isDirectory(Symlinks.FOLLOW));
+ assertThat(linkPath.isDirectory()).isFalse();
+ assertThat(linkPath.isDirectory(Symlinks.NOFOLLOW)).isFalse();
+ assertThat(linkPath.isDirectory(Symlinks.FOLLOW)).isFalse();
if (supportsSymlinks) {
- assertEquals(newPath.toString().length(), linkPath.getFileSize(Symlinks.NOFOLLOW));
- assertEquals(newPath.getFileSize(Symlinks.NOFOLLOW), linkPath.getFileSize());
+ assertThat(linkPath.getFileSize(Symlinks.NOFOLLOW)).isEqualTo(newPath.toString().length());
+ assertThat(linkPath.getFileSize()).isEqualTo(newPath.getFileSize(Symlinks.NOFOLLOW));
}
assertThat(linkPath.getParentDirectory().getDirectoryEntries()).hasSize(2);
assertThat(linkPath.getParentDirectory().getDirectoryEntries()).containsExactly(newPath,
@@ -101,9 +96,9 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
createSymbolicLink(linkPath, newPath);
- assertTrue(linkPath.isSymbolicLink());
- assertFalse(linkPath.isFile());
- assertTrue(linkPath.isDirectory());
+ assertThat(linkPath.isSymbolicLink()).isTrue();
+ assertThat(linkPath.isFile()).isFalse();
+ assertThat(linkPath.isDirectory()).isTrue();
assertThat(linkPath.getParentDirectory().getDirectoryEntries()).hasSize(2);
assertThat(linkPath.getParentDirectory().
getDirectoryEntries()).containsExactly(newPath, linkPath);
@@ -147,8 +142,8 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
private void assertCanonicalPathsMatch(Path newPath, Path link1, Path link2)
throws IOException {
- assertEquals(newPath, link1.resolveSymbolicLinks());
- assertEquals(newPath, link2.resolveSymbolicLinks());
+ assertThat(link1.resolveSymbolicLinks()).isEqualTo(newPath);
+ assertThat(link2.resolveSymbolicLinks()).isEqualTo(newPath);
}
//
@@ -163,8 +158,8 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
} catch (IOException e) {
assertThat(e).hasMessage(xDanglingLink + " (File exists)");
}
- assertTrue(xDanglingLink.isSymbolicLink()); // still a symbolic link
- assertFalse(xDanglingLink.isDirectory(Symlinks.FOLLOW)); // link still dangles
+ assertThat(xDanglingLink.isSymbolicLink()).isTrue(); // still a symbolic link
+ assertThat(xDanglingLink.isDirectory(Symlinks.FOLLOW)).isFalse(); // link still dangles
}
@Test
@@ -175,8 +170,8 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
} catch (IOException e) {
assertThat(e).hasMessage(xLinkToDirectory + " (File exists)");
}
- assertTrue(xLinkToDirectory.isSymbolicLink()); // still a symbolic link
- assertTrue(xLinkToDirectory.isDirectory(Symlinks.FOLLOW)); // link still points to dir
+ assertThat(xLinkToDirectory.isSymbolicLink()).isTrue(); // still a symbolic link
+ assertThat(xLinkToDirectory.isDirectory(Symlinks.FOLLOW)).isTrue(); // link still points to dir
}
// createSymbolicLink(PathFragment)
@@ -202,8 +197,8 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
linkPath.delete();
createSymbolicLink(linkPath, relative);
if (supportsSymlinks) {
- assertEquals(linkTarget.length(), linkPath.getFileSize(Symlinks.NOFOLLOW));
- assertEquals(relative, linkPath.readSymbolicLink());
+ assertThat(linkPath.getFileSize(Symlinks.NOFOLLOW)).isEqualTo(linkTarget.length());
+ assertThat(linkPath.readSymbolicLink()).isEqualTo(relative);
}
}
}
@@ -235,10 +230,10 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
break;
}
}
-
- assertNotNull(nonLinkEntry);
+
+ assertThat(nonLinkEntry).isNotNull();
Path rootChild = testFS.getPath("/" + nonLinkEntry);
- assertEquals(rootChild, linkPath.getRelative(nonLinkEntry).resolveSymbolicLinks());
+ assertThat(linkPath.getRelative(nonLinkEntry).resolveSymbolicLinks()).isEqualTo(rootChild);
}
@Test
@@ -251,7 +246,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
createSymbolicLink(link1, link1target); // ln -s link2/foo link1
createSymbolicLink(link2, link2target); // ln -s xNonEmptyDirectory link2
// link1 --> xNonEmptyDirectory/foo
- assertEquals(link1.resolveSymbolicLinks(), link2target.getRelative("foo"));
+ assertThat(link2target.getRelative("foo")).isEqualTo(link1.resolveSymbolicLinks());
}
//
@@ -330,7 +325,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
while ((ancestor = ancestor.getParentDirectory()) != null) {
xLinkToFile.delete();
createSymbolicLink(xLinkToFile, PathFragment.create(prefix + xFile.relativeTo(ancestor)));
- assertEquals(xFile, xLinkToFile.resolveSymbolicLinks());
+ assertThat(xLinkToFile.resolveSymbolicLinks()).isEqualTo(xFile);
prefix += "../";
}
@@ -340,15 +335,13 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
@Test
public void testReadSymbolicLink() throws IOException {
if (supportsSymlinks) {
- assertEquals(xNothing.toString(),
- xDanglingLink.readSymbolicLink().toString());
+ assertThat(xDanglingLink.readSymbolicLink().toString()).isEqualTo(xNothing.toString());
}
- assertEquals(xFile.toString(),
- xLinkToFile.readSymbolicLink().toString());
+ assertThat(xLinkToFile.readSymbolicLink().toString()).isEqualTo(xFile.toString());
- assertEquals(xEmptyDirectory.toString(),
- xLinkToDirectory.readSymbolicLink().toString());
+ assertThat(xLinkToDirectory.readSymbolicLink().toString())
+ .isEqualTo(xEmptyDirectory.toString());
try {
xFile.readSymbolicLink(); // not a link
@@ -389,9 +382,9 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
Path newPath = absolutize("non-existing-dir/new-file");
Path someLink = absolutize("dangling-link");
createSymbolicLink(someLink, newPath);
- assertTrue(someLink.isSymbolicLink());
- assertTrue(someLink.exists(Symlinks.NOFOLLOW)); // the link itself exists
- assertFalse(someLink.exists()); // ...but the referent doesn't
+ assertThat(someLink.isSymbolicLink()).isTrue();
+ assertThat(someLink.exists(Symlinks.NOFOLLOW)).isTrue(); // the link itself exists
+ assertThat(someLink.exists()).isFalse(); // ...but the referent doesn't
if (supportsSymlinks) {
try {
someLink.resolveSymbolicLinks();
@@ -409,7 +402,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
xChildOfMissingDir.createSymbolicLink(xFile);
fail();
} catch (FileNotFoundException e) {
- assertThat(e.getMessage()).endsWith(" (No such file or directory)");
+ assertThat(e).hasMessageThat().endsWith(" (No such file or directory)");
}
}
}
@@ -417,7 +410,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
@Test
public void testCreateSymbolicLinkWhereNothingExists() throws IOException {
createSymbolicLink(xNothing, xFile);
- assertTrue(xNothing.isSymbolicLink());
+ assertThat(xNothing.isSymbolicLink()).isTrue();
}
@Test
@@ -428,7 +421,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
} catch (IOException e) { // => couldn't be created
assertThat(e).hasMessage(xEmptyDirectory + " (File exists)");
}
- assertTrue(xEmptyDirectory.isDirectory(Symlinks.NOFOLLOW));
+ assertThat(xEmptyDirectory.isDirectory(Symlinks.NOFOLLOW)).isTrue();
}
@Test
@@ -439,7 +432,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
} catch (IOException e) { // => couldn't be created
assertThat(e).hasMessage(xFile + " (File exists)");
}
- assertTrue(xFile.isFile(Symlinks.NOFOLLOW));
+ assertThat(xFile.isFile(Symlinks.NOFOLLOW)).isTrue();
}
@Test
@@ -450,8 +443,8 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
} catch (IOException e) {
assertThat(e).hasMessage(xDanglingLink + " (File exists)");
}
- assertTrue(xDanglingLink.isSymbolicLink()); // still a symbolic link
- assertFalse(xDanglingLink.isDirectory()); // link still dangles
+ assertThat(xDanglingLink.isSymbolicLink()).isTrue(); // still a symbolic link
+ assertThat(xDanglingLink.isDirectory()).isFalse(); // link still dangles
}
@Test
@@ -462,8 +455,8 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
} catch (IOException e) {
assertThat(e).hasMessage(xLinkToDirectory + " (File exists)");
}
- assertTrue(xLinkToDirectory.isSymbolicLink()); // still a symbolic link
- assertTrue(xLinkToDirectory.isDirectory()); // link still points to dir
+ assertThat(xLinkToDirectory.isSymbolicLink()).isTrue(); // still a symbolic link
+ assertThat(xLinkToDirectory.isDirectory()).isTrue(); // link still points to dir
}
@Test
@@ -473,10 +466,10 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
FileSystemUtils.createEmptyFile(newPath);
createSymbolicLink(someLink, newPath);
- assertEquals(2, xEmptyDirectory.getDirectoryEntries().size());
+ assertThat(xEmptyDirectory.getDirectoryEntries()).hasSize(2);
- assertTrue(someLink.delete());
- assertEquals(1, xEmptyDirectory.getDirectoryEntries().size());
+ assertThat(someLink.delete()).isTrue();
+ assertThat(xEmptyDirectory.getDirectoryEntries()).hasSize(1);
assertThat(xEmptyDirectory.getDirectoryEntries()).containsExactly(newPath);
}
@@ -485,7 +478,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
@Test
public void testLinkFollowedToDirectory() throws IOException {
Path theDirectory = absolutize("foo/");
- assertTrue(theDirectory.createDirectory());
+ assertThat(theDirectory.createDirectory()).isTrue();
Path newPath1 = absolutize("foo/new-file-1");
Path newPath2 = absolutize("foo/new-file-2");
Path newPath3 = absolutize("foo/new-file-3");
@@ -509,7 +502,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
Path newPath1 = absolutize("new-file-1");
Path newPath2 = absolutize("new-file-2");
FileSystemUtils.createEmptyFile(newPath1);
- assertTrue(newPath2.createDirectory());
+ assertThat(newPath2.createDirectory()).isTrue();
Path linkPath1 = absolutize("link1");
Path linkPath2 = absolutize("link2");
@@ -519,8 +512,8 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
newPath1.delete();
newPath2.delete();
- assertFalse(linkPath1.isFile());
- assertFalse(linkPath2.isDirectory());
+ assertThat(linkPath1.isFile()).isFalse();
+ assertThat(linkPath2.isDirectory()).isFalse();
}
@Test
@@ -536,7 +529,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
String resultData =
new String(FileSystemUtils.readContentAsLatin1(testFile));
- assertEquals(testData,resultData);
+ assertThat(resultData).isEqualTo(testData);
}
//
@@ -549,20 +542,20 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
Path b = absolutize("b");
FileSystemUtils.createEmptyFile(b);
createSymbolicLink(a, b); // ln -sf "b" "a"
- assertTrue(a.exists()); // = exists(FOLLOW)
- assertTrue(b.exists()); // = exists(FOLLOW)
- assertTrue(a.exists(Symlinks.FOLLOW));
- assertTrue(b.exists(Symlinks.FOLLOW));
- assertTrue(a.exists(Symlinks.NOFOLLOW));
- assertTrue(b.exists(Symlinks.NOFOLLOW));
+ assertThat(a.exists()).isTrue(); // = exists(FOLLOW)
+ assertThat(b.exists()).isTrue(); // = exists(FOLLOW)
+ assertThat(a.exists(Symlinks.FOLLOW)).isTrue();
+ assertThat(b.exists(Symlinks.FOLLOW)).isTrue();
+ assertThat(a.exists(Symlinks.NOFOLLOW)).isTrue();
+ assertThat(b.exists(Symlinks.NOFOLLOW)).isTrue();
b.delete(); // "a" is now a dangling link
- assertFalse(a.exists()); // = exists(FOLLOW)
- assertFalse(b.exists()); // = exists(FOLLOW)
- assertFalse(a.exists(Symlinks.FOLLOW));
- assertFalse(b.exists(Symlinks.FOLLOW));
+ assertThat(a.exists()).isFalse(); // = exists(FOLLOW)
+ assertThat(b.exists()).isFalse(); // = exists(FOLLOW)
+ assertThat(a.exists(Symlinks.FOLLOW)).isFalse();
+ assertThat(b.exists(Symlinks.FOLLOW)).isFalse();
- assertTrue(a.exists(Symlinks.NOFOLLOW)); // symlink still exists
- assertFalse(b.exists(Symlinks.NOFOLLOW));
+ assertThat(a.exists(Symlinks.NOFOLLOW)).isTrue(); // symlink still exists
+ assertThat(b.exists(Symlinks.NOFOLLOW)).isFalse();
}
@Test
@@ -571,19 +564,19 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
Path b = absolutize("b");
b.createDirectory();
createSymbolicLink(a, b); // ln -sf "b" "a"
- assertTrue(a.isDirectory()); // = isDirectory(FOLLOW)
- assertTrue(b.isDirectory()); // = isDirectory(FOLLOW)
- assertTrue(a.isDirectory(Symlinks.FOLLOW));
- assertTrue(b.isDirectory(Symlinks.FOLLOW));
- assertFalse(a.isDirectory(Symlinks.NOFOLLOW)); // it's a link!
- assertTrue(b.isDirectory(Symlinks.NOFOLLOW));
+ assertThat(a.isDirectory()).isTrue(); // = isDirectory(FOLLOW)
+ assertThat(b.isDirectory()).isTrue(); // = isDirectory(FOLLOW)
+ assertThat(a.isDirectory(Symlinks.FOLLOW)).isTrue();
+ assertThat(b.isDirectory(Symlinks.FOLLOW)).isTrue();
+ assertThat(a.isDirectory(Symlinks.NOFOLLOW)).isFalse(); // it's a link!
+ assertThat(b.isDirectory(Symlinks.NOFOLLOW)).isTrue();
b.delete(); // "a" is now a dangling link
- assertFalse(a.isDirectory()); // = isDirectory(FOLLOW)
- assertFalse(b.isDirectory()); // = isDirectory(FOLLOW)
- assertFalse(a.isDirectory(Symlinks.FOLLOW));
- assertFalse(b.isDirectory(Symlinks.FOLLOW));
- assertFalse(a.isDirectory(Symlinks.NOFOLLOW));
- assertFalse(b.isDirectory(Symlinks.NOFOLLOW));
+ assertThat(a.isDirectory()).isFalse(); // = isDirectory(FOLLOW)
+ assertThat(b.isDirectory()).isFalse(); // = isDirectory(FOLLOW)
+ assertThat(a.isDirectory(Symlinks.FOLLOW)).isFalse();
+ assertThat(b.isDirectory(Symlinks.FOLLOW)).isFalse();
+ assertThat(a.isDirectory(Symlinks.NOFOLLOW)).isFalse();
+ assertThat(b.isDirectory(Symlinks.NOFOLLOW)).isFalse();
}
@Test
@@ -592,19 +585,19 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
Path b = absolutize("b");
FileSystemUtils.createEmptyFile(b);
createSymbolicLink(a, b); // ln -sf "b" "a"
- assertTrue(a.isFile()); // = isFile(FOLLOW)
- assertTrue(b.isFile()); // = isFile(FOLLOW)
- assertTrue(a.isFile(Symlinks.FOLLOW));
- assertTrue(b.isFile(Symlinks.FOLLOW));
- assertFalse(a.isFile(Symlinks.NOFOLLOW)); // it's a link!
- assertTrue(b.isFile(Symlinks.NOFOLLOW));
+ assertThat(a.isFile()).isTrue(); // = isFile(FOLLOW)
+ assertThat(b.isFile()).isTrue(); // = isFile(FOLLOW)
+ assertThat(a.isFile(Symlinks.FOLLOW)).isTrue();
+ assertThat(b.isFile(Symlinks.FOLLOW)).isTrue();
+ assertThat(a.isFile(Symlinks.NOFOLLOW)).isFalse(); // it's a link!
+ assertThat(b.isFile(Symlinks.NOFOLLOW)).isTrue();
b.delete(); // "a" is now a dangling link
- assertFalse(a.isFile()); // = isFile()
- assertFalse(b.isFile()); // = isFile()
- assertFalse(a.isFile());
- assertFalse(b.isFile());
- assertFalse(a.isFile(Symlinks.NOFOLLOW));
- assertFalse(b.isFile(Symlinks.NOFOLLOW));
+ assertThat(a.isFile()).isFalse(); // = isFile()
+ assertThat(b.isFile()).isFalse(); // = isFile()
+ assertThat(a.isFile()).isFalse();
+ assertThat(b.isFile()).isFalse();
+ assertThat(a.isFile(Symlinks.NOFOLLOW)).isFalse();
+ assertThat(b.isFile(Symlinks.NOFOLLOW)).isFalse();
}
@Test
@@ -620,11 +613,11 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
Path child = xEmptyDirectory.getChild("child");
Path aliasToChild = xLinkToDirectory.getChild("child");
- assertFalse(aliasToChild.exists());
+ assertThat(aliasToChild.exists()).isFalse();
FileSystemUtils.createEmptyFile(child);
- assertTrue(aliasToChild.exists());
- assertTrue(aliasToChild.isFile());
- assertFalse(aliasToChild.isDirectory());
+ assertThat(aliasToChild.exists()).isTrue();
+ assertThat(aliasToChild.isFile()).isTrue();
+ assertThat(aliasToChild.isDirectory()).isFalse();
validateLinkedReferenceObeysReadOnly(child, aliasToChild);
validateLinkedReferenceObeysExecutable(child, aliasToChild);
@@ -635,11 +628,11 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
Path childDir = xEmptyDirectory.getChild("childDir");
Path linkToChildDir = xLinkToDirectory.getChild("childDir");
- assertFalse(linkToChildDir.exists());
+ assertThat(linkToChildDir.exists()).isFalse();
childDir.createDirectory();
- assertTrue(linkToChildDir.exists());
- assertTrue(linkToChildDir.isDirectory());
- assertFalse(linkToChildDir.isFile());
+ assertThat(linkToChildDir.exists()).isTrue();
+ assertThat(linkToChildDir.isDirectory()).isTrue();
+ assertThat(linkToChildDir.isFile()).isFalse();
validateLinkedReferenceObeysReadOnly(childDir, linkToChildDir);
validateLinkedReferenceObeysExecutable(childDir, linkToChildDir);
@@ -652,11 +645,11 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
createSymbolicLink(linkToLinkToDirectory, xLinkToDirectory);
Path linkToChildDir = linkToLinkToDirectory.getChild("childDir");
- assertFalse(linkToChildDir.exists());
+ assertThat(linkToChildDir.exists()).isFalse();
childDir.createDirectory();
- assertTrue(linkToChildDir.exists());
- assertTrue(linkToChildDir.isDirectory());
- assertFalse(linkToChildDir.isFile());
+ assertThat(linkToChildDir.exists()).isTrue();
+ assertThat(linkToChildDir.isDirectory()).isTrue();
+ assertThat(linkToChildDir.isFile()).isFalse();
validateLinkedReferenceObeysReadOnly(childDir, linkToChildDir);
validateLinkedReferenceObeysExecutable(childDir, linkToChildDir);
@@ -664,26 +657,26 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
private void validateLinkedReferenceObeysReadOnly(Path path, Path link) throws IOException {
path.setWritable(false);
- assertFalse(path.isWritable());
- assertFalse(link.isWritable());
+ assertThat(path.isWritable()).isFalse();
+ assertThat(link.isWritable()).isFalse();
path.setWritable(true);
- assertTrue(path.isWritable());
- assertTrue(link.isWritable());
+ assertThat(path.isWritable()).isTrue();
+ assertThat(link.isWritable()).isTrue();
path.setWritable(false);
- assertFalse(path.isWritable());
- assertFalse(link.isWritable());
+ assertThat(path.isWritable()).isFalse();
+ assertThat(link.isWritable()).isFalse();
}
private void validateLinkedReferenceObeysExecutable(Path path, Path link) throws IOException {
path.setExecutable(true);
- assertTrue(path.isExecutable());
- assertTrue(link.isExecutable());
+ assertThat(path.isExecutable()).isTrue();
+ assertThat(link.isExecutable()).isTrue();
path.setExecutable(false);
- assertFalse(path.isExecutable());
- assertFalse(link.isExecutable());
+ assertThat(path.isExecutable()).isFalse();
+ assertThat(link.isExecutable()).isFalse();
path.setExecutable(true);
- assertTrue(path.isExecutable());
- assertTrue(link.isExecutable());
+ assertThat(path.isExecutable()).isTrue();
+ assertThat(link.isExecutable()).isTrue();
}
@Test
@@ -700,7 +693,7 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
createSymbolicLink(link, linkedTo);
Path linkedChild = link.getChild("child");
byte[] inputData = FileSystemUtils.readContent(linkedChild);
- assertArrayEquals(outputData, inputData);
+ assertThat(inputData).isEqualTo(outputData);
}
@Test
@@ -716,6 +709,6 @@ public abstract class SymlinkAwareFileSystemTest extends FileSystemTest {
FileSystemUtils.writeContent(linkedChild, outputData);
byte[] inputData = FileSystemUtils.readContent(child);
- assertArrayEquals(outputData, inputData);
+ assertThat(inputData).isEqualTo(outputData);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/UnionFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/vfs/UnionFileSystemTest.java
index c1e793562a..2db11eb7d1 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/UnionFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/UnionFileSystemTest.java
@@ -15,12 +15,6 @@ package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableMap;
@@ -89,9 +83,9 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
Path fooPath = unionfs.getPath("/foo");
Path inPath = unionfs.getPath("/in");
Path outPath = unionfs.getPath("/out/in.txt");
- assertSame(inDelegate, unionfs.getDelegate(inPath));
- assertSame(outDelegate, unionfs.getDelegate(outPath));
- assertSame(defaultDelegate, unionfs.getDelegate(fooPath));
+ assertThat(unionfs.getDelegate(inPath)).isSameAs(inDelegate);
+ assertThat(unionfs.getDelegate(outPath)).isSameAs(outDelegate);
+ assertThat(unionfs.getDelegate(fooPath)).isSameAs(defaultDelegate);
}
@Test
@@ -100,12 +94,12 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
Path inPath = unionfs.getPath("/in");
Path outPath = unionfs.getPath("/out/in.txt");
- assertArrayEquals(XATTR_VAL.getBytes(UTF_8), inPath.getxattr(XATTR_KEY));
- assertArrayEquals(XATTR_VAL.getBytes(UTF_8), outPath.getxattr(XATTR_KEY));
- assertArrayEquals(XATTR_VAL.getBytes(UTF_8), fooPath.getxattr(XATTR_KEY));
- assertNull(inPath.getxattr("not_key"));
- assertNull(outPath.getxattr("not_key"));
- assertNull(fooPath.getxattr("not_key"));
+ assertThat(inPath.getxattr(XATTR_KEY)).isEqualTo(XATTR_VAL.getBytes(UTF_8));
+ assertThat(outPath.getxattr(XATTR_KEY)).isEqualTo(XATTR_VAL.getBytes(UTF_8));
+ assertThat(fooPath.getxattr(XATTR_KEY)).isEqualTo(XATTR_VAL.getBytes(UTF_8));
+ assertThat(inPath.getxattr("not_key")).isNull();
+ assertThat(outPath.getxattr("not_key")).isNull();
+ assertThat(fooPath.getxattr("not_key")).isNull();
}
@Test
@@ -126,20 +120,20 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
PathFragment.create("/foo"), inDelegate,
PathFragment.create("/foo/bar"), outDelegate), defaultDelegate);
- assertSame(inDelegate, unionfs.getDelegate(unionfs.getPath("/foo/foo.txt")));
- assertSame(outDelegate, unionfs.getDelegate(unionfs.getPath("/foo/bar/foo.txt")));
- assertSame(inDelegate, unionfs.getDelegate(unionfs.getPath("/foo/bar/../foo.txt")));
- assertSame(defaultDelegate, unionfs.getDelegate(unionfs.getPath("/bar/foo.txt")));
- assertSame(defaultDelegate, unionfs.getDelegate(unionfs.getPath("/foo/bar/../..")));
+ assertThat(unionfs.getDelegate(unionfs.getPath("/foo/foo.txt"))).isSameAs(inDelegate);
+ assertThat(unionfs.getDelegate(unionfs.getPath("/foo/bar/foo.txt"))).isSameAs(outDelegate);
+ assertThat(unionfs.getDelegate(unionfs.getPath("/foo/bar/../foo.txt"))).isSameAs(inDelegate);
+ assertThat(unionfs.getDelegate(unionfs.getPath("/bar/foo.txt"))).isSameAs(defaultDelegate);
+ assertThat(unionfs.getDelegate(unionfs.getPath("/foo/bar/../.."))).isSameAs(defaultDelegate);
}
// Checks that files cannot be modified when the filesystem is created
// read-only, even if the delegate filesystems are read/write.
@Test
public void testModificationFlag() throws Exception {
- assertTrue(unionfs.supportsModifications());
+ assertThat(unionfs.supportsModifications()).isTrue();
Path outPath = unionfs.getPath("/out/foo.txt");
- assertTrue(unionfs.createDirectory(outPath.getParentDirectory()));
+ assertThat(unionfs.createDirectory(outPath.getParentDirectory())).isTrue();
OutputStream outFile = unionfs.getOutputStream(outPath);
outFile.write('b');
outFile.close();
@@ -149,14 +143,14 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
// Note that this does not destroy the underlying filesystems;
// UnionFileSystem is just a view.
unionfs = createDefaultUnionFileSystem(true);
- assertFalse(unionfs.supportsModifications());
+ assertThat(unionfs.supportsModifications()).isFalse();
InputStream outFileInput = unionfs.getInputStream(outPath);
int outFileByte = outFileInput.read();
outFileInput.close();
- assertEquals('b', outFileByte);
+ assertThat(outFileByte).isEqualTo('b');
- assertTrue(unionfs.isExecutable(outPath));
+ assertThat(unionfs.isExecutable(outPath)).isTrue();
// Modifying files through the unionfs isn't permitted, even if the
// delegates are read/write.
@@ -175,9 +169,9 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
Path foo = unionfs.getPath("/foo");
Path bar = unionfs.getPath("/bar");
Path out = unionfs.getPath("/out");
- assertTrue(unionfs.createDirectory(foo));
- assertTrue(unionfs.createDirectory(bar));
- assertTrue(unionfs.createDirectory(out));
+ assertThat(unionfs.createDirectory(foo)).isTrue();
+ assertThat(unionfs.createDirectory(bar)).isTrue();
+ assertThat(unionfs.createDirectory(out)).isTrue();
Path outFile = unionfs.getPath("/out/in");
FileSystemUtils.writeContentAsLatin1(outFile, "Out");
@@ -187,41 +181,43 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
out, testDirUnderRoot);
assertThat(unionfs.getDirectoryEntries(out)).containsExactly(outFile);
- assertSame(unionfs.getDelegate(foo), defaultDelegate);
- assertEquals(foo.asFragment(), unionfs.adjustPath(foo, defaultDelegate).asFragment());
- assertSame(unionfs.getDelegate(bar), defaultDelegate);
- assertSame(unionfs.getDelegate(outFile), outDelegate);
- assertSame(unionfs.getDelegate(out), outDelegate);
+ assertThat(defaultDelegate).isSameAs(unionfs.getDelegate(foo));
+ assertThat(unionfs.adjustPath(foo, defaultDelegate).asFragment()).isEqualTo(foo.asFragment());
+ assertThat(defaultDelegate).isSameAs(unionfs.getDelegate(bar));
+ assertThat(outDelegate).isSameAs(unionfs.getDelegate(outFile));
+ assertThat(outDelegate).isSameAs(unionfs.getDelegate(out));
// As a fragment (i.e. without filesystem or root info), the path name should be preserved.
- assertEquals(outFile.asFragment(), unionfs.adjustPath(outFile, outDelegate).asFragment());
+ assertThat(unionfs.adjustPath(outFile, outDelegate).asFragment())
+ .isEqualTo(outFile.asFragment());
}
// Ensure that the right filesystem is still chosen when paths contain "..".
@Test
public void testDelegationOfUpLevelReferences() throws Exception {
- assertSame(defaultDelegate, unionfs.getDelegate(unionfs.getPath("/in/../foo.txt")));
- assertSame(inDelegate, unionfs.getDelegate(unionfs.getPath("/out/../in")));
- assertSame(outDelegate, unionfs.getDelegate(unionfs.getPath("/out/../in/../out/foo.txt")));
- assertSame(inDelegate, unionfs.getDelegate(unionfs.getPath("/in/./foo.txt")));
+ assertThat(unionfs.getDelegate(unionfs.getPath("/in/../foo.txt"))).isSameAs(defaultDelegate);
+ assertThat(unionfs.getDelegate(unionfs.getPath("/out/../in"))).isSameAs(inDelegate);
+ assertThat(unionfs.getDelegate(unionfs.getPath("/out/../in/../out/foo.txt")))
+ .isSameAs(outDelegate);
+ assertThat(unionfs.getDelegate(unionfs.getPath("/in/./foo.txt"))).isSameAs(inDelegate);
}
// Basic *explicit* cross-filesystem symlink check.
// Note: This does not work implicitly yet, as the next test illustrates.
@Test
public void testCrossDeviceSymlinks() throws Exception {
- assertTrue(unionfs.createDirectory(unionfs.getPath("/out")));
+ assertThat(unionfs.createDirectory(unionfs.getPath("/out"))).isTrue();
// Create an "/in" directory directly on the output delegate to bypass the
// UnionFileSystem's mapping.
- assertTrue(inDelegate.getPath("/in").createDirectory());
+ assertThat(inDelegate.getPath("/in").createDirectory()).isTrue();
OutputStream outStream = inDelegate.getPath("/in/bar.txt").getOutputStream();
outStream.write('i');
outStream.close();
Path outFoo = unionfs.getPath("/out/foo");
unionfs.createSymbolicLink(outFoo, PathFragment.create("../in/bar.txt"));
- assertTrue(unionfs.stat(outFoo, false).isSymbolicLink());
+ assertThat(unionfs.stat(outFoo, false).isSymbolicLink()).isTrue();
try {
unionfs.stat(outFoo, true).isFile();
@@ -231,22 +227,26 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
}
Path resolved = unionfs.resolveSymbolicLinks(outFoo);
- assertSame(unionfs, resolved.getFileSystem());
+ assertThat(resolved.getFileSystem()).isSameAs(unionfs);
InputStream barInput = resolved.getInputStream();
int barChar = barInput.read();
barInput.close();
- assertEquals('i', barChar);
+ assertThat(barChar).isEqualTo('i');
}
@Test
public void testNoDelegateLeakage() throws Exception {
- assertSame(unionfs, unionfs.getPath("/in/foo.txt").getFileSystem());
- assertSame(unionfs, unionfs.getPath("/in/foo/bar").getParentDirectory().getFileSystem());
+ assertThat(unionfs.getPath("/in/foo.txt").getFileSystem()).isSameAs(unionfs);
+ assertThat(unionfs.getPath("/in/foo/bar").getParentDirectory().getFileSystem())
+ .isSameAs(unionfs);
unionfs.createDirectory(unionfs.getPath("/out"));
unionfs.createDirectory(unionfs.getPath("/out/foo"));
unionfs.createDirectory(unionfs.getPath("/out/foo/bar"));
- assertSame(unionfs, Iterables.getOnlyElement(unionfs.getDirectoryEntries(
- unionfs.getPath("/out/foo"))).getParentDirectory().getFileSystem());
+ assertThat(
+ Iterables.getOnlyElement(unionfs.getDirectoryEntries(unionfs.getPath("/out/foo")))
+ .getParentDirectory()
+ .getFileSystem())
+ .isSameAs(unionfs);
}
// Prefix mappings can apply to files starting with a prefix within a directory.
@@ -255,30 +255,36 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
unionfs = new UnionFileSystem(ImmutableMap.<PathFragment, FileSystem>of(
PathFragment.create("/fruit/a"), inDelegate,
PathFragment.create("/fruit/b"), outDelegate), defaultDelegate);
- assertTrue(unionfs.createDirectory(unionfs.getPath("/fruit")));
- assertTrue(defaultDelegate.getPath("/fruit").isDirectory());
- assertTrue(inDelegate.getPath("/fruit").createDirectory());
- assertTrue(outDelegate.getPath("/fruit").createDirectory());
+ assertThat(unionfs.createDirectory(unionfs.getPath("/fruit"))).isTrue();
+ assertThat(defaultDelegate.getPath("/fruit").isDirectory()).isTrue();
+ assertThat(inDelegate.getPath("/fruit").createDirectory()).isTrue();
+ assertThat(outDelegate.getPath("/fruit").createDirectory()).isTrue();
Path apple = unionfs.getPath("/fruit/apple");
Path banana = unionfs.getPath("/fruit/banana");
Path cherry = unionfs.getPath("/fruit/cherry");
unionfs.createDirectory(apple);
unionfs.createDirectory(banana);
- assertSame(inDelegate, unionfs.getDelegate(apple));
- assertSame(outDelegate, unionfs.getDelegate(banana));
- assertSame(defaultDelegate, unionfs.getDelegate(cherry));
+ assertThat(unionfs.getDelegate(apple)).isSameAs(inDelegate);
+ assertThat(unionfs.getDelegate(banana)).isSameAs(outDelegate);
+ assertThat(unionfs.getDelegate(cherry)).isSameAs(defaultDelegate);
FileSystemUtils.writeContentAsLatin1(apple.getRelative("table"), "penny");
FileSystemUtils.writeContentAsLatin1(banana.getRelative("nana"), "nanana");
FileSystemUtils.writeContentAsLatin1(cherry, "garcia");
- assertEquals("penny", new String(
- FileSystemUtils.readContentAsLatin1(inDelegate.getPath("/fruit/apple/table"))));
- assertEquals("nanana", new String(
- FileSystemUtils.readContentAsLatin1(outDelegate.getPath("/fruit/banana/nana"))));
- assertEquals("garcia", new String(
- FileSystemUtils.readContentAsLatin1(defaultDelegate.getPath("/fruit/cherry"))));
+ assertThat(
+ new String(
+ FileSystemUtils.readContentAsLatin1(inDelegate.getPath("/fruit/apple/table"))))
+ .isEqualTo("penny");
+ assertThat(
+ new String(
+ FileSystemUtils.readContentAsLatin1(outDelegate.getPath("/fruit/banana/nana"))))
+ .isEqualTo("nanana");
+ assertThat(
+ new String(
+ FileSystemUtils.readContentAsLatin1(defaultDelegate.getPath("/fruit/cherry"))))
+ .isEqualTo("garcia");
}
// Write using the VFS through a UnionFileSystem and check that the file can
@@ -294,14 +300,14 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
// It would be created in setup(), but of course, that didn't use a UnixFileSystem.
unionfs.createDirectory(workingDir);
Path testFile = unionfs.getPath(workingDir.getRelative("test_file").asFragment());
- assertTrue(testFile.asFragment().startsWith(workingDir.asFragment()));
+ assertThat(testFile.asFragment().startsWith(workingDir.asFragment())).isTrue();
String testString = "This is a test file";
FileSystemUtils.writeContentAsLatin1(testFile, testString);
try {
- assertEquals(testString, new String(FileSystemUtils.readContentAsLatin1(testFile)));
+ assertThat(new String(FileSystemUtils.readContentAsLatin1(testFile))).isEqualTo(testString);
} finally {
testFile.delete();
- assertTrue(unionfs.delete(workingDir));
+ assertThat(unionfs.delete(workingDir)).isTrue();
}
}
@@ -312,7 +318,7 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
PathFragment.create("/out/dir"), outDelegate), defaultDelegate, false);
Path outDir = unionfs.getPath("/out/dir/biz/bang");
FileSystemUtils.createDirectoryAndParents(outDir);
- assertTrue(outDir.isDirectory());
+ assertThat(outDir.isDirectory()).isTrue();
}
private static class XAttrInMemoryFs extends InMemoryFileSystem {
@@ -322,7 +328,7 @@ public class UnionFileSystemTest extends SymlinkAwareFileSystemTest {
@Override
protected byte[] getxattr(Path path, String name) {
- assertSame(this, path.getFileSystem());
+ assertThat(path.getFileSystem()).isSameAs(this);
return (name.equals(XATTR_KEY)) ? XATTR_VAL.getBytes(UTF_8) : null;
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/ZipFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/vfs/ZipFileSystemTest.java
index bbe4129967..c097fc4928 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/ZipFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/ZipFileSystemTest.java
@@ -14,9 +14,6 @@
package com.google.devtools.build.lib.vfs;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.Lists;
@@ -24,18 +21,16 @@ import com.google.common.io.CharStreams;
import com.google.devtools.build.lib.testutil.BlazeTestUtils;
import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.vfs.util.FileSystems;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ZipFileSystemTest {
@@ -70,9 +65,9 @@ public class ZipFileSystemTest {
}
private void checkExists(FileSystem fs) {
- assertTrue(fs.getPath("/dir2/dir3/dir4").exists());
- assertTrue(fs.getPath("/dir2/dir3/dir4/file4").exists());
- assertFalse(fs.getPath("/dir2/dir3/dir4/bogus").exists());
+ assertThat(fs.getPath("/dir2/dir3/dir4").exists()).isTrue();
+ assertThat(fs.getPath("/dir2/dir3/dir4/file4").exists()).isTrue();
+ assertThat(fs.getPath("/dir2/dir3/dir4/bogus").exists()).isFalse();
}
@Test
@@ -82,9 +77,9 @@ public class ZipFileSystemTest {
}
private void checkIsFile(FileSystem fs) {
- assertFalse(fs.getPath("/dir2/dir3/dir4").isFile());
- assertTrue(fs.getPath("/dir2/dir3/dir4/file4").isFile());
- assertFalse(fs.getPath("/dir2/dir3/dir4/bogus").isFile());
+ assertThat(fs.getPath("/dir2/dir3/dir4").isFile()).isFalse();
+ assertThat(fs.getPath("/dir2/dir3/dir4/file4").isFile()).isTrue();
+ assertThat(fs.getPath("/dir2/dir3/dir4/bogus").isFile()).isFalse();
}
@Test
@@ -94,10 +89,10 @@ public class ZipFileSystemTest {
}
private void checkIsDir(FileSystem fs) {
- assertTrue(fs.getPath("/dir2/dir3/dir4").isDirectory());
- assertFalse(fs.getPath("/dir2/dir3/dir4/file4").isDirectory());
- assertFalse(fs.getPath("/bogus/mobogus").isDirectory());
- assertFalse(fs.getPath("/bogus").isDirectory());
+ assertThat(fs.getPath("/dir2/dir3/dir4").isDirectory()).isTrue();
+ assertThat(fs.getPath("/dir2/dir3/dir4/file4").isDirectory()).isFalse();
+ assertThat(fs.getPath("/bogus/mobogus").isDirectory()).isFalse();
+ assertThat(fs.getPath("/bogus").isDirectory()).isFalse();
}
@Test
@@ -124,7 +119,7 @@ public class ZipFileSystemTest {
List<String> list = new ArrayList<>();
listChildren(fs.getRootDirectory(), list);
Collections.sort(list);
- assertEquals(Lists.newArrayList(LISTING), list);
+ assertThat(list).isEqualTo(Lists.newArrayList(LISTING));
}
@Test
@@ -140,13 +135,13 @@ public class ZipFileSystemTest {
private void checkFileSize(FileSystem fs, String name, long expectedSize)
throws IOException {
- assertEquals(expectedSize, fs.getPath(name).getFileSize());
+ assertThat(fs.getPath(name).getFileSize()).isEqualTo(expectedSize);
}
@Test
public void testCanReadRoot() {
Path rootDirectory = zipFS1.getRootDirectory();
- assertTrue(rootDirectory.isDirectory());
+ assertThat(rootDirectory.isDirectory()).isTrue();
}
@Test
@@ -178,7 +173,7 @@ public class ZipFileSystemTest {
List<String> lines = CharStreams.readLines(new InputStreamReader(is, "ISO-8859-1"));
assertThat(lines).hasSize(expectedSize);
for (int i = 0; i < expectedSize; i++) {
- assertEquals("body", lines.get(i));
+ assertThat(lines.get(i)).isEqualTo("body");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryFileSystemTest.java
index ee4dfe937a..71f6a7c48a 100644
--- a/src/test/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryFileSystemTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.lib.vfs.inmemoryfs;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import com.google.common.collect.Lists;
import com.google.devtools.build.lib.testutil.TestThread;
@@ -26,11 +22,6 @@ import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.ScopeEscapableFileSystemTest;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -38,6 +29,9 @@ import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests for {@link InMemoryFileSystem}. Note that most tests are inherited
@@ -134,42 +128,42 @@ public class InMemoryFileSystemTest extends ScopeEscapableFileSystemTest {
@Override
public void runTest() throws Exception {
Path base = testFS.getPath("/base" + baseSelector.getAndIncrement());
- assertTrue(base.exists());
- assertFalse(base.getRelative("notreal").exists());
+ assertThat(base.exists()).isTrue();
+ assertThat(base.getRelative("notreal").exists()).isFalse();
for (int i = 0; i < NUM_TO_WRITE; i++) {
Path subdir1 = base.getRelative("subdir1_" + i);
- assertTrue(subdir1.exists());
- assertTrue(subdir1.isDirectory());
- assertTrue(subdir1.isReadable());
- assertFalse(subdir1.isWritable());
- assertFalse(subdir1.isExecutable());
- assertEquals(100, subdir1.getLastModifiedTime());
+ assertThat(subdir1.exists()).isTrue();
+ assertThat(subdir1.isDirectory()).isTrue();
+ assertThat(subdir1.isReadable()).isTrue();
+ assertThat(subdir1.isWritable()).isFalse();
+ assertThat(subdir1.isExecutable()).isFalse();
+ assertThat(subdir1.getLastModifiedTime()).isEqualTo(100);
Path subdir2 = base.getRelative("subdir2_" + i);
- assertTrue(subdir2.exists());
- assertTrue(subdir2.isDirectory());
- assertFalse(subdir2.isReadable());
- assertTrue(subdir2.isWritable());
- assertTrue(subdir2.isExecutable());
- assertEquals(200, subdir2.getLastModifiedTime());
+ assertThat(subdir2.exists()).isTrue();
+ assertThat(subdir2.isDirectory()).isTrue();
+ assertThat(subdir2.isReadable()).isFalse();
+ assertThat(subdir2.isWritable()).isTrue();
+ assertThat(subdir2.isExecutable()).isTrue();
+ assertThat(subdir2.getLastModifiedTime()).isEqualTo(200);
Path file = base.getRelative("somefile" + i);
- assertTrue(file.exists());
- assertTrue(file.isFile());
- assertTrue(file.isReadable());
- assertFalse(file.isWritable());
- assertFalse(file.isExecutable());
- assertEquals(300, file.getLastModifiedTime());
+ assertThat(file.exists()).isTrue();
+ assertThat(file.isFile()).isTrue();
+ assertThat(file.isReadable()).isTrue();
+ assertThat(file.isWritable()).isFalse();
+ assertThat(file.isExecutable()).isFalse();
+ assertThat(file.getLastModifiedTime()).isEqualTo(300);
BufferedReader reader = new BufferedReader(
new InputStreamReader(file.getInputStream(), Charset.defaultCharset()));
- assertEquals(TEST_FILE_DATA, reader.readLine());
- assertNull(reader.readLine());
+ assertThat(reader.readLine()).isEqualTo(TEST_FILE_DATA);
+ assertThat(reader.readLine()).isNull();
Path symlink = base.getRelative("symlink" + i);
- assertTrue(symlink.exists());
- assertTrue(symlink.isSymbolicLink());
- assertEquals(file.asFragment(), symlink.readSymbolicLink());
+ assertThat(symlink.exists()).isTrue();
+ assertThat(symlink.isSymbolicLink()).isTrue();
+ assertThat(symlink.readSymbolicLink()).isEqualTo(file.asFragment());
}
}
}
@@ -234,27 +228,27 @@ public class InMemoryFileSystemTest extends ScopeEscapableFileSystemTest {
public void runTest() throws Exception {
final int threadId = baseSelector.getAndIncrement();
Path base = testFS.getPath("/common_dir");
- assertTrue(base.exists());
+ assertThat(base.exists()).isTrue();
for (int i = 0; i < NUM_TO_WRITE; i++) {
Path file = base.getRelative("somefile_" + threadId + "_" + i);
- assertTrue(file.exists());
- assertTrue(file.isFile());
- assertEquals(i % 2 == 0, file.isReadable());
- assertEquals(i % 3 == 0, file.isWritable());
- assertEquals(i % 4 == 0, file.isExecutable());
- assertEquals(i, file.getLastModifiedTime());
+ assertThat(file.exists()).isTrue();
+ assertThat(file.isFile()).isTrue();
+ assertThat(file.isReadable()).isEqualTo(i % 2 == 0);
+ assertThat(file.isWritable()).isEqualTo(i % 3 == 0);
+ assertThat(file.isExecutable()).isEqualTo(i % 4 == 0);
+ assertThat(file.getLastModifiedTime()).isEqualTo(i);
if (file.isReadable()) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(file.getInputStream(), Charset.defaultCharset()));
- assertEquals(TEST_FILE_DATA, reader.readLine());
- assertNull(reader.readLine());
+ assertThat(reader.readLine()).isEqualTo(TEST_FILE_DATA);
+ assertThat(reader.readLine()).isNull();
}
Path symlink = base.getRelative("symlink_" + threadId + "_" + i);
- assertTrue(symlink.exists());
- assertTrue(symlink.isSymbolicLink());
- assertEquals(file.asFragment(), symlink.readSymbolicLink());
+ assertThat(symlink.exists()).isTrue();
+ assertThat(symlink.isSymbolicLink()).isTrue();
+ assertThat(symlink.readSymbolicLink()).isEqualTo(file.asFragment());
}
}
}
@@ -296,12 +290,12 @@ public class InMemoryFileSystemTest extends ScopeEscapableFileSystemTest {
int whichFile = baseSelector.getAndIncrement();
Path file = base.getRelative("file" + whichFile);
if (whichFile % 25 != 0) {
- assertTrue(file.delete());
+ assertThat(file.delete()).isTrue();
} else {
// Throw another concurrent access point into the mix.
file.setExecutable(whichFile % 2 == 0);
}
- assertFalse(base.getRelative("doesnotexist" + whichFile).delete());
+ assertThat(base.getRelative("doesnotexist" + whichFile).delete()).isFalse();
}
}
}
@@ -322,10 +316,10 @@ public class InMemoryFileSystemTest extends ScopeEscapableFileSystemTest {
for (int i = 0; i < NUM_TO_WRITE; i++) {
Path file = base.getRelative("file" + i);
if (i % 25 != 0) {
- assertFalse(file.exists());
+ assertThat(file.exists()).isFalse();
} else {
- assertTrue(file.exists());
- assertEquals(i % 2 == 0, file.isExecutable());
+ assertThat(file.exists()).isTrue();
+ assertThat(file.isExecutable()).isEqualTo(i % 2 == 0);
}
}
}
@@ -360,7 +354,7 @@ public class InMemoryFileSystemTest extends ScopeEscapableFileSystemTest {
// Throw another concurrent access point into the mix.
file.setExecutable(whichFile % 2 == 0);
}
- assertFalse(base.getRelative("doesnotexist" + whichFile).delete());
+ assertThat(base.getRelative("doesnotexist" + whichFile).delete()).isFalse();
}
}
}
@@ -381,11 +375,11 @@ public class InMemoryFileSystemTest extends ScopeEscapableFileSystemTest {
for (int i = 0; i < NUM_TO_WRITE; i++) {
Path file = base.getRelative("file" + i);
if (i % 25 != 0) {
- assertFalse(file.exists());
- assertTrue(base.getRelative("newname" + i).exists());
+ assertThat(file.exists()).isFalse();
+ assertThat(base.getRelative("newname" + i).exists()).isTrue();
} else {
- assertTrue(file.exists());
- assertEquals(i % 2 == 0, file.isExecutable());
+ assertThat(file.exists()).isTrue();
+ assertThat(file.isExecutable()).isEqualTo(i % 2 == 0);
}
}
}
diff --git a/src/test/java/com/google/devtools/build/skyframe/CycleDeduperTest.java b/src/test/java/com/google/devtools/build/skyframe/CycleDeduperTest.java
index 5a3f084de2..bd14fe7a69 100644
--- a/src/test/java/com/google/devtools/build/skyframe/CycleDeduperTest.java
+++ b/src/test/java/com/google/devtools/build/skyframe/CycleDeduperTest.java
@@ -13,12 +13,10 @@
// limitations under the License.
package com.google.devtools.build.skyframe;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -31,15 +29,15 @@ public class CycleDeduperTest {
@Test
public void simple() throws Exception {
- assertTrue(cycleDeduper.seen(ImmutableList.of("a", "b")));
- assertFalse(cycleDeduper.seen(ImmutableList.of("a", "b")));
- assertFalse(cycleDeduper.seen(ImmutableList.of("b", "a")));
-
- assertTrue(cycleDeduper.seen(ImmutableList.of("a", "b", "c")));
- assertFalse(cycleDeduper.seen(ImmutableList.of("b", "c", "a")));
- assertFalse(cycleDeduper.seen(ImmutableList.of("c", "a", "b")));
- assertTrue(cycleDeduper.seen(ImmutableList.of("b", "a", "c")));
- assertFalse(cycleDeduper.seen(ImmutableList.of("c", "b", "a")));
+ assertThat(cycleDeduper.seen(ImmutableList.of("a", "b"))).isTrue();
+ assertThat(cycleDeduper.seen(ImmutableList.of("a", "b"))).isFalse();
+ assertThat(cycleDeduper.seen(ImmutableList.of("b", "a"))).isFalse();
+
+ assertThat(cycleDeduper.seen(ImmutableList.of("a", "b", "c"))).isTrue();
+ assertThat(cycleDeduper.seen(ImmutableList.of("b", "c", "a"))).isFalse();
+ assertThat(cycleDeduper.seen(ImmutableList.of("c", "a", "b"))).isFalse();
+ assertThat(cycleDeduper.seen(ImmutableList.of("b", "a", "c"))).isTrue();
+ assertThat(cycleDeduper.seen(ImmutableList.of("c", "b", "a"))).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/skyframe/EagerInvalidatorTest.java b/src/test/java/com/google/devtools/build/skyframe/EagerInvalidatorTest.java
index 5c99c94420..d91e5ca187 100644
--- a/src/test/java/com/google/devtools/build/skyframe/EagerInvalidatorTest.java
+++ b/src/test/java/com/google/devtools/build/skyframe/EagerInvalidatorTest.java
@@ -16,11 +16,6 @@ package com.google.devtools.build.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.skyframe.GraphTester.CONCATENATE;
import static com.google.devtools.build.skyframe.GraphTester.NODE_TYPE;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -54,7 +49,6 @@ import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-
/**
* Tests for {@link InvalidatingNodeVisitor}.
*/
@@ -100,19 +94,19 @@ public class EagerInvalidatorTest {
private void assertChanged(SkyKey key) {
NodeEntry entry = graph.get(null, Reason.OTHER, key);
if (gcExpected()) {
- assertNull(entry);
+ assertThat(entry).isNull();
} else {
- assertTrue(entry.isChanged());
+ assertThat(entry.isChanged()).isTrue();
}
}
private void assertDirtyAndNotChanged(SkyKey key) {
NodeEntry entry = graph.get(null, Reason.OTHER, key);
if (gcExpected()) {
- assertNull(entry);
+ assertThat(entry).isNull();
} else {
- assertTrue(entry.isDirty());
- assertFalse(entry.isChanged());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isFalse();
}
}
@@ -156,7 +150,7 @@ public class EagerInvalidatorTest {
protected void invalidateWithoutError(DirtyTrackingProgressReceiver progressReceiver,
SkyKey... keys) throws InterruptedException {
invalidate(graph, progressReceiver, keys);
- assertTrue(state.isEmpty());
+ assertThat(state.isEmpty()).isTrue();
}
protected void set(String name, String value) {
@@ -164,12 +158,12 @@ public class EagerInvalidatorTest {
}
protected SkyKey skyKey(String name) {
- return GraphTester.toSkyKeys(name)[0];
+ return GraphTester.toSkyKeys(name).get(0);
}
protected void assertValueValue(String name, String expectedValue) throws InterruptedException {
StringValue value = (StringValue) eval(false, skyKey(name));
- assertEquals(expectedValue, value.getValue());
+ assertThat(value.getValue()).isEqualTo(expectedValue);
}
@Before
@@ -272,7 +266,7 @@ public class EagerInvalidatorTest {
// Not a reliable check, but better than nothing.
System.gc();
Thread.sleep(300);
- assertNotNull(weakRef.get());
+ assertThat(weakRef.get()).isNotNull();
}
}
@@ -299,8 +293,8 @@ public class EagerInvalidatorTest {
eval(false);
// The graph values should be gone.
- assertTrue(isInvalidated(skyKey("ab")));
- assertTrue(isInvalidated(skyKey("abc")));
+ assertThat(isInvalidated(skyKey("ab"))).isTrue();
+ assertThat(isInvalidated(skyKey("abc"))).isTrue();
// The reverse deps to ab and ab_c should have been removed if reverse deps are cleared.
Set<SkyKey> reverseDeps = new HashSet<>();
@@ -340,38 +334,44 @@ public class EagerInvalidatorTest {
eval(/*keepGoing=*/false, parent);
final Thread mainThread = Thread.currentThread();
final AtomicReference<SkyKey> badKey = new AtomicReference<>();
- DirtyTrackingProgressReceiver receiver = new DirtyTrackingProgressReceiver(
- new EvaluationProgressReceiver.NullEvaluationProgressReceiver() {
- @Override
- public void invalidated(SkyKey skyKey, InvalidationState state) {
- if (skyKey.equals(child)) {
- // Interrupt on the very first invalidate
- mainThread.interrupt();
- } else if (!skyKey.functionName().equals(NODE_TYPE)) {
- // All other invalidations should have the GraphTester's key type.
- // Exceptions thrown here may be silently dropped, so keep track of errors ourselves.
- badKey.set(skyKey);
- }
- try {
- assertTrue(
- visitor.get().getInterruptionLatchForTestingOnly().await(2, TimeUnit.HOURS));
- } catch (InterruptedException e) {
- // We may well have thrown here because by the time we try to await, the main
- // thread is already interrupted.
- }
- }
- });
+ DirtyTrackingProgressReceiver receiver =
+ new DirtyTrackingProgressReceiver(
+ new EvaluationProgressReceiver.NullEvaluationProgressReceiver() {
+ @Override
+ public void invalidated(SkyKey skyKey, InvalidationState state) {
+ if (skyKey.equals(child)) {
+ // Interrupt on the very first invalidate
+ mainThread.interrupt();
+ } else if (!skyKey.functionName().equals(NODE_TYPE)) {
+ // All other invalidations should have the GraphTester's key type.
+ // Exceptions thrown here may be silently dropped, so keep track of errors
+ // ourselves.
+ badKey.set(skyKey);
+ }
+ try {
+ assertThat(
+ visitor
+ .get()
+ .getInterruptionLatchForTestingOnly()
+ .await(2, TimeUnit.HOURS))
+ .isTrue();
+ } catch (InterruptedException e) {
+ // We may well have thrown here because by the time we try to await, the main
+ // thread is already interrupted.
+ }
+ }
+ });
try {
invalidateWithoutError(receiver, child);
fail();
} catch (InterruptedException e) {
// Expected.
}
- assertNull(badKey.get());
- assertFalse(state.isEmpty());
+ assertThat(badKey.get()).isNull();
+ assertThat(state.isEmpty()).isFalse();
final Set<SkyKey> invalidated = Sets.newConcurrentHashSet();
- assertFalse(isInvalidated(parent));
- assertNotNull(graph.get(null, Reason.OTHER, parent).getValue());
+ assertThat(isInvalidated(parent)).isFalse();
+ assertThat(graph.get(null, Reason.OTHER, parent).getValue()).isNotNull();
receiver = new DirtyTrackingProgressReceiver(
new EvaluationProgressReceiver.NullEvaluationProgressReceiver() {
@Override
@@ -380,12 +380,12 @@ public class EagerInvalidatorTest {
}
});
invalidateWithoutError(receiver);
- assertTrue(invalidated.contains(parent));
+ assertThat(invalidated).contains(parent);
assertThat(state.getInvalidationsForTesting()).isEmpty();
// Regression test coverage:
// "all pending values are marked changed on interrupt".
- assertTrue(isInvalidated(child));
+ assertThat(isInvalidated(child)).isTrue();
assertChanged(child);
for (int i = 1; i < numValues; i++) {
assertDirtyAndNotChanged(family[i]);
diff --git a/src/test/java/com/google/devtools/build/skyframe/ErrorInfoTest.java b/src/test/java/com/google/devtools/build/skyframe/ErrorInfoTest.java
index e88d73ebee..6dbeede700 100644
--- a/src/test/java/com/google/devtools/build/skyframe/ErrorInfoTest.java
+++ b/src/test/java/com/google/devtools/build/skyframe/ErrorInfoTest.java
@@ -174,7 +174,8 @@ public class ErrorInfoTest {
false);
} catch (IllegalStateException e) {
// Brittle, but confirms we failed for the right reason.
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.startsWith("exception and rootCauseOfException must both be null or non-null");
}
}
diff --git a/src/test/java/com/google/devtools/build/skyframe/GraphTest.java b/src/test/java/com/google/devtools/build/skyframe/GraphTest.java
index 84016d7953..d66639bb0f 100644
--- a/src/test/java/com/google/devtools/build/skyframe/GraphTest.java
+++ b/src/test/java/com/google/devtools/build/skyframe/GraphTest.java
@@ -14,10 +14,6 @@
package com.google.devtools.build.skyframe;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -176,7 +172,8 @@ public abstract class GraphTest {
final CountDownLatch waitForSetValue = new CountDownLatch(1);
ExecutorService pool = Executors.newFixedThreadPool(numThreads);
// Add single rdep before transition to done.
- assertEquals(DependencyState.NEEDS_SCHEDULING, entry.addReverseDepAndCheckIfDone(key("rdep")));
+ assertThat(entry.addReverseDepAndCheckIfDone(key("rdep")))
+ .isEqualTo(DependencyState.NEEDS_SCHEDULING);
List<SkyKey> rdepKeys = new ArrayList<>();
for (int i = 0; i < numKeys; i++) {
rdepKeys.add(key("rdep" + i));
@@ -211,11 +208,10 @@ public abstract class GraphTest {
entry.setValue(new StringValue("foo1"), startingVersion);
waitForSetValue.countDown();
wrapper.waitForTasksAndMaybeThrow();
- assertFalse(ExecutorUtil.interruptibleShutdown(pool));
- assertEquals(new StringValue("foo1"), graph.get(null, Reason.OTHER, key).getValue());
- assertEquals(
- numKeys + 1,
- Iterables.size(graph.get(null, Reason.OTHER, key).getReverseDepsForDoneEntry()));
+ assertThat(ExecutorUtil.interruptibleShutdown(pool)).isFalse();
+ assertThat(graph.get(null, Reason.OTHER, key).getValue()).isEqualTo(new StringValue("foo1"));
+ assertThat(graph.get(null, Reason.OTHER, key).getReverseDepsForDoneEntry())
+ .hasSize(numKeys + 1);
graph = getGraph(getNextVersion(startingVersion));
NodeEntry sameEntry = Preconditions.checkNotNull(graph.get(null, Reason.OTHER, key));
@@ -224,10 +220,9 @@ public abstract class GraphTest {
startEvaluation(sameEntry);
sameEntry.markRebuilding();
sameEntry.setValue(new StringValue("foo2"), getNextVersion(startingVersion));
- assertEquals(new StringValue("foo2"), graph.get(null, Reason.OTHER, key).getValue());
- assertEquals(
- numKeys + 1,
- Iterables.size(graph.get(null, Reason.OTHER, key).getReverseDepsForDoneEntry()));
+ assertThat(graph.get(null, Reason.OTHER, key).getValue()).isEqualTo(new StringValue("foo2"));
+ assertThat(graph.get(null, Reason.OTHER, key).getReverseDepsForDoneEntry())
+ .hasSize(numKeys + 1);
}
// Tests adding inflight nodes with a given key while an existing node with the same key
@@ -276,7 +271,7 @@ public abstract class GraphTest {
// NEEDS_SCHEDULING at most once.
try {
if (startEvaluation(entry).equals(DependencyState.NEEDS_SCHEDULING)) {
- assertTrue(valuesSet.add(key));
+ assertThat(valuesSet.add(key)).isTrue();
// Set to done.
entry.setValue(new StringValue("bar" + keyNum), startingVersion);
assertThat(entry.isDone()).isTrue();
@@ -298,12 +293,12 @@ public abstract class GraphTest {
}
}
wrapper.waitForTasksAndMaybeThrow();
- assertFalse(ExecutorUtil.interruptibleShutdown(pool));
+ assertThat(ExecutorUtil.interruptibleShutdown(pool)).isFalse();
// Check that all the values are as expected.
for (int i = 0; i < numKeys; i++) {
SkyKey key = key("foo" + i);
- assertTrue(nodeCreated.contains(key));
- assertTrue(valuesSet.contains(key));
+ assertThat(nodeCreated).contains(key);
+ assertThat(valuesSet).contains(key);
assertThat(graph.get(null, Reason.OTHER, key).getValue())
.isEqualTo(new StringValue("bar" + i));
assertThat(graph.get(null, Reason.OTHER, key).getVersion()).isEqualTo(startingVersion);
@@ -331,9 +326,9 @@ public abstract class GraphTest {
entry.setValue(new StringValue("bar"), startingVersion);
}
- assertNotNull(graph.get(null, Reason.OTHER, key("foo" + 0)));
+ assertThat(graph.get(null, Reason.OTHER, key("foo" + 0))).isNotNull();
graph = getGraph(getNextVersion(startingVersion));
- assertNotNull(graph.get(null, Reason.OTHER, key("foo" + 0)));
+ assertThat(graph.get(null, Reason.OTHER, key("foo" + 0))).isNotNull();
ExecutorService pool1 = Executors.newFixedThreadPool(numThreads);
ExecutorService pool2 = Executors.newFixedThreadPool(numThreads);
ExecutorService pool3 = Executors.newFixedThreadPool(numThreads);
@@ -396,7 +391,7 @@ public abstract class GraphTest {
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
- assertNotNull(entry);
+ assertThat(entry).isNotNull();
// Requests for the value are made at the same time that the version increments from
// the base. Check that there is no problem in requesting the version and that the
// number is sane.
@@ -448,18 +443,18 @@ public abstract class GraphTest {
pool3.execute(wrapper.wrap(r3));
}
wrapper.waitForTasksAndMaybeThrow();
- assertFalse(ExecutorUtil.interruptibleShutdown(pool1));
- assertFalse(ExecutorUtil.interruptibleShutdown(pool2));
- assertFalse(ExecutorUtil.interruptibleShutdown(pool3));
+ assertThat(ExecutorUtil.interruptibleShutdown(pool1)).isFalse();
+ assertThat(ExecutorUtil.interruptibleShutdown(pool2)).isFalse();
+ assertThat(ExecutorUtil.interruptibleShutdown(pool3)).isFalse();
for (int i = 0; i < numKeys; i++) {
NodeEntry entry = graph.get(null, Reason.OTHER, key("foo" + i));
assertThat(entry.getValue()).isEqualTo(new StringValue("bar" + i));
assertThat(entry.getVersion()).isEqualTo(getNextVersion(startingVersion));
for (SkyKey key : entry.getReverseDepsForDoneEntry()) {
- assertEquals(key("rdep"), key);
+ assertThat(key).isEqualTo(key("rdep"));
}
for (SkyKey key : entry.getDirectDeps()) {
- assertEquals(key("dep"), key);
+ assertThat(key).isEqualTo(key("dep"));
}
}
}
diff --git a/src/test/java/com/google/devtools/build/skyframe/GraphTester.java b/src/test/java/com/google/devtools/build/skyframe/GraphTester.java
index f643783b29..455a36ec44 100644
--- a/src/test/java/com/google/devtools/build/skyframe/GraphTester.java
+++ b/src/test/java/com/google/devtools/build/skyframe/GraphTester.java
@@ -15,6 +15,7 @@ package com.google.devtools.build.skyframe;
import static com.google.common.truth.Truth.assertThat;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@@ -261,16 +262,16 @@ public class GraphTester {
}
- public static SkyKey[] toSkyKeys(String... names) {
- SkyKey[] result = new SkyKey[names.length];
+ public static ImmutableList<SkyKey> toSkyKeys(String... names) {
+ ImmutableList.Builder<SkyKey> result = ImmutableList.builder();
for (int i = 0; i < names.length; i++) {
- result[i] = LegacySkyKey.create(GraphTester.NODE_TYPE, names[i]);
+ result.add(LegacySkyKey.create(GraphTester.NODE_TYPE, names[i]));
}
- return result;
+ return result.build();
}
public static SkyKey toSkyKey(String name) {
- return toSkyKeys(name)[0];
+ return toSkyKeys(name).get(0);
}
private class DelegatingFunction implements SkyFunction {
diff --git a/src/test/java/com/google/devtools/build/skyframe/InMemoryNodeEntryTest.java b/src/test/java/com/google/devtools/build/skyframe/InMemoryNodeEntryTest.java
index 37f3ba9f5f..a39dd10fb7 100644
--- a/src/test/java/com/google/devtools/build/skyframe/InMemoryNodeEntryTest.java
+++ b/src/test/java/com/google/devtools/build/skyframe/InMemoryNodeEntryTest.java
@@ -14,11 +14,8 @@
package com.google.devtools.build.skyframe;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.skyframe.NodeEntrySubjectFactory.assertThatNodeEntry;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
@@ -58,10 +55,10 @@ public class InMemoryNodeEntryTest {
public void createEntry() {
InMemoryNodeEntry entry = new InMemoryNodeEntry();
entry.addReverseDepAndCheckIfDone(null); // Start evaluation.
- assertFalse(entry.isDone());
- assertTrue(entry.isReady());
- assertFalse(entry.isDirty());
- assertFalse(entry.isChanged());
+ assertThat(entry.isDone()).isFalse();
+ assertThat(entry.isReady()).isTrue();
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isChanged()).isFalse();
assertThat(entry.getTemporaryDirectDeps()).isEmpty();
}
@@ -71,23 +68,23 @@ public class InMemoryNodeEntryTest {
entry.addReverseDepAndCheckIfDone(null); // Start evaluation.
SkyKey dep1 = key("dep1");
addTemporaryDirectDep(entry, dep1);
- assertFalse(entry.isReady());
- assertTrue(entry.signalDep());
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isFalse();
+ assertThat(entry.signalDep()).isTrue();
+ assertThat(entry.isReady()).isTrue();
assertThatNodeEntry(entry).hasTemporaryDirectDepsThat().containsExactly(dep1);
SkyKey dep2 = key("dep2");
SkyKey dep3 = key("dep3");
addTemporaryDirectDep(entry, dep2);
addTemporaryDirectDep(entry, dep3);
- assertFalse(entry.isReady());
- assertFalse(entry.signalDep());
- assertFalse(entry.isReady());
- assertTrue(entry.signalDep());
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isFalse();
+ assertThat(entry.signalDep()).isFalse();
+ assertThat(entry.isReady()).isFalse();
+ assertThat(entry.signalDep()).isTrue();
+ assertThat(entry.isReady()).isTrue();
assertThat(setValue(entry, new SkyValue() {},
/*errorInfo=*/null, /*graphVersion=*/0L)).isEmpty();
- assertTrue(entry.isDone());
- assertEquals(IntVersion.of(0L), entry.getVersion());
+ assertThat(entry.isDone()).isTrue();
+ assertThat(entry.getVersion()).isEqualTo(IntVersion.of(0L));
assertThat(entry.getDirectDeps()).containsExactly(dep1, dep2, dep3);
}
@@ -96,15 +93,18 @@ public class InMemoryNodeEntryTest {
NodeEntry entry = new InMemoryNodeEntry();
SkyKey mother = key("mother");
SkyKey father = key("father");
- assertEquals(DependencyState.NEEDS_SCHEDULING, entry.addReverseDepAndCheckIfDone(mother));
- assertEquals(DependencyState.ALREADY_EVALUATING, entry.addReverseDepAndCheckIfDone(null));
- assertEquals(DependencyState.ALREADY_EVALUATING, entry.addReverseDepAndCheckIfDone(father));
+ assertThat(entry.addReverseDepAndCheckIfDone(mother))
+ .isEqualTo(DependencyState.NEEDS_SCHEDULING);
+ assertThat(entry.addReverseDepAndCheckIfDone(null))
+ .isEqualTo(DependencyState.ALREADY_EVALUATING);
+ assertThat(entry.addReverseDepAndCheckIfDone(father))
+ .isEqualTo(DependencyState.ALREADY_EVALUATING);
assertThat(setValue(entry, new SkyValue() {},
/*errorInfo=*/null, /*graphVersion=*/0L)).containsExactly(mother, father);
assertThat(entry.getReverseDepsForDoneEntry()).containsExactly(mother, father);
- assertTrue(entry.isDone());
+ assertThat(entry.isDone()).isTrue();
entry.removeReverseDep(mother);
- assertFalse(Iterables.contains(entry.getReverseDepsForDoneEntry(), mother));
+ assertThat(entry.getReverseDepsForDoneEntry()).doesNotContain(mother);
}
@Test
@@ -116,9 +116,9 @@ public class InMemoryNodeEntryTest {
key("cause"));
ErrorInfo errorInfo = ErrorInfo.fromException(exception, false);
assertThat(setValue(entry, /*value=*/null, errorInfo, /*graphVersion=*/0L)).isEmpty();
- assertTrue(entry.isDone());
- assertNull(entry.getValue());
- assertEquals(errorInfo, entry.getErrorInfo());
+ assertThat(entry.isDone()).isTrue();
+ assertThat(entry.getValue()).isNull();
+ assertThat(entry.getErrorInfo()).isEqualTo(errorInfo);
}
@Test
@@ -130,8 +130,8 @@ public class InMemoryNodeEntryTest {
key("cause"));
ErrorInfo errorInfo = ErrorInfo.fromException(exception, false);
setValue(entry, new SkyValue() {}, errorInfo, /*graphVersion=*/0L);
- assertTrue(entry.isDone());
- assertEquals(errorInfo, entry.getErrorInfo());
+ assertThat(entry.isDone()).isTrue();
+ assertThat(entry.getErrorInfo()).isEqualTo(errorInfo);
}
@Test
@@ -180,25 +180,25 @@ public class InMemoryNodeEntryTest {
addTemporaryDirectDep(entry, dep);
entry.signalDep();
setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L);
- assertFalse(entry.isDirty());
- assertTrue(entry.isDone());
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isDone()).isTrue();
entry.markDirty(/*isChanged=*/false);
- assertTrue(entry.isDirty());
- assertFalse(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isFalse();
+ assertThat(entry.isDone()).isFalse();
assertThatNodeEntry(entry)
.addReverseDepAndCheckIfDone(null)
.isEqualTo(DependencyState.NEEDS_SCHEDULING);
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isTrue();
assertThat(entry.getTemporaryDirectDeps()).isEmpty();
SkyKey parent = key("parent");
entry.addReverseDepAndCheckIfDone(parent);
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep);
addTemporaryDirectDep(entry, dep);
entry.signalDep();
assertThatNodeEntry(entry).hasTemporaryDirectDepsThat().containsExactly(dep);
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isTrue();
entry.markRebuilding();
assertThat(setValue(entry, new SkyValue() {}, /*errorInfo=*/null,
/*graphVersion=*/1L)).containsExactly(parent);
@@ -212,25 +212,25 @@ public class InMemoryNodeEntryTest {
addTemporaryDirectDep(entry, dep);
entry.signalDep();
setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L);
- assertFalse(entry.isDirty());
- assertTrue(entry.isDone());
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isDone()).isTrue();
entry.markDirty(/*isChanged=*/true);
- assertTrue(entry.isDirty());
- assertTrue(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isTrue();
+ assertThat(entry.isDone()).isFalse();
assertThatNodeEntry(entry)
.addReverseDepAndCheckIfDone(null)
.isEqualTo(DependencyState.NEEDS_SCHEDULING);
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isTrue();
SkyKey parent = key("parent");
entry.addReverseDepAndCheckIfDone(parent);
- assertEquals(NodeEntry.DirtyState.NEEDS_REBUILDING, entry.getDirtyState());
- assertTrue(entry.isReady());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.NEEDS_REBUILDING);
+ assertThat(entry.isReady()).isTrue();
assertThat(entry.getTemporaryDirectDeps()).isEmpty();
entry.markRebuilding();
assertThat(setValue(entry, new SkyValue() {}, /*errorInfo=*/null,
/*graphVersion=*/1L)).containsExactly(parent);
- assertEquals(IntVersion.of(1L), entry.getVersion());
+ assertThat(entry.getVersion()).isEqualTo(IntVersion.of(1L));
}
@Test
@@ -240,20 +240,20 @@ public class InMemoryNodeEntryTest {
addTemporaryDirectDep(entry, key("dep"));
entry.signalDep();
setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L);
- assertFalse(entry.isDirty());
- assertTrue(entry.isDone());
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isDone()).isTrue();
entry.markDirty(/*isChanged=*/false);
- assertTrue(entry.isDirty());
- assertFalse(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isFalse();
+ assertThat(entry.isDone()).isFalse();
entry.markDirty(/*isChanged=*/true);
- assertTrue(entry.isDirty());
- assertTrue(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isTrue();
+ assertThat(entry.isDone()).isFalse();
assertThatNodeEntry(entry)
.addReverseDepAndCheckIfDone(null)
.isEqualTo(DependencyState.NEEDS_SCHEDULING);
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isTrue();
}
@@ -264,20 +264,20 @@ public class InMemoryNodeEntryTest {
addTemporaryDirectDep(entry, key("dep"));
entry.signalDep();
setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L);
- assertFalse(entry.isDirty());
- assertTrue(entry.isDone());
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isDone()).isTrue();
entry.markDirty(/*isChanged=*/true);
- assertTrue(entry.isDirty());
- assertTrue(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isTrue();
+ assertThat(entry.isDone()).isFalse();
entry.markDirty(/*isChanged=*/false);
- assertTrue(entry.isDirty());
- assertTrue(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isTrue();
+ assertThat(entry.isDone()).isFalse();
assertThatNodeEntry(entry)
.addReverseDepAndCheckIfDone(null)
.isEqualTo(DependencyState.NEEDS_SCHEDULING);
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isTrue();
}
@Test
@@ -285,8 +285,8 @@ public class InMemoryNodeEntryTest {
NodeEntry entry = new InMemoryNodeEntry();
entry.addReverseDepAndCheckIfDone(null); // Start evaluation.
setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L);
- assertFalse(entry.isDirty());
- assertTrue(entry.isDone());
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isDone()).isTrue();
entry.markDirty(/*isChanged=*/true);
try {
entry.markDirty(/*isChanged=*/true);
@@ -316,14 +316,15 @@ public class InMemoryNodeEntryTest {
public void crashOnAddReverseDepTwice() throws InterruptedException {
NodeEntry entry = new InMemoryNodeEntry();
SkyKey parent = key("parent");
- assertEquals(DependencyState.NEEDS_SCHEDULING, entry.addReverseDepAndCheckIfDone(parent));
+ assertThat(entry.addReverseDepAndCheckIfDone(parent))
+ .isEqualTo(DependencyState.NEEDS_SCHEDULING);
try {
entry.addReverseDepAndCheckIfDone(parent);
assertThat(setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L))
.containsExactly(parent);
fail("Cannot add same dep twice");
} catch (IllegalStateException e) {
- assertThat(e.getMessage()).contains("Duplicate reverse deps");
+ assertThat(e).hasMessageThat().contains("Duplicate reverse deps");
}
}
@@ -333,7 +334,7 @@ public class InMemoryNodeEntryTest {
entry.addReverseDepAndCheckIfDone(null); // Start evaluation.
setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L);
SkyKey parent = key("parent");
- assertEquals(DependencyState.DONE, entry.addReverseDepAndCheckIfDone(parent));
+ assertThat(entry.addReverseDepAndCheckIfDone(parent)).isEqualTo(DependencyState.DONE);
try {
entry.addReverseDepAndCheckIfDone(parent);
// We only check for duplicates when we request all the reverse deps.
@@ -348,7 +349,8 @@ public class InMemoryNodeEntryTest {
public void crashOnAddReverseDepBeforeAfterDone() throws InterruptedException {
NodeEntry entry = new InMemoryNodeEntry();
SkyKey parent = key("parent");
- assertEquals(DependencyState.NEEDS_SCHEDULING, entry.addReverseDepAndCheckIfDone(parent));
+ assertThat(entry.addReverseDepAndCheckIfDone(parent))
+ .isEqualTo(DependencyState.NEEDS_SCHEDULING);
setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L);
try {
entry.addReverseDepAndCheckIfDone(parent);
@@ -368,26 +370,26 @@ public class InMemoryNodeEntryTest {
addTemporaryDirectDep(entry, dep);
entry.signalDep();
setValue(entry, new SkyValue() {}, /*errorInfo=*/null, /*graphVersion=*/0L);
- assertFalse(entry.isDirty());
- assertTrue(entry.isDone());
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isDone()).isTrue();
entry.markDirty(/*isChanged=*/false);
- assertTrue(entry.isDirty());
- assertFalse(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isFalse();
+ assertThat(entry.isDone()).isFalse();
assertThatNodeEntry(entry)
.addReverseDepAndCheckIfDone(null)
.isEqualTo(DependencyState.NEEDS_SCHEDULING);
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isTrue();
SkyKey parent = key("parent");
entry.addReverseDepAndCheckIfDone(parent);
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep);
addTemporaryDirectDep(entry, dep);
entry.signalDep(IntVersion.of(0L));
- assertEquals(NodeEntry.DirtyState.VERIFIED_CLEAN, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.VERIFIED_CLEAN);
assertThat(entry.markClean()).containsExactly(parent);
- assertTrue(entry.isDone());
- assertEquals(IntVersion.of(0L), entry.getVersion());
+ assertThat(entry.isDone()).isTrue();
+ assertThat(entry.getVersion()).isEqualTo(IntVersion.of(0L));
}
private static class IntegerValue implements SkyValue {
@@ -418,17 +420,17 @@ public class InMemoryNodeEntryTest {
setValue(entry, new IntegerValue(5), /*errorInfo=*/null, /*graphVersion=*/0L);
entry.markDirty(/*isChanged=*/false);
entry.addReverseDepAndCheckIfDone(null); // Start evaluation.
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
entry.addReverseDepAndCheckIfDone(null); // Start evaluation.
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep);
addTemporaryDirectDep(entry, dep);
entry.signalDep(IntVersion.of(1L));
- assertEquals(NodeEntry.DirtyState.NEEDS_REBUILDING, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.NEEDS_REBUILDING);
assertThatNodeEntry(entry).hasTemporaryDirectDepsThat().containsExactly(dep);
entry.markRebuilding();
setValue(entry, new IntegerValue(5), /*errorInfo=*/null, /*graphVersion=*/1L);
- assertTrue(entry.isDone());
- assertEquals(IntVersion.of(0L), entry.getVersion());
+ assertThat(entry.isDone()).isTrue();
+ assertThat(entry.getVersion()).isEqualTo(IntVersion.of(0L));
}
@Test
@@ -439,23 +441,23 @@ public class InMemoryNodeEntryTest {
addTemporaryDirectDep(entry, dep);
entry.signalDep();
setValue(entry, new IntegerValue(5), /*errorInfo=*/null, /*graphVersion=*/0L);
- assertFalse(entry.isDirty());
- assertTrue(entry.isDone());
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isDone()).isTrue();
entry.markDirty(/*isChanged=*/false);
- assertTrue(entry.isDirty());
- assertFalse(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isFalse();
+ assertThat(entry.isDone()).isFalse();
assertThatNodeEntry(entry)
.addReverseDepAndCheckIfDone(null)
.isEqualTo(DependencyState.NEEDS_SCHEDULING);
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isTrue();
SkyKey parent = key("parent");
entry.addReverseDepAndCheckIfDone(parent);
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep);
addTemporaryDirectDep(entry, dep);
entry.signalDep(IntVersion.of(1L));
- assertEquals(NodeEntry.DirtyState.NEEDS_REBUILDING, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.NEEDS_REBUILDING);
assertThatNodeEntry(entry).hasTemporaryDirectDepsThat().containsExactly(dep);
ReifiedSkyFunctionException exception = new ReifiedSkyFunctionException(
new GenericFunctionException(new SomeErrorException("oops"), Transience.PERSISTENT),
@@ -463,8 +465,10 @@ public class InMemoryNodeEntryTest {
entry.markRebuilding();
setValue(entry, new IntegerValue(5), ErrorInfo.fromException(exception, false),
/*graphVersion=*/1L);
- assertTrue(entry.isDone());
- assertEquals("Version increments when setValue changes", IntVersion.of(1), entry.getVersion());
+ assertThat(entry.isDone()).isTrue();
+ assertWithMessage("Version increments when setValue changes")
+ .that(entry.getVersion())
+ .isEqualTo(IntVersion.of(1));
}
@Test
@@ -480,31 +484,32 @@ public class InMemoryNodeEntryTest {
entry.signalDep();
entry.signalDep();
setValue(entry, new IntegerValue(5), /*errorInfo=*/ null, /*graphVersion=*/ 0L);
- assertFalse(entry.isDirty());
- assertTrue(entry.isDone());
+ assertThat(entry.isDirty()).isFalse();
+ assertThat(entry.isDone()).isTrue();
entry.markDirty(/*isChanged=*/ false);
- assertTrue(entry.isDirty());
- assertFalse(entry.isChanged());
- assertFalse(entry.isDone());
+ assertThat(entry.isDirty()).isTrue();
+ assertThat(entry.isChanged()).isFalse();
+ assertThat(entry.isDone()).isFalse();
assertThatNodeEntry(entry)
.addReverseDepAndCheckIfDone(null)
.isEqualTo(DependencyState.NEEDS_SCHEDULING);
- assertTrue(entry.isReady());
+ assertThat(entry.isReady()).isTrue();
entry.addReverseDepAndCheckIfDone(null);
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep);
addTemporaryDirectDep(entry, dep);
entry.signalDep(IntVersion.of(1L));
- assertEquals(NodeEntry.DirtyState.NEEDS_REBUILDING, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.NEEDS_REBUILDING);
assertThatNodeEntry(entry).hasTemporaryDirectDepsThat().containsExactly(dep);
entry.markRebuilding();
addTemporaryDirectDeps(entry, dep2InGroup, dep1InGroup);
- assertFalse(entry.signalDep());
- assertTrue(entry.signalDep());
+ assertThat(entry.signalDep()).isFalse();
+ assertThat(entry.signalDep()).isTrue();
setValue(entry, new IntegerValue(5), /*errorInfo=*/ null, /*graphVersion=*/ 1L);
- assertTrue(entry.isDone());
- assertEquals(
- "Version does not change when dep group reordered", IntVersion.of(0), entry.getVersion());
+ assertThat(entry.isDone()).isTrue();
+ assertWithMessage("Version does not change when dep group reordered")
+ .that(entry.getVersion())
+ .isEqualTo(IntVersion.of(0));
}
@Test
@@ -521,17 +526,17 @@ public class InMemoryNodeEntryTest {
setValue(entry, /*value=*/null, errorInfo, /*graphVersion=*/0L);
entry.markDirty(/*isChanged=*/false);
entry.addReverseDepAndCheckIfDone(null); // Restart evaluation.
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep);
addTemporaryDirectDep(entry, dep);
entry.signalDep(IntVersion.of(1L));
- assertEquals(NodeEntry.DirtyState.NEEDS_REBUILDING, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.NEEDS_REBUILDING);
assertThatNodeEntry(entry).hasTemporaryDirectDepsThat().containsExactly(dep);
entry.markRebuilding();
setValue(entry, /*value=*/null, errorInfo, /*graphVersion=*/1L);
- assertTrue(entry.isDone());
+ assertThat(entry.isDone()).isTrue();
// ErrorInfo is treated as a NotComparableSkyValue, so it is not pruned.
- assertEquals(IntVersion.of(1L), entry.getVersion());
+ assertThat(entry.getVersion()).isEqualTo(IntVersion.of(1L));
}
@Test
@@ -549,12 +554,12 @@ public class InMemoryNodeEntryTest {
setValue(entry, /*value=*/new IntegerValue(5), null, 0L);
entry.markDirty(/*isChanged=*/false);
entry.addReverseDepAndCheckIfDone(null); // Restart evaluation.
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep, dep2);
addTemporaryDirectDeps(entry, dep, dep2);
entry.signalDep(IntVersion.of(0L));
entry.signalDep(IntVersion.of(0L));
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep3);
}
@@ -580,11 +585,11 @@ public class InMemoryNodeEntryTest {
setValue(entry, null, ErrorInfo.fromException(exception, false), 0L);
entry.markDirty(/*isChanged=*/false);
entry.addReverseDepAndCheckIfDone(null); // Restart evaluation.
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep);
addTemporaryDirectDep(entry, dep);
entry.signalDep(IntVersion.of(0L));
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep4);
}
@@ -598,17 +603,17 @@ public class InMemoryNodeEntryTest {
setValue(entry, new IntegerValue(5), /*errorInfo=*/null, /*graphVersion=*/0L);
entry.markDirty(/*isChanged=*/false);
entry.addReverseDepAndCheckIfDone(null); // Start evaluation.
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(dep);
addTemporaryDirectDep(entry, dep);
- assertTrue(entry.signalDep(IntVersion.of(1L)));
- assertEquals(NodeEntry.DirtyState.NEEDS_REBUILDING, entry.getDirtyState());
+ assertThat(entry.signalDep(IntVersion.of(1L))).isTrue();
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.NEEDS_REBUILDING);
assertThatNodeEntry(entry).hasTemporaryDirectDepsThat().containsExactly(dep);
entry.markRebuilding();
addTemporaryDirectDep(entry, key("dep2"));
- assertTrue(entry.signalDep(IntVersion.of(1L)));
+ assertThat(entry.signalDep(IntVersion.of(1L))).isTrue();
setValue(entry, new IntegerValue(5), /*errorInfo=*/null, /*graphVersion=*/1L);
- assertTrue(entry.isDone());
+ assertThat(entry.isDone()).isTrue();
assertThatNodeEntry(entry).hasVersionThat().isEqualTo(IntVersion.of(0L));
}
@@ -626,15 +631,15 @@ public class InMemoryNodeEntryTest {
setValue(entry, new IntegerValue(5), /*errorInfo=*/null, /*graphVersion=*/0L);
entry.markDirty(/*isChanged=*/false);
entry.addReverseDepAndCheckIfDone(null); // Start new evaluation.
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
for (int ii = 0; ii < 10; ii++) {
assertThat(entry.getNextDirtyDirectDeps()).containsExactly(deps.get(ii));
addTemporaryDirectDep(entry, deps.get(ii));
- assertTrue(entry.signalDep(IntVersion.of(0L)));
+ assertThat(entry.signalDep(IntVersion.of(0L))).isTrue();
if (ii < 9) {
- assertEquals(NodeEntry.DirtyState.CHECK_DEPENDENCIES, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.CHECK_DEPENDENCIES);
} else {
- assertEquals(NodeEntry.DirtyState.VERIFIED_CLEAN, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.VERIFIED_CLEAN);
}
}
}
@@ -647,7 +652,7 @@ public class InMemoryNodeEntryTest {
entry.markDirty(/*isChanged=*/true);
SkyKey newParent = key("new parent");
entry.addReverseDepAndCheckIfDone(newParent);
- assertEquals(NodeEntry.DirtyState.NEEDS_REBUILDING, entry.getDirtyState());
+ assertThat(entry.getDirtyState()).isEqualTo(NodeEntry.DirtyState.NEEDS_REBUILDING);
entry.markRebuilding();
assertThat(setValue(entry, new SkyValue() {}, /*errorInfo=*/null,
/*graphVersion=*/1L)).containsExactly(newParent);
@@ -692,7 +697,7 @@ public class InMemoryNodeEntryTest {
assertThat(clone1.getDirectDeps()).containsExactly(originalChild);
assertThat(clone2.getDirectDeps()).containsExactly(newChild);
- assertThat(entry.getReverseDepsForDoneEntry()).hasSize(0);
+ assertThat(entry.getReverseDepsForDoneEntry()).isEmpty();
assertThat(clone1.getReverseDepsForDoneEntry()).containsExactly(key("parent1"));
assertThat(clone2.getReverseDepsForDoneEntry()).containsExactly(key("parent1"), key("parent2"));
}
diff --git a/src/test/java/com/google/devtools/build/skyframe/MemoizingEvaluatorTest.java b/src/test/java/com/google/devtools/build/skyframe/MemoizingEvaluatorTest.java
index a480d68b69..697e2ac150 100644
--- a/src/test/java/com/google/devtools/build/skyframe/MemoizingEvaluatorTest.java
+++ b/src/test/java/com/google/devtools/build/skyframe/MemoizingEvaluatorTest.java
@@ -25,11 +25,6 @@ import static com.google.devtools.build.skyframe.GraphTester.COPY;
import static com.google.devtools.build.skyframe.GraphTester.NODE_TYPE;
import static com.google.devtools.build.skyframe.GraphTester.skyKey;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Predicates;
@@ -61,7 +56,6 @@ import com.google.devtools.build.skyframe.SkyFunction.Environment;
import com.google.devtools.build.skyframe.SkyFunctionException.Transience;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -150,21 +144,21 @@ public class MemoizingEvaluatorTest {
public void smoke() throws Exception {
tester.set("x", new StringValue("y"));
StringValue value = (StringValue) tester.evalAndGet("x");
- assertEquals("y", value.getValue());
+ assertThat(value.getValue()).isEqualTo("y");
}
@Test
public void invalidationWithNothingChanged() throws Exception {
tester.set("x", new StringValue("y")).setWarning("fizzlepop");
StringValue value = (StringValue) tester.evalAndGet("x");
- assertEquals("y", value.getValue());
+ assertThat(value.getValue()).isEqualTo("y");
assertContainsEvent(eventCollector, "fizzlepop");
assertEventCount(1, eventCollector);
initializeReporter();
tester.invalidate();
value = (StringValue) tester.evalAndGet("x");
- assertEquals("y", value.getValue());
+ assertThat(value.getValue()).isEqualTo("y");
if (eventsStored()) {
assertContainsEvent(eventCollector, "fizzlepop");
assertEventCount(1, eventCollector);
@@ -212,8 +206,8 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate("otherValue1").setConstantValue(new StringValue("otherVal1"));
EvaluationResult<SkyValue> result = tester.eval(false, "top");
- assertTrue(result.hasError());
- assertEquals(toSkyKey("badValue"), Iterables.getOnlyElement(result.getError().getRootCauses()));
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError().getRootCauses()).containsExactly(toSkyKey("badValue"));
assertThat(result.keyNames()).isEmpty();
}
@@ -294,7 +288,7 @@ public class MemoizingEvaluatorTest {
} catch (RuntimeException e) {
// Then the Evaluator#evaluate call throws a RuntimeException e where e.getCause() is the
// RuntimeException thrown by that SkyFunction.
- assertThat(e.getCause()).hasMessage("I don't like being woken up!");
+ assertThat(e).hasCauseThat().hasMessage("I don't like being woken up!");
}
}
@@ -361,12 +355,11 @@ public class MemoizingEvaluatorTest {
tester.eval(true, "d3");
assertThat(tester.getDirtyKeys()).isEmpty();
- assertEquals(
- ImmutableSet.of(skyKey("d1"), skyKey("top")), tester.getDeletedKeys());
- assertEquals(null, tester.getExistingValue("top"));
- assertEquals(null, tester.getExistingValue("d1"));
- assertEquals(d2, tester.getExistingValue("d2"));
- assertEquals(d3, tester.getExistingValue("d3"));
+ assertThat(tester.getDeletedKeys()).isEqualTo(ImmutableSet.of(skyKey("d1"), skyKey("top")));
+ assertThat(tester.getExistingValue("top")).isNull();
+ assertThat(tester.getExistingValue("d1")).isNull();
+ assertThat(tester.getExistingValue("d2")).isEqualTo(d2);
+ assertThat(tester.getExistingValue("d3")).isEqualTo(d3);
}
@Test
@@ -432,12 +425,13 @@ public class MemoizingEvaluatorTest {
tester.set("d2", new StringValue("2"));
tester.set("d3", new StringValue("3"));
tester.eval(true, "top1");
- assertThat(tester.getEnqueuedValues()).containsExactlyElementsIn(
- Arrays.asList(MemoizingEvaluatorTester.toSkyKeys("top1", "d1", "d2")));
+ assertThat(tester.getEnqueuedValues())
+ .containsExactlyElementsIn(MemoizingEvaluatorTester.toSkyKeys("top1", "d1", "d2"));
tester.eval(true, "top2");
- assertThat(tester.getEnqueuedValues()).containsExactlyElementsIn(
- Arrays.asList(MemoizingEvaluatorTester.toSkyKeys("top1", "d1", "d2", "top2", "d3")));
+ assertThat(tester.getEnqueuedValues())
+ .containsExactlyElementsIn(MemoizingEvaluatorTester.toSkyKeys(
+ "top1", "d1", "d2", "top2", "d3"));
}
// NOTE: Some of these tests exercising errors/warnings run through a size-2 for loop in order
@@ -466,12 +460,14 @@ public class MemoizingEvaluatorTest {
for (int i = 0; i < 2; i++) {
initializeReporter();
EvaluationResult<StringValue> result = tester.eval(false, "top");
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
if (rootCausesStored()) {
assertThat(result.getError(topKey).getRootCauses()).containsExactly(topKey);
}
- assertEquals(topKey.toString(), result.getError(topKey).getException().getMessage());
- assertTrue(result.getError(topKey).getException() instanceof SomeErrorException);
+ assertThat(result.getError(topKey).getException())
+ .hasMessageThat()
+ .isEqualTo(topKey.toString());
+ assertThat(result.getError(topKey).getException()).isInstanceOf(SomeErrorException.class);
if (i == 0 || eventsStored()) {
assertContainsEvent(eventCollector, "warn-dep");
assertEventCount(1, eventCollector);
@@ -486,12 +482,14 @@ public class MemoizingEvaluatorTest {
for (int i = 0; i < 2; i++) {
initializeReporter();
EvaluationResult<StringValue> result = tester.eval(false, "top");
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
if (rootCausesStored()) {
assertThat(result.getError(topKey).getRootCauses()).containsExactly(topKey);
}
- assertEquals(topKey.toString(), result.getError(topKey).getException().getMessage());
- assertTrue(result.getError(topKey).getException() instanceof SomeErrorException);
+ assertThat(result.getError(topKey).getException())
+ .hasMessageThat()
+ .isEqualTo(topKey.toString());
+ assertThat(result.getError(topKey).getException()).isInstanceOf(SomeErrorException.class);
if (i == 0 || eventsStored()) {
assertContainsEvent(eventCollector, "warning msg");
assertEventCount(1, eventCollector);
@@ -506,12 +504,14 @@ public class MemoizingEvaluatorTest {
for (int i = 0; i < 2; i++) {
initializeReporter();
EvaluationResult<StringValue> result = tester.eval(i == 0, "top");
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
if (rootCausesStored()) {
assertThat(result.getError(topKey).getRootCauses()).containsExactly(topKey);
}
- assertEquals(topKey.toString(), result.getError(topKey).getException().getMessage());
- assertTrue(result.getError(topKey).getException() instanceof SomeErrorException);
+ assertThat(result.getError(topKey).getException())
+ .hasMessageThat()
+ .isEqualTo(topKey.toString());
+ assertThat(result.getError(topKey).getException()).isInstanceOf(SomeErrorException.class);
if (i == 0 || eventsStored()) {
assertContainsEvent(eventCollector, "warning msg");
assertEventCount(1, eventCollector);
@@ -567,7 +567,7 @@ public class MemoizingEvaluatorTest {
.setProgress("just letting you know");
StringValue value = (StringValue) tester.evalAndGet("x");
- assertEquals("y", value.getValue());
+ assertThat(value.getValue()).isEqualTo("y");
assertContainsEvent(eventCollector, "fizzlepop");
assertContainsEvent(eventCollector, "just letting you know");
assertEventCount(2, eventCollector);
@@ -576,7 +576,7 @@ public class MemoizingEvaluatorTest {
// On the rebuild, we only replay warning messages.
initializeReporter();
value = (StringValue) tester.evalAndGet("x");
- assertEquals("y", value.getValue());
+ assertThat(value.getValue()).isEqualTo("y");
assertContainsEvent(eventCollector, "fizzlepop");
assertEventCount(1, eventCollector);
}
@@ -589,11 +589,11 @@ public class MemoizingEvaluatorTest {
.setComputedValue(COPY);
tester.set("b", new StringValue("y"));
StringValue original = (StringValue) tester.evalAndGet("a");
- assertEquals("y", original.getValue());
+ assertThat(original.getValue()).isEqualTo("y");
tester.set("b", new StringValue("z"));
tester.invalidate();
StringValue old = (StringValue) tester.evalAndGet("a");
- assertEquals("z", old.getValue());
+ assertThat(old.getValue()).isEqualTo("z");
tester.invalidate();
StringValue current = (StringValue) tester.evalAndGet("a");
assertThat(current).isEqualTo(old);
@@ -664,7 +664,7 @@ public class MemoizingEvaluatorTest {
.setComputedValue(COPY);
tester.set("a", new StringValue("me"));
StringValue value = (StringValue) tester.evalAndGet("ab");
- assertEquals("me", value.getValue());
+ assertThat(value.getValue()).isEqualTo("me");
}
@Test
@@ -678,7 +678,7 @@ public class MemoizingEvaluatorTest {
tester.set("a", new StringValue("other"));
tester.invalidate();
StringValue value = (StringValue) tester.evalAndGet("ab");
- assertEquals("other", value.getValue());
+ assertThat(value.getValue()).isEqualTo("other");
}
@Test
@@ -686,7 +686,7 @@ public class MemoizingEvaluatorTest {
setupDiamondDependency();
tester.set("d", new StringValue("me"));
StringValue value = (StringValue) tester.evalAndGet("a");
- assertEquals("meme", value.getValue());
+ assertThat(value.getValue()).isEqualTo("meme");
}
@Test
@@ -698,7 +698,7 @@ public class MemoizingEvaluatorTest {
tester.set("d", new StringValue("other"));
tester.invalidate();
StringValue value = (StringValue) tester.evalAndGet("a");
- assertEquals("otherother", value.getValue());
+ assertThat(value.getValue()).isEqualTo("otherother");
}
private void setupDiamondDependency() {
@@ -750,7 +750,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(top).addDependency(mid).setComputedValue(CONCATENATE);
tester.getOrCreate(mid).setHasError(true);
tester.eval(/*keepGoing=*/false, top, mid);
- assertEquals(0L, valueSet.getCount());
+ assertThat(valueSet.getCount()).isEqualTo(0L);
assertThat(tester.progressReceiver.evaluated).containsExactly(mid);
}
@@ -784,7 +784,7 @@ public class MemoizingEvaluatorTest {
tester.set("b", new StringValue("now"));
tester.invalidate();
StringValue value = (StringValue) tester.evalAndGet("a");
- assertEquals("nowsecond", value.getValue());
+ assertThat(value.getValue()).isEqualTo("nowsecond");
}
@Test
@@ -802,7 +802,7 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> result = tester.eval(/*keep_going=*/false, values);
for (int i = 0; i < values.length; i++) {
SkyValue actual = result.get(toSkyKey(values[i]));
- assertEquals(new StringValue("leaf"), actual);
+ assertThat(actual).isEqualTo(new StringValue("leaf"));
}
for (int j = 0; j < TESTED_NODES; j++) {
@@ -811,7 +811,9 @@ public class MemoizingEvaluatorTest {
result = tester.eval(/*keep_going=*/false, values);
for (int i = 0; i < values.length; i++) {
SkyValue actual = result.get(toSkyKey(values[i]));
- assertEquals("Run " + j + ", value " + i, new StringValue("other" + j), actual);
+ assertWithMessage("Run " + j + ", value " + i)
+ .that(actual)
+ .isEqualTo(new StringValue("other" + j));
}
}
}
@@ -834,7 +836,7 @@ public class MemoizingEvaluatorTest {
}
EvaluationResult<StringValue> result = tester.eval(/*keep_going=*/false, rootKey);
- assertEquals(new StringValue(expected.toString()), result.get(rootKey));
+ assertThat(result.get(rootKey)).isEqualTo(new StringValue(expected.toString()));
for (int j = 0; j < 10; j++) {
expected.setLength(0);
@@ -846,7 +848,7 @@ public class MemoizingEvaluatorTest {
tester.invalidate();
result = tester.eval(/*keep_going=*/false, rootKey);
- assertEquals(new StringValue(expected.toString()), result.get(rootKey));
+ assertThat(result.get(rootKey)).isEqualTo(new StringValue(expected.toString()));
}
}
@@ -882,16 +884,16 @@ public class MemoizingEvaluatorTest {
String lastRight = "right-" + (TEST_NODE_COUNT - 1);
EvaluationResult<StringValue> result = tester.eval(/*keep_going=*/false, lastLeft, lastRight);
- assertEquals(new StringValue("leaf"), result.get(toSkyKey(lastLeft)));
- assertEquals(new StringValue("leaf"), result.get(toSkyKey(lastRight)));
+ assertThat(result.get(toSkyKey(lastLeft))).isEqualTo(new StringValue("leaf"));
+ assertThat(result.get(toSkyKey(lastRight))).isEqualTo(new StringValue("leaf"));
for (int j = 0; j < TESTED_NODES; j++) {
String value = "other" + j;
tester.set("leaf", new StringValue(value));
tester.invalidate();
result = tester.eval(/*keep_going=*/false, lastLeft, lastRight);
- assertEquals(new StringValue(value), result.get(toSkyKey(lastLeft)));
- assertEquals(new StringValue(value), result.get(toSkyKey(lastRight)));
+ assertThat(result.get(toSkyKey(lastLeft))).isEqualTo(new StringValue(value));
+ assertThat(result.get(toSkyKey(lastRight))).isEqualTo(new StringValue(value));
}
}
@@ -910,8 +912,8 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(aKey).addDependency(bKey);
tester.getOrCreate(bKey).addDependency(aKey);
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/true, topKey, goodKey);
- assertEquals(goodValue, result.get(goodKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(goodKey)).isEqualTo(goodValue);
+ assertThat(result.get(topKey)).isNull();
ErrorInfo errorInfo = result.getError(topKey);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
if (cyclesDetected()) {
@@ -921,7 +923,7 @@ public class MemoizingEvaluatorTest {
tester.invalidate();
result = tester.eval(/*keepGoing=*/false, topKey, goodKey);
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
errorInfo = result.getError(topKey);
cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
if (cyclesDetected()) {
@@ -963,7 +965,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(aKey).addDependency(bKey).setComputedValue(COPY);
tester.getOrCreate(bKey).addDependency(aKey);
EvaluationResult<StringValue> result = tester.eval(keepGoing, topKey);
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
ErrorInfo errorInfo = result.getError(topKey);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
if (cyclesDetected()) {
@@ -975,8 +977,8 @@ public class MemoizingEvaluatorTest {
tester.set(bKey, new StringValue("bValue"));
tester.invalidate();
result = tester.eval(keepGoing, topKey);
- assertEquals(new StringValue("bValue"), result.get(topKey));
- assertEquals(null, result.getError(topKey));
+ assertThat(result.get(topKey)).isEqualTo(new StringValue("bValue"));
+ assertThat(result.getError(topKey)).isNull();
}
@Test
@@ -1024,7 +1026,7 @@ public class MemoizingEvaluatorTest {
// Then when we evaluate,
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/ true, aKey);
// aKey has an error,
- assertEquals(null, result.get(aKey));
+ assertThat(result.get(aKey)).isNull();
if (cyclesDetected()) {
// And both cycles were found underneath aKey: the (aKey->bKey->cKey) cycle, and the
// aKey->(bKey->cKey) cycle. This is because cKey depended on aKey and then bKey, so it pushed
@@ -1050,7 +1052,7 @@ public class MemoizingEvaluatorTest {
// Then when we evaluate,
EvaluationResult<StringValue> result2 = tester.eval(/*keepGoing=*/ true, aKey);
// Things are just as before.
- assertEquals(null, result2.get(aKey));
+ assertThat(result2.get(aKey)).isNull();
if (cyclesDetected()) {
assertThatEvaluationResult(result)
.hasErrorEntryForKeyThat(aKey)
@@ -1079,7 +1081,7 @@ public class MemoizingEvaluatorTest {
.setComputedValue(CONCATENATE);
tester.getOrCreate(cycleKey2).addDependency(cycleKey1).setComputedValue(COPY);
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/true, cycleKey1);
- assertEquals(null, result.get(cycleKey1));
+ assertThat(result.get(cycleKey1)).isNull();
ErrorInfo errorInfo = result.getError(cycleKey1);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
if (cyclesDetected()) {
@@ -1089,7 +1091,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(cycleKey1, /*markAsModified=*/true);
tester.invalidate();
result = tester.eval(/*keepGoing=*/true, cycleKey1, cycleKey2);
- assertEquals(null, result.get(cycleKey1));
+ assertThat(result.get(cycleKey1)).isNull();
errorInfo = result.getError(cycleKey1);
cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
if (cyclesDetected()) {
@@ -1135,7 +1137,7 @@ public class MemoizingEvaluatorTest {
// Evaluate twice to make sure nothing strange happens with invalidation the second time.
for (int i = 0; i < 2; i++) {
EvaluationResult<SkyValue> result = tester.eval(/*keepGoing=*/ true, cycleKey1);
- assertEquals(null, result.get(cycleKey1));
+ assertThat(result.get(cycleKey1)).isNull();
ErrorInfo errorInfo = result.getError(cycleKey1);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
if (cyclesDetected()) {
@@ -1154,7 +1156,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(cycleKey1).addDependency(cycleKey2).setComputedValue(COPY);
tester.getOrCreate(cycleKey2).addDependency(cycleKey1).setComputedValue(COPY);
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/true, cycleKey1);
- assertEquals(null, result.get(cycleKey1));
+ assertThat(result.get(cycleKey1)).isNull();
ErrorInfo errorInfo = result.getError(cycleKey1);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
if (cyclesDetected()) {
@@ -1164,7 +1166,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(cycleKey1, /*markAsModified=*/true);
tester.invalidate();
result = tester.eval(/*keepGoing=*/true, cycleKey1);
- assertEquals(null, result.get(cycleKey1));
+ assertThat(result.get(cycleKey1)).isNull();
errorInfo = result.getError(cycleKey1);
cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
if (cyclesDetected()) {
@@ -1490,8 +1492,8 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> result = tester.eval(
/*keepGoing=*/true, /*numThreads=*/5, topLevel);
- assertFalse(result.hasError());
- assertEquals(5, maxValue[0]);
+ assertThat(result.hasError()).isFalse();
+ assertThat(maxValue[0]).isEqualTo(5);
}
/**
@@ -1528,7 +1530,7 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, topKey);
assertThat(result.getError().getRootCauses()).containsExactly(errorKey);
// Make sure midKey didn't finish building.
- assertEquals(null, tester.getExistingValue(midKey));
+ assertThat(tester.getExistingValue(midKey)).isNull();
// Give slowKey a nice ordinary builder.
tester.getOrCreate(slowKey, /*markAsModified=*/false).setBuilder(null)
.setConstantValue(new StringValue("slow"));
@@ -1568,7 +1570,7 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, topKey);
assertThat(result.getError().getRootCauses()).containsExactly(errorKey);
// Make sure midKey didn't finish building.
- assertEquals(null, tester.getExistingValue(midKey));
+ assertThat(tester.getExistingValue(midKey)).isNull();
// Give slowKey a nice ordinary builder.
tester.getOrCreate(slowKey, /*markAsModified=*/false).setBuilder(null)
.setConstantValue(new StringValue("slow"));
@@ -1653,7 +1655,7 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, topKey);
assertThat(result.getError().getRootCauses()).containsExactly(errorKey);
// Make sure midKey didn't finish building.
- assertEquals(null, tester.getExistingValue(midKey));
+ assertThat(tester.getExistingValue(midKey)).isNull();
// Give slowKey a nice ordinary builder.
tester.getOrCreate(slowKey, /*markAsModified=*/false).setBuilder(null)
.setConstantValue(new StringValue("slow"));
@@ -1676,12 +1678,12 @@ public class MemoizingEvaluatorTest {
.setComputedValue(CONCATENATE).addDependency("after");
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/true, parentKey);
assertThat(result.errorMap()).isEmpty();
- assertEquals("recoveredafter", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("recoveredafter");
tester.set("after", new StringValue("before"));
tester.invalidate();
result = tester.eval(/*keepGoing=*/true, parentKey);
assertThat(result.errorMap()).isEmpty();
- assertEquals("recoveredbefore", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("recoveredbefore");
}
@Test
@@ -1695,12 +1697,12 @@ public class MemoizingEvaluatorTest {
.setComputedValue(CONCATENATE).addDependency("after");
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/true, parentKey);
assertThat(result.errorMap()).isEmpty();
- assertEquals("recoveredafter", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("recoveredafter");
tester.set(errorKey, new StringValue("reformed")).setHasError(false);
tester.invalidate();
result = tester.eval(/*keepGoing=*/true, parentKey);
assertThat(result.errorMap()).isEmpty();
- assertEquals("reformedafter", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("reformedafter");
}
@Test
@@ -1725,7 +1727,7 @@ public class MemoizingEvaluatorTest {
// Request the parent again. This time it should succeed.
result = tester.eval(/*keepGoing=*/false, parentKey);
assertThat(result.errorMap()).isEmpty();
- assertEquals("reformed", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("reformed");
// Confirm that the parent no longer depends on the error transience value -- make it
// unbuildable again, but without invalidating it, and invalidate transient errors. The parent
// should not be rebuilt.
@@ -1733,7 +1735,7 @@ public class MemoizingEvaluatorTest {
tester.invalidateTransientErrors();
result = tester.eval(/*keepGoing=*/false, parentKey);
assertThat(result.errorMap()).isEmpty();
- assertEquals("reformed", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("reformed");
}
/**
@@ -1768,7 +1770,7 @@ public class MemoizingEvaluatorTest {
tester.set(leaf, new StringValue("leaf"));
tester.getOrCreate(top).addDependency(leaf).setHasTransientError(true);
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, top);
- assertTrue(result.toString(), result.hasError());
+ assertWithMessage(result.toString()).that(result.hasError()).isTrue();
tester.getOrCreate(leaf, /*markAsModified=*/true);
tester.invalidate();
SkyKey irrelevant = GraphTester.toSkyKey("irrelevant");
@@ -1776,7 +1778,7 @@ public class MemoizingEvaluatorTest {
tester.eval(/*keepGoing=*/true, irrelevant);
tester.invalidateTransientErrors();
result = tester.eval(/*keepGoing=*/true, top);
- assertTrue(result.toString(), result.hasError());
+ assertWithMessage(result.toString()).that(result.hasError()).isTrue();
}
@Test
@@ -1794,7 +1796,7 @@ public class MemoizingEvaluatorTest {
// because
// it was only called during the bubbling-up phase.
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, midKey);
- assertEquals(null, result.get(midKey));
+ assertThat(result.get(midKey)).isNull();
assertThat(result.getError().getRootCauses()).containsExactly(errorKey);
// In a keepGoing build, midKey should be re-evaluated.
assertEquals("recovered",
@@ -1846,14 +1848,14 @@ public class MemoizingEvaluatorTest {
// Assert that build fails and "error" really is in error.
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, topKey);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
assertThat(result.getError(topKey).getRootCauses()).containsExactly(errorKey);
// Ensure that evaluation succeeds if errorKey does not throw an error.
tester.getOrCreate(errorKey).setBuilder(null);
tester.set(errorKey, new StringValue("ok"));
tester.invalidate();
- assertEquals(new StringValue("top"), tester.evalAndGet("top"));
+ assertThat(tester.evalAndGet("top")).isEqualTo(new StringValue("top"));
}
/**
@@ -1896,19 +1898,19 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> evaluationResult = tester.eval(
/*keepGoing=*/true, groupDepA, depC);
- assertTrue(evaluationResult.hasError());
- assertEquals("depC", evaluationResult.get(groupDepA).getValue());
+ assertThat(evaluationResult.hasError()).isTrue();
+ assertThat(evaluationResult.get(groupDepA).getValue()).isEqualTo("depC");
assertThat(evaluationResult.getError(depC).getRootCauses()).containsExactly(depC).inOrder();
evaluationResult = tester.eval(/*keepGoing=*/false, topKey);
- assertTrue(evaluationResult.hasError());
+ assertThat(evaluationResult.hasError()).isTrue();
assertThat(evaluationResult.getError(topKey).getRootCauses()).containsExactly(topKey).inOrder();
tester.set(groupDepA, new StringValue("groupDepB"));
tester.getOrCreate(depC, /*markAsModified=*/true);
tester.invalidate();
evaluationResult = tester.eval(/*keepGoing=*/false, topKey);
- assertFalse(evaluationResult.toString(), evaluationResult.hasError());
- assertEquals("top", evaluationResult.get(topKey).getValue());
+ assertWithMessage(evaluationResult.toString()).that(evaluationResult.hasError()).isFalse();
+ assertThat(evaluationResult.get(topKey).getValue()).isEqualTo("top");
}
@Test
@@ -1916,13 +1918,13 @@ public class MemoizingEvaluatorTest {
initializeTester();
tester.set("x", new StringValue("y")).setWarning("fizzlepop");
StringValue value = (StringValue) tester.evalAndGet("x");
- assertEquals("y", value.getValue());
+ assertThat(value.getValue()).isEqualTo("y");
assertContainsEvent(eventCollector, "fizzlepop");
assertEventCount(1, eventCollector);
tester.invalidate();
value = (StringValue) tester.evalAndGet("x");
- assertEquals("y", value.getValue());
+ assertThat(value.getValue()).isEqualTo("y");
// No new events emitted.
assertEventCount(1, eventCollector);
}
@@ -2015,9 +2017,9 @@ public class MemoizingEvaluatorTest {
};
// First build : just prime the graph.
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, top);
- assertFalse(result.hasError());
- assertEquals(new StringValue("top"), result.get(top));
- assertEquals(2, numTopInvocations.get());
+ assertThat(result.hasError()).isFalse();
+ assertThat(result.get(top)).isEqualTo(new StringValue("top"));
+ assertThat(numTopInvocations.get()).isEqualTo(2);
// Now dirty the graph, and maybe have firstKey throw an error.
String warningText = "warning text";
tester.getOrCreate(firstKey, /*markAsModified=*/true).setHasError(throwError)
@@ -2026,21 +2028,27 @@ public class MemoizingEvaluatorTest {
delayTopSignaling.set(true);
result = tester.eval(/*keepGoing=*/false, top);
if (throwError) {
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
assertThat(result.keyNames()).isEmpty(); // No successfully evaluated values.
ErrorInfo errorInfo = result.getError(top);
assertThat(errorInfo.getRootCauses()).containsExactly(firstKey);
- assertEquals("on the incremental build, top's builder should have only been used in error "
- + "bubbling", 3, numTopInvocations.get());
+ assertWithMessage(
+ "on the incremental build, top's builder should have only been used in error "
+ + "bubbling")
+ .that(numTopInvocations.get())
+ .isEqualTo(3);
} else {
- assertEquals(new StringValue("top"), result.get(top));
- assertFalse(result.hasError());
- assertEquals("on the incremental build, top's builder should have only been executed once in "
- + "normal evaluation", 3, numTopInvocations.get());
+ assertThat(result.get(top)).isEqualTo(new StringValue("top"));
+ assertThat(result.hasError()).isFalse();
+ assertWithMessage(
+ "on the incremental build, top's builder should have only been executed once in "
+ + "normal evaluation")
+ .that(numTopInvocations.get())
+ .isEqualTo(3);
}
assertContainsEvent(eventCollector, warningText);
- assertEquals(0, topSignaled.getCount());
- assertEquals(0, topRestartedBuild.getCount());
+ assertThat(topSignaled.getCount()).isEqualTo(0);
+ assertThat(topRestartedBuild.getCount()).isEqualTo(0);
}
@Test
@@ -2231,7 +2239,7 @@ public class MemoizingEvaluatorTest {
// For invalidation.
tester.set("dummy", new StringValue("dummy"));
StringValue topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("leafy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("leafy");
tester.set(leaf, new StringValue("crunchy"));
tester.invalidate();
// For invalidation.
@@ -2239,7 +2247,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(mid, /*markAsModified=*/true);
tester.invalidate();
topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("crunchy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("crunchy");
}
/**
@@ -2297,7 +2305,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(parent).addDependency(leaf).setComputedValue(CONCATENATE);
EvaluationResult<StringValue> result;
result = tester.eval(/*keepGoing=*/false, parent);
- assertEquals("leaf", result.get(parent).getValue());
+ assertThat(result.get(parent).getValue()).isEqualTo("leaf");
// Invalidate leaf, but don't actually change it. It will transitively dirty parent
// concurrently with parent directly dirtying itself.
tester.getOrCreate(leaf, /*markAsModified=*/true);
@@ -2308,9 +2316,9 @@ public class MemoizingEvaluatorTest {
tester.invalidate();
blockingEnabled.set(true);
result = tester.eval(/*keepGoing=*/false, parent);
- assertEquals("leafother2", result.get(parent).getValue());
- assertEquals(0, waitForChanged.getCount());
- assertEquals(0, threadsStarted.getCount());
+ assertThat(result.get(parent).getValue()).isEqualTo("leafother2");
+ assertThat(waitForChanged.getCount()).isEqualTo(0);
+ assertThat(threadsStarted.getCount()).isEqualTo(0);
}
@Test
@@ -2332,7 +2340,7 @@ public class MemoizingEvaluatorTest {
}
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, topKey);
- assertEquals(new StringValue(expected.toString()), result.get(topKey));
+ assertThat(result.get(topKey)).isEqualTo(new StringValue(expected.toString()));
for (int j = 0; j < RUNS; j++) {
for (int i = 0; i < values.length; i++) {
@@ -2344,7 +2352,7 @@ public class MemoizingEvaluatorTest {
tester.invalidate();
result = tester.eval(/*keep_going=*/false, topKey);
- assertEquals(new StringValue(expected.toString()), result.get(topKey));
+ assertThat(result.get(topKey)).isEqualTo(new StringValue(expected.toString()));
}
}
@@ -2372,8 +2380,8 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(fatherKey).addDependency(errorKey)
.addDependency(midKey).addDependency(lastKey).setComputedValue(CONCATENATE);
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, motherKey, fatherKey);
- assertEquals("biding timeslowlast", result.get(motherKey).getValue());
- assertEquals("biding timeslowlast", result.get(fatherKey).getValue());
+ assertThat(result.get(motherKey).getValue()).isEqualTo("biding timeslowlast");
+ assertThat(result.get(fatherKey).getValue()).isEqualTo("biding timeslowlast");
tester.set(slowKey, null);
// Each parent depends on errorKey, midKey, lastKey. We keep slowKey waiting until errorKey is
// finished. So there is no way lastKey can be enqueued by either parent. Thus, the parent that
@@ -2394,10 +2402,11 @@ public class MemoizingEvaluatorTest {
// -> one of mother or father builds. The other one should be cleaned, and no references to it
// left in the graph.
result = tester.eval(/*keepGoing=*/false, motherKey, fatherKey);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
// Only one of mother or father should be in the graph.
- assertTrue(result.getError(motherKey) + ", " + result.getError(fatherKey),
- (result.getError(motherKey) == null) != (result.getError(fatherKey) == null));
+ assertWithMessage(result.getError(motherKey) + ", " + result.getError(fatherKey))
+ .that((result.getError(motherKey) == null) != (result.getError(fatherKey) == null))
+ .isTrue();
SkyKey parentKey = (reevaluateMissingValue == (result.getError(motherKey) == null))
? motherKey : fatherKey;
// Give slowKey a nice ordinary builder.
@@ -2419,7 +2428,7 @@ public class MemoizingEvaluatorTest {
if (removeError) {
assertThat(result.get(parentKey).getValue()).isEqualTo("reformedleaf2" + lastString);
} else {
- assertNotNull(result.getError(parentKey));
+ assertThat(result.getError(parentKey)).isNotNull();
}
}
@@ -2510,7 +2519,7 @@ public class MemoizingEvaluatorTest {
}
};
evalThread.start();
- assertTrue(notifyStart.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(notifyStart.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue();
evalThread.interrupt();
evalThread.joinAndAssertState(TestUtils.WAIT_TIMEOUT_MILLISECONDS);
// Free leafKey to compute next time.
@@ -2532,7 +2541,9 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> result =
tester.eval(/*keepGoing=*/false, tops.toArray(new SkyKey[0]));
for (SkyKey topKey : tops) {
- assertEquals(topKey.toString(), "crunchynew last", result.get(topKey).getValue());
+ assertWithMessage(topKey.toString())
+ .that(result.get(topKey).getValue())
+ .isEqualTo("crunchynew last");
}
}
@@ -2613,7 +2624,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(mid).addDependency(leaf).setComputedValue(COPY);
tester.set(leaf, new StringValue("leafy"));
StringValue topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("leafy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("leafy");
// Mark leaf changed, but don't actually change it.
tester.getOrCreate(leaf, /*markAsModified=*/true);
// mid will give an error if re-evaluated, but it shouldn't be because it is not marked changed,
@@ -2621,9 +2632,9 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(mid, /*markAsModified=*/false).setHasError(true);
tester.invalidate();
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, top);
- assertFalse(result.hasError());
+ assertThat(result.hasError()).isFalse();
topValue = result.get(top);
- assertEquals("leafy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("leafy");
assertThat(tester.getDirtyKeys()).isEmpty();
assertThat(tester.getDeletedKeys()).isEmpty();
}
@@ -2642,7 +2653,7 @@ public class MemoizingEvaluatorTest {
SkyValue leafyValue = new StringValue("leafy");
tester.set(leaf, leafyValue);
StringValue value = (StringValue) tester.evalAndGet("top");
- assertEquals("leafysuffixsuffix", value.getValue());
+ assertThat(value.getValue()).isEqualTo("leafysuffixsuffix");
// Mark leaf changed, but don't actually change it.
tester.getOrCreate(leaf, /*markAsModified=*/true);
// mid will give an error if re-evaluated, but it shouldn't be because it is not marked changed,
@@ -2650,13 +2661,13 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(mid, /*markAsModified=*/false).setHasError(true);
tester.invalidate();
value = (StringValue) tester.evalAndGet("leaf");
- assertEquals("leafy", value.getValue());
+ assertThat(value.getValue()).isEqualTo("leafy");
assertThat(tester.getDirtyKeys()).containsExactly(mid, top);
assertThat(tester.getDeletedKeys()).isEmpty();
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, top);
assertWithMessage(result.toString()).that(result.hasError()).isFalse();
value = result.get(top);
- assertEquals("leafysuffixsuffix", value.getValue());
+ assertThat(value.getValue()).isEqualTo("leafysuffixsuffix");
assertThat(tester.getDirtyKeys()).isEmpty();
assertThat(tester.getDeletedKeys()).isEmpty();
}
@@ -2689,7 +2700,7 @@ public class MemoizingEvaluatorTest {
// And top is evaluated,
StringValue topValue = (StringValue) tester.evalAndGet("top");
// Then top's value is as expected,
- assertEquals(fixedTopValue, topValue);
+ assertThat(topValue).isEqualTo(fixedTopValue);
// And top was actually evaluated.
assertThat(topEvaluated.get()).isTrue();
// When leaf is changed,
@@ -2699,7 +2710,7 @@ public class MemoizingEvaluatorTest {
// And top is evaluated,
StringValue topValue2 = (StringValue) tester.evalAndGet("top");
// Then top's value is as expected,
- assertEquals(fixedTopValue, topValue2);
+ assertThat(topValue2).isEqualTo(fixedTopValue);
// And top was actually evaluated.
assertThat(topEvaluated.get()).isTrue();
// When leaf is invalidated but not actually changed,
@@ -2709,7 +2720,7 @@ public class MemoizingEvaluatorTest {
// And top is evaluated,
StringValue topValue3 = (StringValue) tester.evalAndGet("top");
// Then top's value is as expected,
- assertEquals(fixedTopValue, topValue3);
+ assertThat(topValue3).isEqualTo(fixedTopValue);
// And top was *not* actually evaluated, because change pruning cut off evaluation.
assertThat(topEvaluated.get()).isFalse();
}
@@ -2747,7 +2758,7 @@ public class MemoizingEvaluatorTest {
// And top is evaluated,
StringValue topValue = (StringValue) tester.evalAndGet("top");
// Then top's value is as expected,
- assertEquals(fixedTopValue, topValue);
+ assertThat(topValue).isEqualTo(fixedTopValue);
// And top was actually evaluated.
assertThat(topEvaluated.get()).isTrue();
// When leaf is changed,
@@ -2757,7 +2768,7 @@ public class MemoizingEvaluatorTest {
// And top is evaluated,
StringValue topValue2 = (StringValue) tester.evalAndGet("top");
// Then top's value is as expected,
- assertEquals(fixedTopValue, topValue2);
+ assertThat(topValue2).isEqualTo(fixedTopValue);
// And top was actually evaluated.
assertThat(topEvaluated.get()).isTrue();
// When other is invalidated but not actually changed,
@@ -2767,7 +2778,7 @@ public class MemoizingEvaluatorTest {
// And top is evaluated,
StringValue topValue3 = (StringValue) tester.evalAndGet("top");
// Then top's value is as expected,
- assertEquals(fixedTopValue, topValue3);
+ assertThat(topValue3).isEqualTo(fixedTopValue);
// And top was *not* actually evaluated, because change pruning cut off evaluation.
assertThat(topEvaluated.get()).isFalse();
}
@@ -2808,13 +2819,13 @@ public class MemoizingEvaluatorTest {
SkyKey top = GraphTester.toSkyKey("top");
tester.getOrCreate(top).addDependency(buildFile).setComputedValue(authorDrink);
StringValue topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("hemingway drank absinthe", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("hemingway drank absinthe");
tester.set(buildFile, new StringValue("joyce"));
// Don't evaluate absinthe successfully anymore.
tester.getOrCreate(absinthe).setHasError(true);
tester.invalidate();
topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("joyce drank whiskey", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("joyce drank whiskey");
assertThat(tester.getDirtyKeys()).containsExactly(buildFile, top);
assertThat(tester.getDeletedKeys()).isEmpty();
}
@@ -2830,20 +2841,20 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(mid).addDependency(leaf);
tester.set(leaf, new StringValue("leafy"));
StringValue topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("ignore", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("ignore");
assertThat(tester.getDirtyKeys()).isEmpty();
assertThat(tester.getDeletedKeys()).isEmpty();
// Change leaf.
tester.set(leaf, new StringValue("crunchy"));
tester.invalidate();
topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("ignore", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("ignore");
assertThat(tester.getDirtyKeys()).containsExactly(leaf);
assertThat(tester.getDeletedKeys()).isEmpty();
tester.set(leaf, new StringValue("smushy"));
tester.invalidate();
topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("ignore", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("ignore");
assertThat(tester.getDirtyKeys()).containsExactly(leaf);
assertThat(tester.getDeletedKeys()).isEmpty();
}
@@ -2892,7 +2903,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(top).addDependency(leaf).setComputedValue(COPY);
tester.set(leaf, new StringValue("leafy"));
StringValue topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("leafy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("leafy");
assertThat(tester.getDirtyKeys()).isEmpty();
assertThat(tester.getDeletedKeys()).isEmpty();
failBuildAndRemoveValue(leaf);
@@ -2901,7 +2912,7 @@ public class MemoizingEvaluatorTest {
tester.set(leaf, new StringValue("crunchy"));
tester.invalidate();
topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("crunchy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("crunchy");
}
/**
@@ -2917,7 +2928,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(top).addDependency(leaf).setComputedValue(COPY);
tester.set(leaf, new StringValue("leafy"));
StringValue topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("leafy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("leafy");
assertThat(tester.getDirtyKeys()).isEmpty();
assertThat(tester.getDeletedKeys()).isEmpty();
failBuildAndRemoveValue(leaf);
@@ -2929,7 +2940,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(top, /*markAsModified=*/true);
tester.invalidate();
topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("crunchy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("crunchy");
}
/**
@@ -2987,7 +2998,7 @@ public class MemoizingEvaluatorTest {
.setComputedValue(COPY);
tester.set(leaf, new StringValue("leafy"));
StringValue topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("leafy", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("leafy");
assertThat(tester.getDirtyKeys()).isEmpty();
assertThat(tester.getDeletedKeys()).isEmpty();
// Change leaf.
@@ -2995,7 +3006,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(top, /*markAsModified=*/false).setHasError(true);
tester.invalidate();
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, top);
- assertNull("value should not have completed evaluation", result.get(top));
+ assertWithMessage("value should not have completed evaluation").that(result.get(top)).isNull();
assertWithMessage(
"The error thrown by leaf should have been swallowed by the error thrown by top")
.that(result.getError().getRootCauses()).containsExactly(top);
@@ -3012,7 +3023,7 @@ public class MemoizingEvaluatorTest {
tester.set(secondError, new StringValue("secondError")).addDependency(leaf);
tester.set(leaf, new StringValue("leafy"));
StringValue topValue = (StringValue) tester.evalAndGet("top");
- assertEquals("leafysecondError", topValue.getValue());
+ assertThat(topValue.getValue()).isEqualTo("leafysecondError");
assertThat(tester.getDirtyKeys()).isEmpty();
assertThat(tester.getDeletedKeys()).isEmpty();
// Invalidate leaf.
@@ -3022,7 +3033,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(top, /*markAsModified=*/false).setHasError(true);
tester.invalidate();
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false, top);
- assertNull("value should not have completed evaluation", result.get(top));
+ assertWithMessage("value should not have completed evaluation").that(result.get(top)).isNull();
assertWithMessage(
"The error thrown by leaf should have been swallowed by the error thrown by top")
.that(result.getError().getRootCauses()).containsExactly(top);
@@ -3033,13 +3044,13 @@ public class MemoizingEvaluatorTest {
initializeTester();
SkyKey error = GraphTester.toSkyKey("error");
tester.getOrCreate(error).setHasError(true);
- assertNotNull(tester.evalAndGetError(error));
+ assertThat(tester.evalAndGetError(error)).isNotNull();
tester.invalidateTransientErrors();
SkyKey secondError = GraphTester.toSkyKey("secondError");
tester.getOrCreate(secondError).setHasError(true);
// secondError declares a new dependence on ErrorTransienceValue, but not until it has already
// thrown an error.
- assertNotNull(tester.evalAndGetError(secondError));
+ assertThat(tester.evalAndGetError(secondError)).isNotNull();
}
@Test
@@ -3056,8 +3067,8 @@ public class MemoizingEvaluatorTest {
tester.set(error, val);
tester.invalidate();
result = tester.eval(/*keepGoing=*/false, topKey);
- assertEquals(val, result.get(topKey));
- assertFalse(result.hasError());
+ assertThat(result.get(topKey)).isEqualTo(val);
+ assertThat(result.hasError()).isFalse();
}
/** Regression test for crash bug. */
@@ -3094,8 +3105,8 @@ public class MemoizingEvaluatorTest {
tester.invalidate();
tester.invalidateTransientErrors();
result = tester.eval(/*keepGoing=*/false, topKey);
- assertEquals(reformed, result.get(topKey));
- assertFalse(result.hasError());
+ assertThat(result.get(topKey)).isEqualTo(reformed);
+ assertThat(result.hasError()).isFalse();
}
/**
@@ -3133,8 +3144,8 @@ public class MemoizingEvaluatorTest {
// First error-free evaluation, to put all values in graph.
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/false,
topErrorFirstKey, topBubbleKey);
- assertEquals("biding time", result.get(topErrorFirstKey).getValue());
- assertEquals("slowbiding time", result.get(topBubbleKey).getValue());
+ assertThat(result.get(topErrorFirstKey).getValue()).isEqualTo("biding time");
+ assertThat(result.get(topBubbleKey).getValue()).isEqualTo("slowbiding time");
// Set up timing of child values: slowKey waits to finish until errorKey has thrown an
// exception that has been caught by the threadpool.
tester.set(slowKey, null);
@@ -3152,7 +3163,7 @@ public class MemoizingEvaluatorTest {
// errorKey finishes, written to graph -> slowKey maybe starts+finishes & (Visitor aborts)
// -> some top key builds.
result = tester.eval(/*keepGoing=*/false, topErrorFirstKey, topBubbleKey);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
assertWithMessage(result.toString()).that(result.getError(topErrorFirstKey)).isNotNull();
}
@@ -3188,8 +3199,8 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(topKey).setBuilder(null).addDependency(error).setComputedValue(COPY);
tester.invalidate();
result = tester.eval(/*keepGoing=*/false, topKey);
- assertEquals(reformed, result.get(topKey));
- assertFalse(result.hasError());
+ assertThat(result.get(topKey)).isEqualTo(reformed);
+ assertThat(result.hasError()).isFalse();
}
/**
@@ -3227,12 +3238,12 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/ false, parentKey);
assertThat(result.keyNames()).isEmpty();
Map.Entry<SkyKey, ErrorInfo> error = Iterables.getOnlyElement(result.errorMap().entrySet());
- assertEquals(parentKey, error.getKey());
+ assertThat(error.getKey()).isEqualTo(parentKey);
assertThat(error.getValue().getRootCauses()).containsExactly(errorKey);
- assertFalse(Thread.interrupted());
+ assertThat(Thread.interrupted()).isFalse();
result = tester.eval(/*keepGoing=*/ true, parentKey);
assertThat(result.errorMap()).isEmpty();
- assertEquals("recovered", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("recovered");
}
/**
@@ -3287,8 +3298,8 @@ public class MemoizingEvaluatorTest {
assertThat(result.getError(midKey).getRootCauses()).containsExactly(badKey);
waitForSecondCall.set(true);
result = tester.eval(/*keepGoing=*/ true, topKey, midKey);
- assertNotNull(firstThread.get());
- assertEquals(0, otherThreadWinning.getCount());
+ assertThat(firstThread.get()).isNotNull();
+ assertThat(otherThreadWinning.getCount()).isEqualTo(0);
assertThatEvaluationResult(result).hasErrorEntryForKeyThat(midKey).isNotNull();
assertThatEvaluationResult(result).hasErrorEntryForKeyThat(topKey).isNotNull();
if (rootCausesStored()) {
@@ -3315,11 +3326,11 @@ public class MemoizingEvaluatorTest {
EvaluationResult<StringValue> result = tester.eval(/*keepGoing=*/ false, parentKey);
assertThat(result.keyNames()).isEmpty();
Map.Entry<SkyKey, ErrorInfo> error = Iterables.getOnlyElement(result.errorMap().entrySet());
- assertEquals(parentKey, error.getKey());
+ assertThat(error.getKey()).isEqualTo(parentKey);
assertThat(error.getValue().getRootCauses()).containsExactly(errorKey);
result = tester.eval(/*keepGoing=*/ true, parentKey);
assertThat(result.errorMap()).isEmpty();
- assertEquals("recoveredafter", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("recoveredafter");
}
@Test
@@ -3412,19 +3423,19 @@ public class MemoizingEvaluatorTest {
tester.eval(/*keepGoing=*/ false, errorKey, otherErrorKey);
// Then the result reports that an error occurred because of errorKey,
- assertTrue(result.hasError());
- assertEquals(errorKey, result.getError().getRootCauseOfException());
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError().getRootCauseOfException()).isEqualTo(errorKey);
// And no value is committed for otherErrorKey,
- assertNull(tester.driver.getExistingErrorForTesting(otherErrorKey));
- assertNull(tester.driver.getExistingValueForTesting(otherErrorKey));
+ assertThat(tester.driver.getExistingErrorForTesting(otherErrorKey)).isNull();
+ assertThat(tester.driver.getExistingValueForTesting(otherErrorKey)).isNull();
// And no value was committed for errorKey,
- assertNull(nonNullValueMessage.get(), nonNullValueMessage.get());
+ assertWithMessage(nonNullValueMessage.get()).that(nonNullValueMessage.get()).isNull();
// And the SkyFunction for otherErrorKey was evaluated exactly once.
- assertEquals(1, numOtherInvocations.get());
- assertNull(bogusInvocationMessage.get(), bogusInvocationMessage.get());
+ assertThat(numOtherInvocations.get()).isEqualTo(1);
+ assertWithMessage(bogusInvocationMessage.get()).that(bogusInvocationMessage.get()).isNull();
// NB: The SkyFunction for otherErrorKey gets evaluated exactly once--it does not get
// re-evaluated during error bubbling. Why? When otherErrorKey throws, it is always the
@@ -3538,11 +3549,11 @@ public class MemoizingEvaluatorTest {
@Test
public void errorTransienceBug() throws Exception {
tester.getOrCreate("key").setHasTransientError(true);
- assertNotNull(tester.evalAndGetError("key").getException());
+ assertThat(tester.evalAndGetError("key").getException()).isNotNull();
StringValue value = new StringValue("hi");
tester.getOrCreate("key").setHasTransientError(false).setConstantValue(value);
tester.invalidateTransientErrors();
- assertEquals(value, tester.evalAndGet("key"));
+ assertThat(tester.evalAndGet("key")).isEqualTo(value);
// This works because the version of the ValueEntry for the ErrorTransience value is always
// increased on each InMemoryMemoizingEvaluator#evaluate call. But that's not the only way to
// implement error transience; another valid implementation would be to unconditionally mark
@@ -3556,19 +3567,19 @@ public class MemoizingEvaluatorTest {
SkyKey errorKey = GraphTester.toSkyKey("my_error_value");
tester.getOrCreate(errorKey).setHasTransientError(true);
ErrorInfo errorInfo = tester.evalAndGetError(errorKey);
- assertNotNull(errorInfo);
+ assertThat(errorInfo).isNotNull();
assertThat(errorInfo.getRootCauses()).containsExactly(errorKey);
// Re-evaluates to same thing when errors are invalidated
tester.invalidateTransientErrors();
errorInfo = tester.evalAndGetError(errorKey);
- assertNotNull(errorInfo);
+ assertThat(errorInfo).isNotNull();
StringValue value = new StringValue("reformed");
assertThat(errorInfo.getRootCauses()).containsExactly(errorKey);
tester.getOrCreate(errorKey, /*markAsModified=*/false).setHasTransientError(false)
.setConstantValue(value);
tester.invalidateTransientErrors();
StringValue stringValue = (StringValue) tester.evalAndGet(/*keepGoing=*/true, errorKey);
- assertSame(stringValue, value);
+ assertThat(value).isSameAs(stringValue);
// Value builder will now throw, but we should never get to it because it isn't dirty.
tester.getOrCreate(errorKey, /*markAsModified=*/false).setHasTransientError(true);
tester.invalidateTransientErrors();
@@ -3639,16 +3650,16 @@ public class MemoizingEvaluatorTest {
tester.invalidate();
EvaluationResult<StringValue> result = tester.eval(
/*keep_going=*/false, lastLeft, lastRight);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
tester.differencer.invalidate(ImmutableList.of(leftValues[i]));
tester.invalidate();
result = tester.eval(/*keep_going=*/false, lastLeft, lastRight);
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
tester.getOrCreate(leftValues[i], /*markAsModified=*/true).setHasError(false);
tester.invalidate();
result = tester.eval(/*keep_going=*/false, lastLeft, lastRight);
- assertEquals(new StringValue("leaf"), result.get(toSkyKey(lastLeft)));
- assertEquals(new StringValue("leaf"), result.get(toSkyKey(lastRight)));
+ assertThat(result.get(toSkyKey(lastLeft))).isEqualTo(new StringValue("leaf"));
+ assertThat(result.get(toSkyKey(lastRight))).isEqualTo(new StringValue("leaf"));
} catch (Exception e) {
System.err.println("twoRailLeftRightDependenciesWithFailure exception on run " + i);
throw e;
@@ -3662,7 +3673,7 @@ public class MemoizingEvaluatorTest {
SkyValue val = new StringValue("val");
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet("new_value"));
+ assertThat(tester.evalAndGet("new_value")).isEqualTo(val);
}
@Test
@@ -3672,7 +3683,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(key).setConstantValue(new StringValue("old_val"));
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
}
@Test
@@ -3689,7 +3700,7 @@ public class MemoizingEvaluatorTest {
tester.differencer.inject(ImmutableMap.of(key, val));
tester.eval(/*keepGoing=*/false, new SkyKey[0]); // Inject again.
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
}
@Test
@@ -3700,7 +3711,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(key).setConstantValue(new StringValue("old_val"));
tester.differencer.invalidate(ImmutableList.of(key));
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
}
@Test
@@ -3711,7 +3722,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(key).setConstantValue(new StringValue("old_val"));
tester.evaluator.delete(Predicates.<SkyKey>alwaysTrue());
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
}
@Test
@@ -3720,11 +3731,11 @@ public class MemoizingEvaluatorTest {
SkyValue val = new StringValue("val");
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
tester.differencer.invalidate(ImmutableList.of(key));
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
}
@Test
@@ -3733,11 +3744,11 @@ public class MemoizingEvaluatorTest {
SkyValue val = new StringValue("val");
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
tester.evaluator.delete(Predicates.<SkyKey>alwaysTrue());
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
}
@Test
@@ -3748,7 +3759,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate("other").setConstantValue(prevVal);
tester.getOrCreate(key).addDependency("other").setComputedValue(COPY);
- assertEquals(prevVal, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(prevVal);
tester.differencer.inject(ImmutableMap.of(key, val));
try {
tester.evalAndGet("value");
@@ -3767,7 +3778,7 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate("other").setConstantValue(val);
tester.getOrCreate(key).addDependency("other").setComputedValue(COPY);
- assertEquals(val, tester.evalAndGet("value"));
+ assertThat(tester.evalAndGet("value")).isEqualTo(val);
tester.differencer.inject(ImmutableMap.of(key, val));
try {
tester.evalAndGet("value");
@@ -3788,7 +3799,7 @@ public class MemoizingEvaluatorTest {
tester.evalAndGetError(key);
tester.differencer.inject(ImmutableMap.of(key, val));
- assertEquals(val, tester.evalAndGet(false, key));
+ assertThat(tester.evalAndGet(false, key)).isEqualTo(val);
}
@Test
@@ -3801,19 +3812,19 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(parentKey).addDependency("child").setComputedValue(COPY);
EvaluationResult<SkyValue> result = tester.eval(false, parentKey);
- assertFalse(result.hasError());
- assertEquals(oldVal, result.get(parentKey));
+ assertThat(result.hasError()).isFalse();
+ assertThat(result.get(parentKey)).isEqualTo(oldVal);
SkyValue val = new StringValue("val");
tester.differencer.inject(ImmutableMap.of(childKey, val));
- assertEquals(val, tester.evalAndGet("child"));
+ assertThat(tester.evalAndGet("child")).isEqualTo(val);
// Injecting a new child should have invalidated the parent.
- Assert.assertNull(tester.getExistingValue("parent"));
+ assertThat(tester.getExistingValue("parent")).isNull();
tester.eval(false, childKey);
- assertEquals(val, tester.getExistingValue("child"));
- Assert.assertNull(tester.getExistingValue("parent"));
- assertEquals(val, tester.evalAndGet("parent"));
+ assertThat(tester.getExistingValue("child")).isEqualTo(val);
+ assertThat(tester.getExistingValue("parent")).isNull();
+ assertThat(tester.evalAndGet("parent")).isEqualTo(val);
}
@Test
@@ -3824,12 +3835,12 @@ public class MemoizingEvaluatorTest {
tester.getOrCreate(parentKey).addDependency("child").setComputedValue(COPY);
tester.getOrCreate(childKey).setConstantValue(new StringValue("same_val"));
- assertEquals(val, tester.evalAndGet("parent"));
+ assertThat(tester.evalAndGet("parent")).isEqualTo(val);
tester.differencer.inject(ImmutableMap.of(childKey, val));
- assertEquals(val, tester.getExistingValue("child"));
+ assertThat(tester.getExistingValue("child")).isEqualTo(val);
// Since we are injecting an equal value, the parent should not have been invalidated.
- assertEquals(val, tester.getExistingValue("parent"));
+ assertThat(tester.getExistingValue("parent")).isEqualTo(val);
}
@Test
@@ -3846,7 +3857,7 @@ public class MemoizingEvaluatorTest {
// Expected.
}
SkyValue newVal = tester.evalAndGet("key");
- assertEquals(val, newVal);
+ assertThat(newVal).isEqualTo(val);
}
@Test
@@ -3919,7 +3930,8 @@ public class MemoizingEvaluatorTest {
if (type == EventType.IS_DIRTY && key.equals(failingKey)) {
// Wait for the build to abort or for the other node to incorrectly build.
try {
- assertTrue(slowBuilt.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(slowBuilt.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
+ .isTrue();
} catch (InterruptedException e) {
// This is ok, because it indicates the build is shutting down.
Thread.currentThread().interrupt();
@@ -4005,7 +4017,8 @@ public class MemoizingEvaluatorTest {
// When the uncached parent is first signaled by its changed dep, make sure that
// we wait until the cached parent is signaled too.
try {
- assertTrue(cachedSignaled.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(cachedSignaled.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
+ .isTrue();
} catch (InterruptedException e) {
// Before the relevant bug was fixed, this code was not interrupted, and the
// uncached parent got to build, yielding an inconsistent state at a later point
@@ -4484,7 +4497,7 @@ public class MemoizingEvaluatorTest {
public <T extends SkyValue> EvaluationResult<T> eval(boolean keepGoing, String... keys)
throws InterruptedException {
- return eval(keepGoing, toSkyKeys(keys));
+ return eval(keepGoing, toSkyKeys(keys).toArray(new SkyKey[0]));
}
public SkyValue evalAndGet(boolean keepGoing, String key)
@@ -4500,14 +4513,14 @@ public class MemoizingEvaluatorTest {
throws InterruptedException {
EvaluationResult<StringValue> evaluationResult = eval(keepGoing, key);
SkyValue result = evaluationResult.get(key);
- assertNotNull(evaluationResult.toString(), result);
+ assertWithMessage(evaluationResult.toString()).that(result).isNotNull();
return result;
}
public ErrorInfo evalAndGetError(SkyKey key) throws InterruptedException {
EvaluationResult<StringValue> evaluationResult = eval(/*keepGoing=*/true, key);
ErrorInfo result = evaluationResult.getError(key);
- assertNotNull(evaluationResult.toString(), result);
+ assertWithMessage(evaluationResult.toString()).that(result).isNotNull();
return result;
}
diff --git a/src/test/java/com/google/devtools/build/skyframe/ParallelEvaluatorTest.java b/src/test/java/com/google/devtools/build/skyframe/ParallelEvaluatorTest.java
index cfeab4edf0..78ab4a58aa 100644
--- a/src/test/java/com/google/devtools/build/skyframe/ParallelEvaluatorTest.java
+++ b/src/test/java/com/google/devtools/build/skyframe/ParallelEvaluatorTest.java
@@ -22,10 +22,6 @@ import static com.google.devtools.build.lib.testutil.MoreAsserts.assertNoEvents;
import static com.google.devtools.build.skyframe.EvaluationResultSubjectFactory.assertThatEvaluationResult;
import static com.google.devtools.build.skyframe.GraphTester.CONCATENATE;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Supplier;
@@ -51,7 +47,6 @@ import com.google.devtools.build.skyframe.NotifyingHelper.Listener;
import com.google.devtools.build.skyframe.NotifyingHelper.Order;
import com.google.devtools.build.skyframe.SkyFunctionException.Transience;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -62,7 +57,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -148,7 +142,7 @@ public class ParallelEvaluatorTest {
set("b", "b");
tester.getOrCreate("ab").addDependency("a").addDependency("b").setComputedValue(CONCATENATE);
StringValue value = (StringValue) eval(false, GraphTester.toSkyKey("ab"));
- assertEquals("ab", value.getValue());
+ assertThat(value.getValue()).isEqualTo("ab");
assertNoEvents(eventCollector);
}
@@ -276,10 +270,10 @@ public class ParallelEvaluatorTest {
}
};
evalThread.start();
- assertTrue(allValuesReady.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ assertThat(allValuesReady.await(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue();
evalThread.interrupt();
evalThread.join(TestUtils.WAIT_TIMEOUT_MILLISECONDS);
- assertFalse(evalThread.isAlive());
+ assertThat(evalThread.isAlive()).isFalse();
if (buildFastFirst) {
// If leafKey was already built, it is not reported to the receiver.
assertThat(receivedValues).containsExactly(fastKey);
@@ -356,14 +350,16 @@ public class ParallelEvaluatorTest {
// Start the thread and wait for a semaphore. This ensures that the thread was really started.
t.start();
- assertTrue(threadStarted.tryAcquire(TestUtils.WAIT_TIMEOUT_MILLISECONDS,
- TimeUnit.MILLISECONDS));
+ assertThat(threadStarted.tryAcquire(TestUtils.WAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS))
+ .isTrue();
// Interrupt the thread and wait for a semaphore. This ensures that the thread was really
// interrupted and this fact was acknowledged.
t.interrupt();
- assertTrue(threadInterrupted.tryAcquire(TestUtils.WAIT_TIMEOUT_MILLISECONDS,
- TimeUnit.MILLISECONDS));
+ assertThat(
+ threadInterrupted.tryAcquire(
+ TestUtils.WAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS))
+ .isTrue();
// The SkyFunction may have reported an error.
if (wasError[0] != null) {
@@ -402,9 +398,10 @@ public class ParallelEvaluatorTest {
try {
evaluator.eval(ImmutableList.of(valueToEval));
} catch (RuntimeException re) {
- assertThat(re.getMessage())
+ assertThat(re)
+ .hasMessageThat()
.contains("Unrecoverable error while evaluating node '" + valueToEval.toString() + "'");
- assertThat(re.getCause()).isInstanceOf(CustomRuntimeException.class);
+ assertThat(re).hasCauseThat().isInstanceOf(CustomRuntimeException.class);
}
}
@@ -413,7 +410,7 @@ public class ParallelEvaluatorTest {
graph = new InMemoryGraphImpl();
set("a", "a").setWarning("warning on 'a'");
StringValue value = (StringValue) eval(false, GraphTester.toSkyKey("a"));
- assertEquals("a", value.getValue());
+ assertThat(value.getValue()).isEqualTo("a");
assertContainsEvent(eventCollector, "warning on 'a'");
assertEventCount(1, eventCollector);
}
@@ -477,7 +474,7 @@ public class ParallelEvaluatorTest {
}
});
evaluator.eval(ImmutableList.of(a));
- assertTrue(evaluated.get());
+ assertThat(evaluated.get()).isTrue();
assertEventCount(2, eventCollector);
assertContainsEvent(eventCollector, "boop");
assertContainsEvent(eventCollector, "beep");
@@ -485,7 +482,7 @@ public class ParallelEvaluatorTest {
evaluator = makeEvaluator(graph, tester.getSkyFunctionMap(), /*keepGoing=*/ false);
evaluated.set(false);
evaluator.eval(ImmutableList.of(a));
- assertFalse(evaluated.get());
+ assertThat(evaluated.get()).isFalse();
assertEventCount(1, eventCollector);
assertContainsEvent(eventCollector, "boop");
}
@@ -520,7 +517,7 @@ public class ParallelEvaluatorTest {
ErrorInfo error = result.getError(parentErrorKey);
assertThat(error.getRootCauses()).containsExactly(errorKey);
StringValue abValue = result.get(errorFreeKey);
- assertEquals("ab", abValue.getValue());
+ assertThat(abValue.getValue()).isEqualTo("ab");
}
@Test
@@ -589,7 +586,7 @@ public class ParallelEvaluatorTest {
ErrorInfo error = result.getError(topKey);
assertThat(error.getRootCauses()).containsExactly(catastropheKey);
} else {
- assertTrue(result.hasError());
+ assertThat(result.hasError()).isTrue();
assertThat(result.errorMap()).isEmpty();
assertThat(result.getCatastrophe()).isSameAs(catastrophe);
}
@@ -607,10 +604,10 @@ public class ParallelEvaluatorTest {
// Child is guaranteed to complete successfully before parent can run (and fail),
// since parent depends on it.
StringValue childValue = result.get(childKey);
- Assert.assertNotNull(childValue);
- assertEquals("onions", childValue.getValue());
+ assertThat(childValue).isNotNull();
+ assertThat(childValue.getValue()).isEqualTo("onions");
ErrorInfo error = result.getError(parentKey);
- Assert.assertNotNull(error);
+ assertThat(error).isNotNull();
assertThat(error.getRootCauses()).containsExactly(parentKey);
}
@@ -654,13 +651,13 @@ public class ParallelEvaluatorTest {
EvaluationResult<SkyValue> result = eval(/*keepGoing=*/true, ImmutableList.of(recoveryKey));
assertThat(result.errorMap()).isEmpty();
assertThatEvaluationResult(result).hasNoError();
- assertEquals(new StringValue("i recovered"), result.get(recoveryKey));
+ assertThat(result.get(recoveryKey)).isEqualTo(new StringValue("i recovered"));
result = eval(/*keepGoing=*/false, ImmutableList.of(topKey));
assertThatEvaluationResult(result).hasError();
assertThat(result.keyNames()).isEmpty();
- assertEquals(1, result.errorMap().size());
- assertNotNull(result.getError(topKey).getException());
+ assertThat(result.errorMap()).hasSize(1);
+ assertThat(result.getError(topKey).getException()).isNotNull();
}
@Test
@@ -692,7 +689,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(parentKey).addDependency("mid").setComputedValue(CONCATENATE);
EvaluationResult<StringValue> result = eval(false, ImmutableList.of(parentKey));
Map.Entry<SkyKey, ErrorInfo> error = Iterables.getOnlyElement(result.errorMap().entrySet());
- assertEquals(parentKey, error.getKey());
+ assertThat(error.getKey()).isEqualTo(parentKey);
assertThat(error.getValue().getRootCauses()).containsExactly(errorKey);
}
@@ -708,7 +705,7 @@ public class ParallelEvaluatorTest {
false, new StringValue("unused"), ImmutableList.of(errorKey)));
EvaluationResult<StringValue> result = eval( /*keepGoing=*/false,
ImmutableList.of(parentKey, errorKey));
- assertEquals(result.toString(), 2, result.errorMap().size());
+ assertWithMessage(result.toString()).that(result.errorMap().size()).isEqualTo(2);
}
@Test
@@ -723,8 +720,8 @@ public class ParallelEvaluatorTest {
SkyKey[] list = { parentKey };
EvaluationResult<StringValue> result = eval(false, list);
ErrorInfo errorInfo = result.getError();
- assertEquals(errorKey, Iterables.getOnlyElement(errorInfo.getRootCauses()));
- assertEquals(errorKey.toString(), errorInfo.getException().getMessage());
+ assertThat(errorInfo.getRootCauses()).containsExactly(errorKey);
+ assertThat(errorInfo.getException()).hasMessageThat().isEqualTo(errorKey.toString());
}
@Test
@@ -741,7 +738,7 @@ public class ParallelEvaluatorTest {
/*notifyFinish=*/null, /*waitForException=*/false, /*value=*/null,
ImmutableList.<SkyKey>of()));
EvaluationResult<StringValue> result = eval(/*keepGoing=*/false, firstError, secondError);
- assertTrue(result.toString(), result.hasError());
+ assertWithMessage(result.toString()).that(result.hasError()).isTrue();
// With keepGoing=false, the eval call will terminate with exactly one error (the first one
// thrown). But the first one thrown here is non-deterministic since we synchronize the
// builders so that they run at roughly the same time.
@@ -757,10 +754,10 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(aKey).addDependency(bKey);
tester.getOrCreate(bKey).addDependency(aKey);
ErrorInfo errorInfo = eval(false, ImmutableList.of(aKey)).getError();
- assertEquals(null, errorInfo.getException());
+ assertThat(errorInfo.getException()).isNull();
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(aKey, bKey).inOrder();
- assertTrue(cycleInfo.getPathToCycle().isEmpty());
+ assertThat(cycleInfo.getPathToCycle()).isEmpty();
}
@Test
@@ -775,7 +772,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(aKey).addDependency(bKey);
tester.getOrCreate(bKey).addDependency(aKey);
ErrorInfo errorInfo = eval(false, ImmutableList.of(topKey)).getError();
- assertEquals(null, errorInfo.getException());
+ assertThat(errorInfo.getException()).isNull();
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(aKey, bKey).inOrder();
assertThat(cycleInfo.getPathToCycle()).containsExactly(topKey, midKey).inOrder();
@@ -791,7 +788,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(midKey).addDependency(aKey);
tester.getOrCreate(aKey).addDependency(aKey);
ErrorInfo errorInfo = eval(false, ImmutableList.of(topKey)).getError();
- assertEquals(null, errorInfo.getException());
+ assertThat(errorInfo.getException()).isNull();
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(aKey).inOrder();
assertThat(cycleInfo.getPathToCycle()).containsExactly(topKey, midKey).inOrder();
@@ -812,8 +809,8 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(aKey).addDependency(bKey);
tester.getOrCreate(bKey).addDependency(aKey);
EvaluationResult<StringValue> result = eval(true, topKey, goodKey);
- assertEquals(goodValue, result.get(goodKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(goodKey)).isEqualTo(goodValue);
+ assertThat(result.get(topKey)).isNull();
ErrorInfo errorInfo = result.getError(topKey);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(aKey, bKey).inOrder();
@@ -834,7 +831,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(cKey).addDependency(dKey);
tester.getOrCreate(dKey).addDependency(cKey);
EvaluationResult<StringValue> result = eval(false, ImmutableList.of(topKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
ErrorInfo errorInfo = result.getError(topKey);
Iterable<CycleInfo> cycles = CycleInfo.prepareCycles(topKey,
ImmutableList.of(new CycleInfo(ImmutableList.of(aKey, bKey)),
@@ -857,7 +854,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(cKey).addDependency(dKey);
tester.getOrCreate(dKey).addDependency(cKey);
EvaluationResult<StringValue> result = eval(true, ImmutableList.of(topKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
ErrorInfo errorInfo = result.getError(topKey);
CycleInfo aCycle = new CycleInfo(ImmutableList.of(topKey), ImmutableList.of(aKey, bKey));
CycleInfo cCycle = new CycleInfo(ImmutableList.of(topKey), ImmutableList.of(cKey, dKey));
@@ -876,7 +873,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(bKey).addDependency(cKey);
tester.getOrCreate(cKey).addDependency(topKey);
EvaluationResult<StringValue> result = eval(true, ImmutableList.of(topKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
ErrorInfo errorInfo = result.getError(topKey);
CycleInfo topCycle = new CycleInfo(ImmutableList.of(topKey, aKey, cKey));
assertThat(errorInfo.getCycleInfo()).containsExactly(topCycle);
@@ -894,7 +891,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(bKey).addDependency(cKey);
tester.getOrCreate(cKey).addDependency(topKey);
EvaluationResult<StringValue> result = eval(true, ImmutableList.of(topKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
ErrorInfo errorInfo = result.getError(topKey);
CycleInfo topCycle = new CycleInfo(ImmutableList.of(topKey, aKey, bKey, cKey));
assertThat(errorInfo.getCycleInfo()).containsExactly(topCycle);
@@ -913,7 +910,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(cKey);
tester.set(cKey, new StringValue("cValue"));
EvaluationResult<StringValue> result = eval(false, ImmutableList.of(topKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
ErrorInfo errorInfo = result.getError(topKey);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(aKey, bKey).inOrder();
@@ -931,7 +928,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(zKey).addDependency(cKey).addDependency(zKey);
tester.getOrCreate(cKey).addDependency(aKey);
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(aKey));
- assertEquals(null, result.get(aKey));
+ assertThat(result.get(aKey)).isNull();
ErrorInfo errorInfo = result.getError(aKey);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(zKey).inOrder();
@@ -951,7 +948,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(cKey).addDependency(aKey);
tester.getOrCreate(dKey).addDependency(bKey);
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(aKey));
- assertEquals(null, result.get(aKey));
+ assertThat(result.get(aKey)).isNull();
ErrorInfo errorInfo = result.getError(aKey);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(bKey, dKey).inOrder();
@@ -969,7 +966,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(bKey).addDependency(cKey);
tester.getOrCreate(cKey).addDependency(aKey).addDependency(bKey);
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(aKey));
- assertEquals(null, result.get(aKey));
+ assertThat(result.get(aKey)).isNull();
assertThat(result.getError(aKey).getCycleInfo()).containsExactly(
new CycleInfo(ImmutableList.of(aKey, bKey, cKey)),
new CycleInfo(ImmutableList.of(aKey), ImmutableList.of(bKey, cKey)));
@@ -985,8 +982,8 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(bKey).addDependency(bKey);
tester.getOrCreate(errorKey).setHasError(true);
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(aKey));
- assertEquals(null, result.get(aKey));
- assertNotNull(result.getError(aKey).getException());
+ assertThat(result.get(aKey)).isNull();
+ assertThat(result.getError(aKey).getException()).isNotNull();
CycleInfo cycleInfo = Iterables.getOnlyElement(result.getError(aKey).getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(bKey).inOrder();
assertThat(cycleInfo.getPathToCycle()).containsExactly(aKey).inOrder();
@@ -1026,7 +1023,7 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(dep).addDependency(dep);
}
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(topKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
assertManyCycles(result.getError(topKey), topKey, /*selfEdge=*/false);
}
@@ -1048,10 +1045,10 @@ public class ParallelEvaluatorTest {
tester.getOrCreate(dep).addDependency(cycleKey);
}
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(topKey));
- assertEquals(null, result.get(topKey));
+ assertThat(result.get(topKey)).isNull();
CycleInfo cycleInfo = Iterables.getOnlyElement(result.getError(topKey).getCycleInfo());
- assertEquals(1, cycleInfo.getCycle().size());
- assertEquals(3, cycleInfo.getPathToCycle().size());
+ assertThat(cycleInfo.getCycle()).hasSize(1);
+ assertThat(cycleInfo.getPathToCycle()).hasSize(3);
assertThat(cycleInfo.getPathToCycle().subList(0, 2)).containsExactly(topKey, midKey).inOrder();
}
@@ -1064,7 +1061,7 @@ public class ParallelEvaluatorTest {
assertThat(Iterables.size(errorInfo.getCycleInfo())).isLessThan(50);
boolean foundSelfEdge = false;
for (CycleInfo cycle : errorInfo.getCycleInfo()) {
- assertEquals(1, cycle.getCycle().size()); // Self-edge.
+ assertThat(cycle.getCycle()).hasSize(1); // Self-edge.
if (!Iterables.isEmpty(cycle.getPathToCycle())) {
assertThat(cycle.getPathToCycle()).containsExactly(topKey).inOrder();
} else {
@@ -1072,7 +1069,7 @@ public class ParallelEvaluatorTest {
foundSelfEdge = true;
}
}
- assertEquals(errorInfo + ", " + topKey, selfEdge, foundSelfEdge);
+ assertWithMessage(errorInfo + ", " + topKey).that(foundSelfEdge).isEqualTo(selfEdge);
}
@Test
@@ -1108,7 +1105,9 @@ public class ParallelEvaluatorTest {
// Check lastSelfKey.
ErrorInfo errorInfo = result.getError(lastSelfKey);
- assertEquals(errorInfo.toString(), 1, Iterables.size(errorInfo.getCycleInfo()));
+ assertWithMessage(errorInfo.toString())
+ .that(Iterables.size(errorInfo.getCycleInfo()))
+ .isEqualTo(1);
CycleInfo cycleInfo = Iterables.getOnlyElement(errorInfo.getCycleInfo());
assertThat(cycleInfo.getCycle()).containsExactly(lastSelfKey);
assertThat(cycleInfo.getPathToCycle()).isEmpty();
@@ -1152,11 +1151,11 @@ public class ParallelEvaluatorTest {
.setComputedValue(CONCATENATE).addDependency("after");
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(parentKey));
assertThat(result.errorMap()).isEmpty();
- assertEquals("recoveredafter", result.get(parentKey).getValue());
+ assertThat(result.get(parentKey).getValue()).isEqualTo("recoveredafter");
result = eval(/*keepGoing=*/false, ImmutableList.of(parentKey));
assertThat(result.keyNames()).isEmpty();
Map.Entry<SkyKey, ErrorInfo> error = Iterables.getOnlyElement(result.errorMap().entrySet());
- assertEquals(parentKey, error.getKey());
+ assertThat(error.getKey()).isEqualTo(parentKey);
assertThat(error.getValue().getRootCauses()).containsExactly(errorKey);
}
@@ -1172,7 +1171,7 @@ public class ParallelEvaluatorTest {
/*keepGoing=*/false, ImmutableList.of(parentErrorKey));
assertThat(result.keyNames()).isEmpty();
Map.Entry<SkyKey, ErrorInfo> error = Iterables.getOnlyElement(result.errorMap().entrySet());
- assertEquals(parentErrorKey, error.getKey());
+ assertThat(error.getKey()).isEqualTo(parentErrorKey);
assertThat(error.getValue().getRootCauses()).containsExactly(parentErrorKey);
}
@@ -1188,7 +1187,7 @@ public class ParallelEvaluatorTest {
/*keepGoing=*/true, ImmutableList.of(parentErrorKey));
assertThat(result.keyNames()).isEmpty();
Map.Entry<SkyKey, ErrorInfo> error = Iterables.getOnlyElement(result.errorMap().entrySet());
- assertEquals(parentErrorKey, error.getKey());
+ assertThat(error.getKey()).isEqualTo(parentErrorKey);
assertThat(error.getValue().getRootCauses()).containsExactly(parentErrorKey);
}
@@ -1206,7 +1205,7 @@ public class ParallelEvaluatorTest {
.setComputedValue(CONCATENATE);
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(topKey));
assertThat(ImmutableList.<String>copyOf(result.<String>keyNames())).containsExactly("top");
- assertEquals("parent valueafter", result.get(topKey).getValue());
+ assertThat(result.get(topKey).getValue()).isEqualTo("parent valueafter");
assertThat(result.errorMap()).isEmpty();
}
@@ -1225,7 +1224,7 @@ public class ParallelEvaluatorTest {
EvaluationResult<StringValue> result = eval(/*keepGoing=*/false, ImmutableList.of(topKey));
assertThat(result.keyNames()).isEmpty();
Map.Entry<SkyKey, ErrorInfo> error = Iterables.getOnlyElement(result.errorMap().entrySet());
- assertEquals(topKey, error.getKey());
+ assertThat(error.getKey()).isEqualTo(topKey);
assertThat(error.getValue().getRootCauses()).containsExactly(errorKey);
}
@@ -1496,9 +1495,12 @@ public class ParallelEvaluatorTest {
evaluator.eval(ImmutableList.of(LegacySkyKey.create(parentType, "octodad")));
fail();
} catch (RuntimeException e) {
- assertEquals("I WANT A PONY!!!", e.getCause().getMessage());
- assertEquals("Unrecoverable error while evaluating node 'child:billy the kid' "
- + "(requested by nodes 'parent:octodad')", e.getMessage());
+ assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("I WANT A PONY!!!");
+ assertThat(e)
+ .hasMessageThat()
+ .isEqualTo(
+ "Unrecoverable error while evaluating node 'child:billy the kid' "
+ + "(requested by nodes 'parent:octodad')");
}
}
@@ -1528,7 +1530,7 @@ public class ParallelEvaluatorTest {
.setComputedValue(CONCATENATE);
EvaluationResult<StringValue> result = eval(keepGoing, ImmutableList.of(topKey));
assertThat(result.keyNames()).isEmpty();
- assertSame(exception, result.getError(topKey).getException());
+ assertThat(result.getError(topKey).getException()).isSameAs(exception);
assertThat(result.getError(topKey).getRootCauses()).containsExactly(errorKey);
}
@@ -1579,7 +1581,7 @@ public class ParallelEvaluatorTest {
return null;
}
} catch (SomeErrorException e) {
- assertEquals(e.toString(), exception, e);
+ assertWithMessage(e.toString()).that(e).isEqualTo(exception);
}
if (keepGoing) {
return topValue;
@@ -1598,12 +1600,12 @@ public class ParallelEvaluatorTest {
EvaluationResult<StringValue> result = eval(keepGoing, ImmutableList.of(topKey));
if (!keepGoing) {
assertThat(result.keyNames()).isEmpty();
- assertEquals(topException, result.getError(topKey).getException());
+ assertThat(result.getError(topKey).getException()).isEqualTo(topException);
assertThat(result.getError(topKey).getRootCauses()).containsExactly(topKey);
assertThatEvaluationResult(result).hasError();
} else {
assertThatEvaluationResult(result).hasNoError();
- assertSame(topValue, result.get(topKey));
+ assertThat(result.get(topKey)).isSameAs(topValue);
}
}
@@ -1763,8 +1765,9 @@ public class ParallelEvaluatorTest {
}
});
EvaluationResult<StringValue> evaluationResult = eval(keepGoing, ImmutableList.of(parentKey));
- assertTrue(evaluationResult.hasError());
- assertEquals(keepGoing ? parentExn : childExn, evaluationResult.getError().getException());
+ assertThat(evaluationResult.hasError()).isTrue();
+ assertThat(evaluationResult.getError().getException())
+ .isEqualTo(keepGoing ? parentExn : childExn);
}
@Test
@@ -1798,7 +1801,7 @@ public class ParallelEvaluatorTest {
cycles.add(cycleInfo.getCycle());
}
// Skyframe doesn't automatically dedupe cycles that are the same except for entry point.
- assertEquals(2, cycles.size());
+ assertThat(cycles).hasSize(2);
int numUniqueCycles = 0;
CycleDeduper<SkyKey> cycleDeduper = new CycleDeduper<SkyKey>();
for (ImmutableList<SkyKey> cycle : cycles) {
@@ -1806,7 +1809,7 @@ public class ParallelEvaluatorTest {
numUniqueCycles++;
}
}
- assertEquals(1, numUniqueCycles);
+ assertThat(numUniqueCycles).isEqualTo(1);
}
@Test
@@ -1854,25 +1857,22 @@ public class ParallelEvaluatorTest {
tester.set("d3", new StringValue("3"));
driver.evaluate(ImmutableList.of(GraphTester.toSkyKey("top1")), false, 200, reporter);
- assertThat(enqueuedValues)
- .containsExactlyElementsIn(Arrays.asList(GraphTester.toSkyKeys("top1", "d1", "d2")));
- assertThat(evaluatedValues)
- .containsExactlyElementsIn(Arrays.asList(GraphTester.toSkyKeys("top1", "d1", "d2")));
+ assertThat(enqueuedValues).containsExactlyElementsIn(
+ GraphTester.toSkyKeys("top1", "d1", "d2"));
+ assertThat(evaluatedValues).containsExactlyElementsIn(
+ GraphTester.toSkyKeys("top1", "d1", "d2"));
enqueuedValues.clear();
evaluatedValues.clear();
driver.evaluate(ImmutableList.of(GraphTester.toSkyKey("top2")), false, 200, reporter);
- assertThat(enqueuedValues)
- .containsExactlyElementsIn(Arrays.asList(GraphTester.toSkyKeys("top2", "d3")));
- assertThat(evaluatedValues)
- .containsExactlyElementsIn(Arrays.asList(GraphTester.toSkyKeys("top2", "d3")));
+ assertThat(enqueuedValues).containsExactlyElementsIn(GraphTester.toSkyKeys("top2", "d3"));
+ assertThat(evaluatedValues).containsExactlyElementsIn(GraphTester.toSkyKeys("top2", "d3"));
enqueuedValues.clear();
evaluatedValues.clear();
driver.evaluate(ImmutableList.of(GraphTester.toSkyKey("top1")), false, 200, reporter);
assertThat(enqueuedValues).isEmpty();
- assertThat(evaluatedValues)
- .containsExactlyElementsIn(Arrays.asList(GraphTester.toSkyKeys("top1")));
+ assertThat(evaluatedValues).containsExactlyElementsIn(GraphTester.toSkyKeys("top1"));
}
public void runDepOnErrorHaltsNoKeepGoingBuildEagerly(boolean childErrorCached,
@@ -1898,31 +1898,33 @@ public class ParallelEvaluatorTest {
// On the first invocation, either the child error should already be cached and
// not propagated, or it should be computed freshly and not propagated. On the
// second build (error bubbling), the child error should be propagated.
- assertTrue("bogus non-null value " + value, value == null);
- assertEquals(
- "parent incorrectly re-computed during normal evaluation", 1, invocations);
- assertFalse(
- "child error not propagated during error bubbling",
- env.inErrorBubblingForTesting());
+ assertWithMessage("bogus non-null value " + value).that(value == null).isTrue();
+ assertWithMessage("parent incorrectly re-computed during normal evaluation")
+ .that(invocations)
+ .isEqualTo(1);
+ assertWithMessage("child error not propagated during error bubbling")
+ .that(env.inErrorBubblingForTesting())
+ .isFalse();
return value;
} catch (SomeErrorException e) {
- assertTrue(
- "child error propagated during normal evaluation",
- env.inErrorBubblingForTesting());
- assertEquals(2, invocations);
+ assertWithMessage("child error propagated during normal evaluation")
+ .that(env.inErrorBubblingForTesting())
+ .isTrue();
+ assertThat(invocations).isEqualTo(2);
return null;
}
} else {
if (invocations == 1) {
- assertFalse(
- "parent's first computation should be during normal evaluation",
- env.inErrorBubblingForTesting());
+ assertWithMessage(
+ "parent's first computation should be during normal evaluation")
+ .that(env.inErrorBubblingForTesting())
+ .isFalse();
return env.getValue(childKey);
} else {
- assertEquals(2, invocations);
- assertTrue(
- "parent incorrectly re-computed during normal evaluation",
- env.inErrorBubblingForTesting());
+ assertThat(invocations).isEqualTo(2);
+ assertWithMessage("parent incorrectly re-computed during normal evaluation")
+ .that(env.inErrorBubblingForTesting())
+ .isTrue();
return env.getValue(childKey);
}
}
@@ -1938,9 +1940,9 @@ public class ParallelEvaluatorTest {
evalValueInError(childKey);
}
EvaluationResult<StringValue> result = eval(/*keepGoing=*/false, ImmutableList.of(parentKey));
- assertEquals(2, numParentInvocations.get());
- assertTrue(result.hasError());
- assertEquals(childKey, result.getError().getRootCauseOfException());
+ assertThat(numParentInvocations.get()).isEqualTo(2);
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError().getRootCauseOfException()).isEqualTo(childKey);
}
@Test
@@ -1989,7 +1991,9 @@ public class ParallelEvaluatorTest {
public SkyValue compute(SkyKey skyKey, Environment env)
throws SkyFunctionException, InterruptedException {
int invocations = numOtherParentInvocations.incrementAndGet();
- assertEquals("otherParentKey should not be restarted", 1, invocations);
+ assertWithMessage("otherParentKey should not be restarted")
+ .that(invocations)
+ .isEqualTo(1);
return env.getValue(otherKey);
}
@@ -2042,19 +2046,19 @@ public class ParallelEvaluatorTest {
int invocations = numErrorParentInvocations.incrementAndGet();
try {
SkyValue value = env.getValueOrThrow(errorKey, SomeErrorException.class);
- assertTrue("bogus non-null value " + value, value == null);
+ assertWithMessage("bogus non-null value " + value).that(value == null).isTrue();
if (invocations == 1) {
return null;
} else {
- assertFalse(env.inErrorBubblingForTesting());
+ assertThat(env.inErrorBubblingForTesting()).isFalse();
fail("RACE CONDITION: errorParentKey was restarted!");
return null;
}
} catch (SomeErrorException e) {
- assertTrue(
- "child error propagated during normal evaluation",
- env.inErrorBubblingForTesting());
- assertEquals(2, invocations);
+ assertWithMessage("child error propagated during normal evaluation")
+ .that(env.inErrorBubblingForTesting())
+ .isTrue();
+ assertThat(invocations).isEqualTo(2);
return null;
}
}
@@ -2092,8 +2096,8 @@ public class ParallelEvaluatorTest {
});
EvaluationResult<StringValue> result = eval(/*keepGoing=*/false,
ImmutableList.of(otherParentKey, errorParentKey));
- assertTrue(result.hasError());
- assertEquals(errorKey, result.getError().getRootCauseOfException());
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError().getRootCauseOfException()).isEqualTo(errorKey);
}
@Test
@@ -2109,11 +2113,11 @@ public class ParallelEvaluatorTest {
new StringValue("parent2"));
tester.getOrCreate(errorKey).setHasError(true);
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(parent1Key));
- assertTrue(result.hasError());
- assertEquals(errorKey, result.getError().getRootCauseOfException());
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError().getRootCauseOfException()).isEqualTo(errorKey);
result = eval(/*keepGoing=*/false, ImmutableList.of(parent2Key));
- assertTrue(result.hasError());
- assertEquals(errorKey, result.getError(parent2Key).getRootCauseOfException());
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError(parent2Key).getRootCauseOfException()).isEqualTo(errorKey);
}
@Test
@@ -2123,8 +2127,8 @@ public class ParallelEvaluatorTest {
SkyKey errorKey = GraphTester.toSkyKey("error");
tester.getOrCreate(errorKey).setHasError(true);
EvaluationResult<StringValue> result = eval(/*keepGoing=*/true, ImmutableList.of(errorKey));
- assertTrue(result.hasError());
- assertEquals(errorKey, result.getError().getRootCauseOfException());
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError().getRootCauseOfException()).isEqualTo(errorKey);
SkyKey rogueKey = GraphTester.toSkyKey("rogue");
tester.getOrCreate(rogueKey).setBuilder(new SkyFunction() {
@Override
@@ -2141,9 +2145,9 @@ public class ParallelEvaluatorTest {
}
});
result = eval(/*keepGoing=*/false, ImmutableList.of(errorKey, rogueKey));
- assertTrue(result.hasError());
- assertEquals(errorKey, result.getError(errorKey).getRootCauseOfException());
- assertFalse(result.errorMap().containsKey(rogueKey));
+ assertThat(result.hasError()).isTrue();
+ assertThat(result.getError(errorKey).getRootCauseOfException()).isEqualTo(errorKey);
+ assertThat(result.errorMap()).doesNotContainKey(rogueKey);
}
private void runUnhandledTransitiveErrors(boolean keepGoing,
@@ -2199,9 +2203,9 @@ public class ParallelEvaluatorTest {
});
tester.getOrCreate(childKey).setHasError(/*hasError=*/true);
EvaluationResult<StringValue> result = eval(keepGoing, ImmutableList.of(grandparentKey));
- assertTrue(result.hasError());
- assertTrue(errorPropagated.get());
- assertEquals(grandparentKey, result.getError().getRootCauseOfException());
+ assertThat(result.hasError()).isTrue();
+ assertThat(errorPropagated.get()).isTrue();
+ assertThat(result.getError().getRootCauseOfException()).isEqualTo(grandparentKey);
}
@Test
diff --git a/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/MainTest.java b/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/MainTest.java
index 31cc9fc1cc..4cf8216437 100644
--- a/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/MainTest.java
+++ b/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/MainTest.java
@@ -38,7 +38,8 @@ public class MainTest {
Main.parseArgs(new String[] {"--workspace=workspace", "--version_between=1..2"});
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.isEqualTo("Argument --workspace and --output should not be empty.");
}
}
@@ -51,7 +52,8 @@ public class MainTest {
"--version_between=1..2", "--time_between=" + TIME_BETWEEN});
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage())
+ assertThat(e)
+ .hasMessageThat()
.isEqualTo("Please use exact one type of version filter at a time.");
}
}
@@ -63,9 +65,11 @@ public class MainTest {
new String[]{"--output=output", "--workspace=workspace", "--version_between=1.3"});
fail("Should throw OptionsParsingException");
} catch (OptionsParsingException e) {
- assertThat(e.getMessage())
- .isEqualTo("While parsing option --version_between=1.3: "
- + "Error parsing version_filter option: no '..' found.");
+ assertThat(e)
+ .hasMessageThat()
+ .isEqualTo(
+ "While parsing option --version_between=1.3: "
+ + "Error parsing version_filter option: no '..' found.");
}
}
@@ -88,9 +92,12 @@ public class MainTest {
"--time_between=" + TIME_BETWEEN_WRONG_FORMAT});
fail("Should throw OptionsParsingException");
} catch (OptionsParsingException e) {
- assertThat(e.getMessage())
- .isEqualTo("While parsing option --time_between=" + TIME_BETWEEN_WRONG_FORMAT
- + ": Error parsing datetime, format should be: yyyy-MM-ddTHH:mm:ss");
+ assertThat(e)
+ .hasMessageThat()
+ .isEqualTo(
+ "While parsing option --time_between="
+ + TIME_BETWEEN_WRONG_FORMAT
+ + ": Error parsing datetime, format should be: yyyy-MM-ddTHH:mm:ss");
}
}
diff --git a/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/BUILD b/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/BUILD
index 2c481da396..022a4037d2 100644
--- a/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/BUILD
+++ b/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/BUILD
@@ -7,6 +7,7 @@ java_test(
"//src/tools/benchmark/java/com/google/devtools/build/benchmark/codegenerator:codegenerator_lib",
"//third_party:guava",
"//third_party:junit4",
+ "//third_party:truth",
],
)
diff --git a/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorHelperTest.java b/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorHelperTest.java
index 15f41b30a5..1217e962a5 100644
--- a/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorHelperTest.java
+++ b/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorHelperTest.java
@@ -14,8 +14,7 @@
package com.google.devtools.build.benchmark.codegenerator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Joiner;
import java.io.IOException;
@@ -157,10 +156,10 @@ public class JavaCodeGeneratorHelperTest {
JavaCodeGeneratorHelper.writeRandomClassToDir(false, "ClassName", "com.package.name", dir);
Path javaFile = dir.resolve("com/package/name/ClassName.java");
- assertTrue(javaFile.toFile().exists());
+ assertThat(javaFile.toFile().exists()).isTrue();
String content = new Scanner(javaFile).useDelimiter("\\Z").next();
- assertEquals(RANDOM_CLASS_CONTENT, content);
+ assertThat(content).isEqualTo(RANDOM_CLASS_CONTENT);
}
@Test
@@ -169,10 +168,10 @@ public class JavaCodeGeneratorHelperTest {
JavaCodeGeneratorHelper.writeRandomClassToDir(true, "ClassNameExtra", "com.package.name", dir);
Path javaFile = dir.resolve("com/package/name/ClassNameExtra.java");
- assertTrue(javaFile.toFile().exists());
+ assertThat(javaFile.toFile().exists()).isTrue();
String content = new Scanner(javaFile).useDelimiter("\\Z").next();
- assertEquals(RANDOM_CLASS_EXTRA_CONTENT, content);
+ assertThat(content).isEqualTo(RANDOM_CLASS_EXTRA_CONTENT);
}
@Test
@@ -181,10 +180,10 @@ public class JavaCodeGeneratorHelperTest {
JavaCodeGeneratorHelper.writeMainClassToDir("com.package.name", dir);
Path javaFile = dir.resolve("com/package/name/Main.java");
- assertTrue(javaFile.toFile().exists());
+ assertThat(javaFile.toFile().exists()).isTrue();
String content = new Scanner(javaFile).useDelimiter("\\Z").next();
- assertEquals(MAIN_CLASS_CONTENT, content);
+ assertThat(content).isEqualTo(MAIN_CLASS_CONTENT);
}
@Test
@@ -194,10 +193,10 @@ public class JavaCodeGeneratorHelperTest {
JavaCodeGeneratorHelper.buildFileWithNextDeps(42, "<this is deps>", dir);
Path buildFile = dir.resolve("BUILD");
- assertTrue(buildFile.toFile().exists());
+ assertThat(buildFile.toFile().exists()).isTrue();
String content = new Scanner(buildFile).useDelimiter("\\Z").next();
- assertEquals(DEPS_BUILD_FILE_CONTENT, content);
+ assertThat(content).isEqualTo(DEPS_BUILD_FILE_CONTENT);
}
@Test
@@ -207,10 +206,10 @@ public class JavaCodeGeneratorHelperTest {
JavaCodeGeneratorHelper.buildFileWithMainClass("Target", "<this is deps>", dir);
Path buildFile = dir.resolve("BUILD");
- assertTrue(buildFile.toFile().exists());
+ assertThat(buildFile.toFile().exists()).isTrue();
String content = new Scanner(buildFile).useDelimiter("\\Z").next();
- assertEquals(TARGET_BUILD_FILE_CONTENT, content);
+ assertThat(content).isEqualTo(TARGET_BUILD_FILE_CONTENT);
}
@Test
@@ -219,10 +218,10 @@ public class JavaCodeGeneratorHelperTest {
JavaCodeGeneratorHelper.targetWithNextHelper(42, true, dir);
Path javaFile = dir.resolve("com/example/deps42/Deps42.java");
- assertTrue(javaFile.toFile().exists());
+ assertThat(javaFile.toFile().exists()).isTrue();
String content = new Scanner(javaFile).useDelimiter("\\Z").next();
- assertEquals(DEPS_CLASS_CONTENT, content);
+ assertThat(content).isEqualTo(DEPS_CLASS_CONTENT);
}
@Test
@@ -231,10 +230,10 @@ public class JavaCodeGeneratorHelperTest {
JavaCodeGeneratorHelper.targetWithNextExtraHelper(42, false, dir);
Path javaFile = dir.resolve("com/example/deps42/Deps42.java");
- assertTrue(javaFile.toFile().exists());
+ assertThat(javaFile.toFile().exists()).isTrue();
String content = new Scanner(javaFile).useDelimiter("\\Z").next();
- assertEquals(DEPS_CLASS_EXTRA_CONTENT, content);
+ assertThat(content).isEqualTo(DEPS_CLASS_EXTRA_CONTENT);
}
@Test
@@ -243,10 +242,10 @@ public class JavaCodeGeneratorHelperTest {
JavaCodeGeneratorHelper.parallelDepsMainClassHelper(4, dir);
Path javaFile = dir.resolve("com/example/generated/Main.java");
- assertTrue(javaFile.toFile().exists());
+ assertThat(javaFile.toFile().exists()).isTrue();
String content = new Scanner(javaFile).useDelimiter("\\Z").next();
- assertEquals(MAIN_CLASS_WITH_DEPS_CONTENT, content);
+ assertThat(content).isEqualTo(MAIN_CLASS_WITH_DEPS_CONTENT);
}
private static String joinLines(String... lines) {
diff --git a/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorTest.java b/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorTest.java
index 24db84f410..6472772216 100644
--- a/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorTest.java
+++ b/src/tools/benchmark/javatests/com/google/devtools/build/benchmark/codegenerator/JavaCodeGeneratorTest.java
@@ -15,10 +15,8 @@
package com.google.devtools.build.benchmark.codegenerator;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.assertNotNull;
import com.google.common.collect.ImmutableSet;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
@@ -47,7 +45,7 @@ public class JavaCodeGeneratorTest {
// Check dir contains 4 project directories
File[] filesList = dir.toFile().listFiles();
- assertNotNull(filesList);
+ assertThat(filesList).isNotNull();
ImmutableSet<String> filenames = fileArrayToImmutableSet(filesList);
assertThat(filenames).containsExactly(
JavaCodeGenerator.TARGET_A_FEW_FILES,
@@ -88,13 +86,13 @@ public class JavaCodeGeneratorTest {
private static void checkProjectPathContains(Path root, String targetName) {
// Check project dir contains BUILD and com
File[] filesList = root.resolve(targetName).toFile().listFiles();
- assertNotNull(filesList);
+ assertThat(filesList).isNotNull();
ImmutableSet<String> filenames = fileArrayToImmutableSet(filesList);
assertThat(filenames).containsExactly("BUILD", "com");
// Check project dir contains com/example
filesList = root.resolve(targetName).resolve("com").toFile().listFiles();
- assertNotNull(filesList);
+ assertThat(filesList).isNotNull();
filenames = fileArrayToImmutableSet(filesList);
assertThat(filenames).containsExactly("example");
}
@@ -103,7 +101,7 @@ public class JavaCodeGeneratorTest {
// Check Java files
File[] filesList =
root.resolve(targetName).resolve("com/example/generated").toFile().listFiles();
- assertNotNull(filesList);
+ assertThat(filesList).isNotNull();
ImmutableSet<String> filenames = fileArrayToImmutableSet(filesList);
ImmutableSet.Builder<String> randomClassNames = ImmutableSet.builder();
randomClassNames.add("Main.java");
@@ -118,13 +116,13 @@ public class JavaCodeGeneratorTest {
for (int i = 1; i < targetSize; ++i) {
File[] filesList =
root.resolve(targetName).resolve("com/example/deps" + i).toFile().listFiles();
- assertNotNull(filesList);
+ assertThat(filesList).isNotNull();
ImmutableSet<String> filenames = fileArrayToImmutableSet(filesList);
assertThat(filenames).containsExactly("Deps" + i + ".java");
}
File[] filesList =
root.resolve(targetName).resolve("com/example/generated").toFile().listFiles();
- assertNotNull(filesList);
+ assertThat(filesList).isNotNull();
ImmutableSet<String> filenames = fileArrayToImmutableSet(filesList);
assertThat(filenames).containsExactly("Main.java");
}