• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef UPDATE_ENGINE_COMMON_TEST_UTILS_H_
18 #define UPDATE_ENGINE_COMMON_TEST_UTILS_H_
19 
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 
24 // Streams used for gtest's PrintTo() functions.
25 #include <iostream>  // NOLINT(readability/streams)
26 #include <memory>
27 #include <string>
28 #include <vector>
29 
30 #include <base/files/file_path.h>
31 #include <base/files/scoped_temp_dir.h>
32 #include <gmock/gmock.h>
33 #include <gtest/gtest.h>
34 
35 #include "update_engine/common/action.h"
36 #include "update_engine/common/utils.h"
37 #include "update_engine/update_metadata.pb.h"
38 
39 // These are some handy functions for unittests.
40 
41 namespace chromeos_update_engine {
42 
43 // PrintTo() functions are used by gtest to log these objects. These PrintTo()
44 // functions must be defined in the same namespace as the first argument.
45 void PrintTo(const Extent& extent, ::std::ostream* os);
46 void PrintTo(const ErrorCode& error_code, ::std::ostream* os);
47 
48 namespace test_utils {
49 
50 // 300 byte pseudo-random string. Not null terminated.
51 // This does not gzip compress well.
52 extern const uint8_t kRandomString[300];
53 
54 // Writes the data passed to path. The file at path will be overwritten if it
55 // exists. Returns true on success, false otherwise.
56 bool WriteFileVector(const std::string& path, const brillo::Blob& data);
57 bool WriteFileString(const std::string& path, const std::string& data);
58 
59 // Binds provided |filename| to an unused loopback device, whose name is written
60 // to the string pointed to by |out_lo_dev_name|. The new loop device will be
61 // read-only unless |writable| is set to true. Returns true on success, false
62 // otherwise (along with corresponding test failures), in which case the content
63 // of |out_lo_dev_name| is unknown.
64 bool BindToUnusedLoopDevice(const std::string& filename,
65                             bool writable,
66                             std::string* out_lo_dev_name);
67 bool UnbindLoopDevice(const std::string& lo_dev_name);
68 
69 // Returns true iff a == b
70 bool ExpectVectorsEq(const brillo::Blob& a, const brillo::Blob& b);
71 
System(const std::string & cmd)72 inline int System(const std::string& cmd) {
73   return system(cmd.c_str());
74 }
75 
76 // Reads a symlink from disk. Returns empty string on failure.
77 std::string Readlink(const std::string& path);
78 
79 void FillWithData(brillo::Blob* buffer);
80 
81 // Compare the value of native array for download source parameter.
82 MATCHER_P(DownloadSourceMatcher, source_array, "") {
83   return std::equal(source_array, source_array + kNumDownloadSources, arg);
84 }
85 
86 // Class to unmount FS when object goes out of scope
87 class ScopedFilesystemUnmounter {
88  public:
ScopedFilesystemUnmounter(const std::string & mountpoint)89   explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
90       : mountpoint_(mountpoint), should_unmount_(true) {}
~ScopedFilesystemUnmounter()91   ~ScopedFilesystemUnmounter() {
92     if (should_unmount_) {
93       utils::UnmountFilesystem(mountpoint_);
94     }
95   }
set_should_unmount(bool unmount)96   void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
97 
98  private:
99   const std::string mountpoint_;
100   bool should_unmount_;
101   DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
102 };
103 
104 class ScopedLoopbackDeviceBinder {
105  public:
ScopedLoopbackDeviceBinder(const std::string & file,bool writable,std::string * dev)106   ScopedLoopbackDeviceBinder(const std::string& file,
107                              bool writable,
108                              std::string* dev) {
109     is_bound_ = BindToUnusedLoopDevice(file, writable, &dev_);
110     EXPECT_TRUE(is_bound_);
111 
112     if (is_bound_ && dev)
113       *dev = dev_;
114   }
115 
~ScopedLoopbackDeviceBinder()116   ~ScopedLoopbackDeviceBinder() {
117     if (!is_bound_)
118       return;
119 
120     for (int retry = 0; retry < 5; retry++) {
121       if (UnbindLoopDevice(dev_))
122         return;
123       sleep(1);
124     }
125     ADD_FAILURE();
126   }
127 
dev()128   const std::string& dev() const {
129     EXPECT_TRUE(is_bound_);
130     return dev_;
131   }
132 
is_bound()133   bool is_bound() const { return is_bound_; }
134 
135  private:
136   std::string dev_;
137   bool is_bound_;
138   DISALLOW_COPY_AND_ASSIGN(ScopedLoopbackDeviceBinder);
139 };
140 
141 class ScopedTempFile {
142  public:
ScopedTempFile()143   ScopedTempFile() : ScopedTempFile("update_engine_test_temp_file.XXXXXX") {}
144 
ScopedTempFile(const std::string & pattern)145   explicit ScopedTempFile(const std::string& pattern) {
146     EXPECT_TRUE(utils::MakeTempFile(pattern, &path_, nullptr));
147     unlinker_.reset(new ScopedPathUnlinker(path_));
148   }
149 
path()150   const std::string& path() const { return path_; }
151 
152  private:
153   std::string path_;
154   std::unique_ptr<ScopedPathUnlinker> unlinker_;
155 };
156 
157 class ScopedLoopMounter {
158  public:
159   explicit ScopedLoopMounter(const std::string& file_path,
160                              std::string* mnt_path,
161                              unsigned long flags);  // NOLINT(runtime/int)
162 
163  private:
164   // These objects must be destructed in the following order:
165   //   ScopedFilesystemUnmounter (the file system must be unmounted first)
166   //   ScopedLoopbackDeviceBinder (then the loop device can be deleted)
167   //   ScopedDirRemover (then the mount point can be deleted)
168   base::ScopedTempDir temp_dir_;
169   std::unique_ptr<ScopedLoopbackDeviceBinder> loop_binder_;
170   std::unique_ptr<ScopedFilesystemUnmounter> unmounter_;
171 };
172 
173 // Returns the path where the build artifacts are stored. This is the directory
174 // where the unittest executable is being run from.
175 base::FilePath GetBuildArtifactsPath();
176 // Returns the path of the build artifact specified in |relative_path|.
177 std::string GetBuildArtifactsPath(const std::string& relative_path);
178 
179 }  // namespace test_utils
180 
181 // Useful actions for test. These need to be defined in the
182 // chromeos_update_engine namespace.
183 
184 class NoneType;
185 
186 template <typename T>
187 class ObjectFeederAction;
188 
189 template <typename T>
190 class ActionTraits<ObjectFeederAction<T>> {
191  public:
192   typedef T OutputObjectType;
193   typedef NoneType InputObjectType;
194 };
195 
196 // This is a simple Action class for testing. It feeds an object into
197 // another action.
198 template <typename T>
199 class ObjectFeederAction : public Action<ObjectFeederAction<T>> {
200  public:
201   typedef NoneType InputObjectType;
202   typedef T OutputObjectType;
PerformAction()203   void PerformAction() {
204     LOG(INFO) << "feeder running!";
205     CHECK(this->processor_);
206     if (this->HasOutputPipe()) {
207       this->SetOutputObject(out_obj_);
208     }
209     this->processor_->ActionComplete(this, ErrorCode::kSuccess);
210   }
StaticType()211   static std::string StaticType() { return "ObjectFeederAction"; }
Type()212   std::string Type() const { return StaticType(); }
set_obj(const T & out_obj)213   void set_obj(const T& out_obj) { out_obj_ = out_obj; }
214 
215  private:
216   T out_obj_;
217 };
218 
219 template <typename T>
220 class ObjectCollectorAction;
221 
222 template <typename T>
223 class ActionTraits<ObjectCollectorAction<T>> {
224  public:
225   typedef NoneType OutputObjectType;
226   typedef T InputObjectType;
227 };
228 
229 // This is a simple Action class for testing. It receives an object from
230 // another action.
231 template <typename T>
232 class ObjectCollectorAction : public Action<ObjectCollectorAction<T>> {
233  public:
234   typedef T InputObjectType;
235   typedef NoneType OutputObjectType;
PerformAction()236   void PerformAction() {
237     LOG(INFO) << "collector running!";
238     ASSERT_TRUE(this->processor_);
239     if (this->HasInputObject()) {
240       object_ = this->GetInputObject();
241     }
242     this->processor_->ActionComplete(this, ErrorCode::kSuccess);
243   }
StaticType()244   static std::string StaticType() { return "ObjectCollectorAction"; }
Type()245   std::string Type() const { return StaticType(); }
object()246   const T& object() const { return object_; }
247 
248  private:
249   T object_;
250 };
251 
252 }  // namespace chromeos_update_engine
253 
254 #endif  // UPDATE_ENGINE_COMMON_TEST_UTILS_H_
255