Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / extensions / browser / content_hash_tree_unittest.cc
blobb5aada8c9ccdfaa3f43100490861d791e0b5d1b5
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/memory/scoped_ptr.h"
6 #include "base/stl_util.h"
7 #include "crypto/secure_hash.h"
8 #include "crypto/sha2.h"
9 #include "extensions/browser/content_hash_tree.h"
10 #include "testing/gtest/include/gtest/gtest.h"
12 using crypto::kSHA256Length;
13 using crypto::SecureHash;
15 // Helper to return a fake sha256 signature based on a seed.
16 static std::string FakeSignatureWithSeed(int seed) {
17 std::string input;
18 for (int i = 0; i < seed * 3; i++) {
19 input.push_back(static_cast<char>(((i + 19) * seed) % 256));
21 return crypto::SHA256HashString(input);
24 namespace extensions {
26 TEST(ContentHashTreeTest, HashTreeBasics) {
27 std::vector<std::string> nodes;
28 // Empty array.
29 EXPECT_EQ(std::string(), ComputeTreeHashRoot(nodes, 16));
31 // One node.
32 std::string node1 = FakeSignatureWithSeed(1);
33 nodes.push_back(node1);
34 EXPECT_EQ(node1, ComputeTreeHashRoot(nodes, 16));
36 // Two nodes.
37 std::string node2 = FakeSignatureWithSeed(2);
38 nodes.push_back(node2);
40 std::string expected(kSHA256Length, 0);
41 scoped_ptr<SecureHash> hash(SecureHash::Create(SecureHash::SHA256));
42 hash->Update(node1.data(), node1.size());
43 hash->Update(node2.data(), node2.size());
44 hash->Finish(string_as_array(&expected), expected.size());
45 EXPECT_EQ(expected, ComputeTreeHashRoot(nodes, 16));
48 TEST(ContentHashTreeTest, HashTreeMultipleLevels) {
49 std::vector<std::string> nodes;
50 for (int i = 0; i < 3; i++) {
51 std::string node;
52 nodes.push_back(FakeSignatureWithSeed(i));
55 // First try a test where our branch factor is >= 3, so we expect the result
56 // to be the hash of all 3 concatenated together. E.g the expected top hash
57 // should be 4 in the following diagram:
58 // 4
59 // 1 2 3
60 std::string expected =
61 crypto::SHA256HashString(nodes[0] + nodes[1] + nodes[2]);
62 EXPECT_EQ(expected, ComputeTreeHashRoot(nodes, 4));
64 // Now try making the branch factor be 2, so that we
65 // should get the following:
66 // 6
67 // 4 5
68 // 1 2 3
69 // where 4 is the hash of 1 and 2, 5 is the hash of 3, and 6 is the
70 // hash of 4 and 5.
71 std::string hash_of_first_2 = crypto::SHA256HashString(nodes[0] + nodes[1]);
72 std::string hash_of_third = crypto::SHA256HashString(nodes[2]);
73 expected = crypto::SHA256HashString(hash_of_first_2 + hash_of_third);
74 EXPECT_EQ(expected, ComputeTreeHashRoot(nodes, 2));
77 } // namespace extensions