Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / cert / internal / test_helpers.cc
blob0b5363d8acc7da720b37c2698226f91a189a9c0a
1 // Copyright 2015 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 "net/cert/internal/test_helpers.h"
7 #include "base/base64.h"
8 #include "base/base_paths.h"
9 #include "base/files/file_util.h"
10 #include "base/path_service.h"
11 #include "net/cert/pem_tokenizer.h"
13 namespace net {
15 namespace der {
17 void PrintTo(const Input& data, ::std::ostream* os) {
18 std::string b64;
19 base::Base64Encode(
20 base::StringPiece(reinterpret_cast<const char*>(data.UnsafeData()),
21 data.Length()),
22 &b64);
24 *os << "[" << b64 << "]";
27 bool operator==(const Input& a, const Input& b) {
28 return a.Equals(b);
31 } // namespace der
33 der::Input InputFromString(const std::string* s) {
34 return der::Input(reinterpret_cast<const uint8_t*>(s->data()), s->size());
37 ::testing::AssertionResult ReadTestDataFromPemFile(
38 const std::string& file_path_ascii,
39 const PemBlockMapping* mappings,
40 size_t mappings_length) {
41 // Compute the full path, relative to the src/ directory.
42 base::FilePath src_root;
43 PathService::Get(base::DIR_SOURCE_ROOT, &src_root);
44 base::FilePath filepath = src_root.AppendASCII(file_path_ascii);
46 // Read the full contents of the PEM file.
47 std::string file_data;
48 if (!base::ReadFileToString(filepath, &file_data)) {
49 return ::testing::AssertionFailure() << "Couldn't read file: "
50 << filepath.value();
53 // mappings_copy is used to keep track of which mappings have already been
54 // satisfied (by nulling the |value| field). This is used to track when
55 // blocks are mulitply defined.
56 std::vector<PemBlockMapping> mappings_copy(mappings,
57 mappings + mappings_length);
59 // Build the |pem_headers| vector needed for PEMTokenzier.
60 std::vector<std::string> pem_headers;
61 for (const auto& mapping : mappings_copy) {
62 pem_headers.push_back(mapping.block_name);
65 PEMTokenizer pem_tokenizer(file_data, pem_headers);
66 while (pem_tokenizer.GetNext()) {
67 for (auto& mapping : mappings_copy) {
68 // Find the mapping for this block type.
69 if (pem_tokenizer.block_type() == mapping.block_name) {
70 if (!mapping.value) {
71 return ::testing::AssertionFailure()
72 << "PEM block defined multiple times: " << mapping.block_name;
75 // Copy the data to the result.
76 mapping.value->assign(pem_tokenizer.data());
78 // Mark the mapping as having been satisfied.
79 mapping.value = nullptr;
84 // Ensure that all specified blocks were found.
85 for (const auto& mapping : mappings_copy) {
86 if (mapping.value && !mapping.optional) {
87 return ::testing::AssertionFailure() << "PEM block missing: "
88 << mapping.block_name;
92 return ::testing::AssertionSuccess();
95 } // namespace net