TestUtil.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include "TestUtil.h"
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <fcntl.h>
  5. #include <cerrno>
  6. #include <cstring>
  7. #include <sstream>
  8. #include <fstream>
  9. #include "a2io.h"
  10. #include "File.h"
  11. #include "FatalException.h"
  12. #include "Cookie.h"
  13. #include "DefaultDiskWriter.h"
  14. #include "fmt.h"
  15. #include "util.h"
  16. #ifdef ENABLE_MESSAGE_DIGEST
  17. # include "message_digest_helper.h"
  18. #endif // ENABLE_MESSAGE_DIGEST
  19. namespace aria2 {
  20. void createFile(const std::string& path, size_t length)
  21. {
  22. File(File(path).getDirname()).mkdirs();
  23. DefaultDiskWriter dw(path);
  24. dw.initAndOpenFile();
  25. dw.truncate(length);
  26. }
  27. std::string readFile(const std::string& path)
  28. {
  29. std::stringstream ss;
  30. std::ifstream in(path.c_str(), std::ios::binary);
  31. char buf[4096];
  32. while(1) {
  33. in.read(buf, sizeof(buf));
  34. ss.write(buf, in.gcount());
  35. if(in.gcount() != sizeof(buf)) {
  36. break;
  37. }
  38. }
  39. return ss.str();
  40. }
  41. Cookie createCookie
  42. (const std::string& name,
  43. const std::string& value,
  44. const std::string& domain,
  45. bool hostOnly,
  46. const std::string& path,
  47. bool secure)
  48. {
  49. return Cookie
  50. (name, value, 0, false, domain, hostOnly, path, secure, false, 0);
  51. }
  52. Cookie createCookie
  53. (const std::string& name,
  54. const std::string& value,
  55. time_t expiryTime,
  56. const std::string& domain,
  57. bool hostOnly,
  58. const std::string& path,
  59. bool secure)
  60. {
  61. return Cookie
  62. (name, value, expiryTime, true, domain, hostOnly, path, secure, false, 0);
  63. }
  64. std::string fromHex(const std::string& s)
  65. {
  66. return util::fromHex(s.begin(), s.end());
  67. }
  68. #ifdef ENABLE_MESSAGE_DIGEST
  69. std::string fileHexDigest
  70. (const SharedHandle<MessageDigest>& ctx, const std::string& filename)
  71. {
  72. SharedHandle<DiskWriter> writer(new DefaultDiskWriter(filename));
  73. writer->openExistingFile();
  74. return util::toHex(message_digest::digest(ctx, writer, 0, writer->size()));
  75. }
  76. #endif // ENABLE_MESSAGE_DIGEST
  77. WrDiskCacheEntry::DataCell* createDataCell(int64_t goff,
  78. const char* data,
  79. size_t offset)
  80. {
  81. WrDiskCacheEntry::DataCell* cell = new WrDiskCacheEntry::DataCell();
  82. cell->goff = goff;
  83. size_t len = strlen(data);
  84. cell->data = new unsigned char[len];
  85. memcpy(cell->data, data, len);
  86. cell->offset = offset;
  87. cell->len = cell->capacity = len - offset;
  88. return cell;
  89. }
  90. } // namespace aria2