TestUtil.cc 2.0 KB

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