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 #ifndef _BSDIFF_TEST_UTILS_H_ 6 #define _BSDIFF_TEST_UTILS_H_ 7 8 #include <gtest/gtest.h> 9 #include <string> 10 #include <vector> 11 12 #include "bsdiff/logging.h" 13 14 #define TEST_AND_RETURN_FALSE(_x) \ 15 do { \ 16 if (!static_cast<bool>(_x)) { \ 17 LOG(ERROR) << #_x " failed."; \ 18 return false; \ 19 } \ 20 } while (0) 21 22 namespace test_utils { 23 24 class BsdiffTestEnvironment : public ::testing::Environment { 25 public: 26 virtual void SetUp(); 27 }; 28 29 // Reads all the contents of the file |path| into |out|. Returns whether it 30 // read up to the end of file. 31 bool ReadFile(const std::string& path, std::vector<uint8_t>* out); 32 33 // Overrides the file |path| with the contents passed in |out|. Returns whether 34 // the operation succeeded. 35 bool WriteFile(const std::string& path, std::vector<uint8_t> contents); 36 37 // Utility class to create and delete a temp file. 38 class ScopedTempFile { 39 public: 40 // Creates a temp file with the passed |pattern|. The pattern should end with 41 // "XXXXXX", that will be replaced with a random string. The file will be 42 // removed when this instance is destroyed. 43 explicit ScopedTempFile(const std::string& pattern); 44 ~ScopedTempFile(); 45 46 std::string filename() const { return filename_; } 47 const char* c_str() const { return filename_.c_str(); } 48 49 // Releases the temporary file. It will not be deleted when this instance is 50 // destroyed. 51 void release() { filename_.clear(); } 52 53 private: 54 std::string filename_; 55 }; 56 57 // This struct representes a parsed BSDIFF40 file. 58 struct BsdiffPatchFile { 59 static const size_t kHeaderSize = 32; 60 61 // Parses a BSDIFF40 file and stores the contents in the local methods. 62 bool LoadFromFile(const std::string& filename); 63 64 // Returns wheter the patch file is valid. 65 bool IsValid() const; 66 67 // The magic string in the header file. Normally "BSDIFF40". 68 std::string magic; 69 70 // The length of the first (ctrl) bzip2 stream. Negative values are invalid. 71 int64_t ctrl_len = -1; 72 73 // The length of the first (diff) bzip2 stream. Negative values are invalid. 74 int64_t diff_len = -1; 75 76 // The length of the first (diff) bzip2 stream. This value is not stored in 77 // the file, but generated based on the |file_size|. 78 uint64_t extra_len = 0; 79 80 // The length of the new file after applying the patch. Negative values are 81 // invalid. 82 int64_t new_file_len = -1; 83 84 // The three compressed streams. 85 std::vector<uint8_t> bz2_ctrl; 86 std::vector<uint8_t> bz2_diff; 87 std::vector<uint8_t> bz2_extra; 88 89 uint64_t file_size = 0; 90 }; 91 92 93 } // namespace test_utils 94 95 96 #endif // _BSDIFF_TEST_UTILS_H_ 97