TestUtil.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. #ifdef ENABLE_MESSAGE_DIGEST
  16. # include "MessageDigestHelper.h"
  17. #endif // ENABLE_MESSAGE_DIGEST
  18. namespace aria2 {
  19. void createFile(const std::string& path, size_t length)
  20. {
  21. File(File(path).getDirname()).mkdirs();
  22. int fd = creat(path.c_str(), OPEN_MODE);
  23. if(fd == -1) {
  24. throw FATAL_EXCEPTION(fmt("Could not create file=%s. cause:%s",
  25. path.c_str(),
  26. strerror(errno)));
  27. }
  28. if(-1 == ftruncate(fd, length)) {
  29. throw FATAL_EXCEPTION(fmt("ftruncate failed. cause:%s", strerror(errno)));
  30. }
  31. close(fd);
  32. }
  33. std::string readFile(const std::string& path)
  34. {
  35. std::stringstream ss;
  36. std::ifstream in(path.c_str(), std::ios::binary);
  37. char buf[4096];
  38. while(1) {
  39. in.read(buf, sizeof(buf));
  40. ss.write(buf, in.gcount());
  41. if(in.gcount() != sizeof(buf)) {
  42. break;
  43. }
  44. }
  45. return ss.str();
  46. }
  47. Cookie createCookie
  48. (const std::string& name,
  49. const std::string& value,
  50. const std::string& domain,
  51. bool hostOnly,
  52. const std::string& path,
  53. bool secure)
  54. {
  55. return Cookie
  56. (name, value, 0, false, domain, hostOnly, path, secure, false, 0);
  57. }
  58. Cookie createCookie
  59. (const std::string& name,
  60. const std::string& value,
  61. time_t expiryTime,
  62. const std::string& domain,
  63. bool hostOnly,
  64. const std::string& path,
  65. bool secure)
  66. {
  67. return Cookie
  68. (name, value, expiryTime, true, domain, hostOnly, path, secure, false, 0);
  69. }
  70. #ifdef ENABLE_MESSAGE_DIGEST
  71. std::string fileHexDigest
  72. (const SharedHandle<MessageDigest>& ctx, const std::string& filename)
  73. {
  74. SharedHandle<DiskWriter> writer(new DefaultDiskWriter(filename));
  75. writer->openExistingFile();
  76. return MessageDigestHelper::hexDigest(ctx, writer, 0, writer->size());
  77. }
  78. #endif // ENABLE_MESSAGE_DIGEST
  79. } // namespace aria2