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