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"
17 void PrintTo(const Input
& data
, ::std::ostream
* os
) {
20 base::StringPiece(reinterpret_cast<const char*>(data
.UnsafeData()),
24 *os
<< "[" << b64
<< "]";
27 bool operator==(const Input
& a
, const Input
& b
) {
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: "
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
) {
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();