ccalvarin | 37c70a1 | 2018-08-13 10:31:15 -0700 | [diff] [blame] | 1 | // Copyright 2018 The Bazel Authors. All rights reserved. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | package com.google.devtools.build.lib.vfs; |
| 15 | |
| 16 | import static com.google.common.truth.Truth.assertThat; |
| 17 | |
| 18 | import com.google.common.collect.ImmutableList; |
| 19 | import java.nio.charset.StandardCharsets; |
| 20 | import java.util.Collection; |
| 21 | import org.junit.Test; |
| 22 | import org.junit.runner.RunWith; |
| 23 | import org.junit.runners.Parameterized; |
| 24 | import org.junit.runners.Parameterized.Parameter; |
| 25 | import org.junit.runners.Parameterized.Parameters; |
| 26 | |
| 27 | /** |
| 28 | * Tests different {@link DigestHashFunction} for consistency between the MessageDigests and the |
| 29 | * HashFunctions that it exposes. |
| 30 | */ |
| 31 | @RunWith(Parameterized.class) |
| 32 | public class DigestHashFunctionsTest { |
| 33 | @Parameters(name = "{index}: digestHashFunction={0}") |
| 34 | public static Collection<DigestHashFunction[]> hashFunctions() { |
| 35 | // TODO(b/112537387): Remove the array-ification and return Collection<DigestHashFunction>. This |
| 36 | // is possible in Junit4.12, but 4.11 requires the array. Bazel 0.18 will have Junit4.12, so |
| 37 | // this can change then. |
| 38 | return DigestHashFunction.getPossibleHashFunctions() |
| 39 | .stream() |
| 40 | .map(dhf -> new DigestHashFunction[] {dhf}) |
| 41 | .collect(ImmutableList.toImmutableList()); |
| 42 | } |
| 43 | |
| 44 | @Parameter public DigestHashFunction digestHashFunction; |
| 45 | |
| 46 | private void assertHashFunctionAndMessageDigestEquivalentForInput(byte[] input) { |
| 47 | byte[] hashFunctionOutput = digestHashFunction.getHashFunction().hashBytes(input).asBytes(); |
| 48 | byte[] messageDigestOutput = digestHashFunction.cloneOrCreateMessageDigest().digest(input); |
| 49 | assertThat(hashFunctionOutput).isEqualTo(messageDigestOutput); |
| 50 | } |
| 51 | |
| 52 | @Test |
| 53 | public void emptyDigestIsConsistent() { |
| 54 | assertHashFunctionAndMessageDigestEquivalentForInput(new byte[] {}); |
| 55 | } |
| 56 | |
| 57 | @Test |
| 58 | public void shortDigestIsConsistent() { |
| 59 | assertHashFunctionAndMessageDigestEquivalentForInput("Bazel".getBytes(StandardCharsets.UTF_8)); |
| 60 | } |
| 61 | } |