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 <gtest/gtest.h>
33 
34 #include "update_engine/common/action.h"
35 #include "update_engine/common/testing_constants.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 // Class to unmount FS when object goes out of scope
82 class ScopedFilesystemUnmounter {
83  public:
ScopedFilesystemUnmounter(const std::string & mountpoint)84   explicit ScopedFilesystemUnmounter(const std::string& mountpoint)
85       : mountpoint_(mountpoint), should_unmount_(true) {}
~ScopedFilesystemUnmounter()86   ~ScopedFilesystemUnmounter() {
87     if (should_unmount_) {
88       utils::UnmountFilesystem(mountpoint_);
89     }
90   }
set_should_unmount(bool unmount)91   void set_should_unmount(bool unmount) { should_unmount_ = unmount; }
92 
93  private:
94   const std::string mountpoint_;
95   bool should_unmount_;
96   DISALLOW_COPY_AND_ASSIGN(ScopedFilesystemUnmounter);
97 };
98 
99 class ScopedLoopbackDeviceBinder {
100  public:
ScopedLoopbackDeviceBinder(const std::string & file,bool writable,std::string * dev)101   ScopedLoopbackDeviceBinder(const std::string& file,
102                              bool writable,
103                              std::string* dev) {
104     is_bound_ = BindToUnusedLoopDevice(file, writable, &dev_);
105     EXPECT_TRUE(is_bound_);
106 
107     if (is_bound_ && dev)
108       *dev = dev_;
109   }
110 
~ScopedLoopbackDeviceBinder()111   ~ScopedLoopbackDeviceBinder() {
112     if (!is_bound_)
113       return;
114 
115     for (int retry = 0; retry < 5; retry++) {
116       if (UnbindLoopDevice(dev_))
117         return;
118       sleep(1);
119     }
120     ADD_FAILURE();
121   }
122 
dev()123   const std::string& dev() const {
124     EXPECT_TRUE(is_bound_);
125     return dev_;
126   }
127 
is_bound()128   bool is_bound() const { return is_bound_; }
129 
130  private:
131   std::string dev_;
132   bool is_bound_;
133   DISALLOW_COPY_AND_ASSIGN(ScopedLoopbackDeviceBinder);
134 };
135 
136 class ScopedLoopMounter {
137  public:
138   explicit ScopedLoopMounter(const std::string& file_path,
139                              std::string* mnt_path,
140                              unsigned long flags);  // NOLINT(runtime/int)
141 
142  private:
143   // These objects must be destructed in the following order:
144   //   ScopedFilesystemUnmounter (the file system must be unmounted first)
145   //   ScopedLoopbackDeviceBinder (then the loop device can be deleted)
146   //   ScopedDirRemover (then the mount point can be deleted)
147   base::ScopedTempDir temp_dir_;
148   std::unique_ptr<ScopedLoopbackDeviceBinder> loop_binder_;
149   std::unique_ptr<ScopedFilesystemUnmounter> unmounter_;
150 };
151 
152 // Returns the path where the build artifacts are stored. This is the directory
153 // where the unittest executable is being run from.
154 base::FilePath GetBuildArtifactsPath();
155 // Returns the path of the build artifact specified in |relative_path|.
156 std::string GetBuildArtifactsPath(const std::string& relative_path);
157 
158 }  // namespace test_utils
159 
160 // Useful actions for test. These need to be defined in the
161 // chromeos_update_engine namespace.
162 
163 class NoneType;
164 
165 template <typename T>
166 class ObjectFeederAction;
167 
168 template <typename T>
169 class ActionTraits<ObjectFeederAction<T>> {
170  public:
171   typedef T OutputObjectType;
172   typedef NoneType InputObjectType;
173 };
174 
175 // This is a simple Action class for testing. It feeds an object into
176 // another action.
177 template <typename T>
178 class ObjectFeederAction : public Action<ObjectFeederAction<T>> {
179  public:
180   typedef NoneType InputObjectType;
181   typedef T OutputObjectType;
PerformAction()182   void PerformAction() {
183     LOG(INFO) << "feeder running!";
184     CHECK(this->processor_);
185     if (this->HasOutputPipe()) {
186       this->SetOutputObject(out_obj_);
187     }
188     this->processor_->ActionComplete(this, ErrorCode::kSuccess);
189   }
StaticType()190   static std::string StaticType() { return "ObjectFeederAction"; }
Type()191   std::string Type() const { return StaticType(); }
set_obj(const T & out_obj)192   void set_obj(const T& out_obj) { out_obj_ = out_obj; }
193 
194  private:
195   T out_obj_;
196 };
197 
198 template <typename T>
199 class ObjectCollectorAction;
200 
201 template <typename T>
202 class ActionTraits<ObjectCollectorAction<T>> {
203  public:
204   typedef NoneType OutputObjectType;
205   typedef T InputObjectType;
206 };
207 
208 // This is a simple Action class for testing. It receives an object from
209 // another action.
210 template <typename T>
211 class ObjectCollectorAction : public Action<ObjectCollectorAction<T>> {
212  public:
213   typedef T InputObjectType;
214   typedef NoneType OutputObjectType;
PerformAction()215   void PerformAction() {
216     LOG(INFO) << "collector running!";
217     ASSERT_TRUE(this->processor_);
218     if (this->HasInputObject()) {
219       object_ = this->GetInputObject();
220     }
221     this->processor_->ActionComplete(this, ErrorCode::kSuccess);
222   }
StaticType()223   static std::string StaticType() { return "ObjectCollectorAction"; }
Type()224   std::string Type() const { return StaticType(); }
object()225   const T& object() const { return object_; }
226 
227  private:
228   T object_;
229 };
230 
231 }  // namespace chromeos_update_engine
232 
233 #endif  // UPDATE_ENGINE_COMMON_TEST_UTILS_H_
234