1 // Copyright 2015 The Chromium OS 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.
4
5 #include "chromeos-dbus-bindings/test_utils.h"
6
7 #include <string>
8 #include <vector>
9
10 #include <base/files/file_path.h>
11 #include <base/files/file_util.h>
12 #include <base/logging.h>
13 #include <brillo/process.h>
14 #include <gtest/gtest.h>
15
16 using std::string;
17 using std::vector;
18
19 namespace {
20
21 // Return the diff between the texts |a| and |b|.
GetUnifiedDiff(const string & a,const string & b)22 string GetUnifiedDiff(const string& a, const string& b) {
23 base::FilePath path_a, path_b;
24 if (!base::CreateTemporaryFile(&path_a) ||
25 !base::CreateTemporaryFile(&path_b)) {
26 return "Error creating temporary file";
27 }
28 WriteFile(path_a, a.data(), a.size());
29 WriteFile(path_b, b.data(), b.size());
30
31 brillo::ProcessImpl proc;
32 proc.AddArg("diff");
33 proc.AddArg("-u");
34 proc.AddArg(path_a.value());
35 proc.AddArg(path_b.value());
36 proc.SetSearchPath(true);
37 proc.RedirectUsingPipe(STDOUT_FILENO, false);
38 proc.Start();
39
40 int fd = proc.GetPipe(STDOUT_FILENO);
41 vector<char> buffer(32 * 1024);
42 string output;
43 while (true) {
44 int rc = read(fd, buffer.data(), buffer.size());
45 if (rc < 0) {
46 PLOG(ERROR) << "Reading from diff.";
47 break;
48 } else if (rc == 0) {
49 break;
50 } else {
51 output.append(buffer.data(), rc);
52 }
53 }
54 proc.Wait();
55
56 base::DeleteFile(path_a, false);
57 base::DeleteFile(path_b, false);
58 return output;
59 }
60
61 } // namespace
62
63 namespace chromeos_dbus_bindings {
64 namespace test_utils {
65
ExpectTextContained(const tracked_objects::Location & from_here,const string & expected_str,const string & expected_expr,const string & actual_str,const string & actual_expr)66 void ExpectTextContained(const tracked_objects::Location& from_here,
67 const string& expected_str,
68 const string& expected_expr,
69 const string& actual_str,
70 const string& actual_expr) {
71 if (string::npos != actual_str.find(expected_str))
72 return;
73
74 ADD_FAILURE_AT(from_here.file_name(), from_here.line_number())
75 << "Expected to find " << expected_expr << " within " << actual_expr
76 << ".\nHere is the diff:\n"
77 << GetUnifiedDiff(expected_str, actual_str);
78 }
79
80 } // namespace test_utils
81 } // namespace chromeos_dbus_bindings
82