filestreamtest.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include "unittest.h"
  2. #include "rapidjson/filestream.h"
  3. #include "rapidjson/filereadstream.h"
  4. #include "rapidjson/filewritestream.h"
  5. #include "rapidjson/encodedstream.h"
  6. using namespace rapidjson;
  7. class FileStreamTest : public ::testing::Test {
  8. virtual void SetUp() {
  9. FILE *fp = fopen(filename_ = "data/sample.json", "rb");
  10. if (!fp)
  11. fp = fopen(filename_ = "../../bin/data/sample.json", "rb");
  12. ASSERT_TRUE(fp != 0);
  13. fseek(fp, 0, SEEK_END);
  14. length_ = (size_t)ftell(fp);
  15. fseek(fp, 0, SEEK_SET);
  16. json_ = (char*)malloc(length_ + 1);
  17. fread(json_, 1, length_, fp);
  18. json_[length_] = '\0';
  19. fclose(fp);
  20. }
  21. virtual void TearDown() {
  22. free(json_);
  23. }
  24. protected:
  25. const char* filename_;
  26. char *json_;
  27. size_t length_;
  28. };
  29. // Depreciated
  30. //TEST_F(FileStreamTest, FileStream_Read) {
  31. // FILE *fp = fopen(filename_, "rb");
  32. // ASSERT_TRUE(fp != 0);
  33. // FileStream s(fp);
  34. //
  35. // for (size_t i = 0; i < length_; i++) {
  36. // EXPECT_EQ(json_[i], s.Peek());
  37. // EXPECT_EQ(json_[i], s.Peek()); // 2nd time should be the same
  38. // EXPECT_EQ(json_[i], s.Take());
  39. // }
  40. //
  41. // EXPECT_EQ(length_, s.Tell());
  42. // EXPECT_EQ('\0', s.Peek());
  43. //
  44. // fclose(fp);
  45. //}
  46. TEST_F(FileStreamTest, FileReadStream) {
  47. FILE *fp = fopen(filename_, "rb");
  48. ASSERT_TRUE(fp != 0);
  49. char buffer[65536];
  50. FileReadStream s(fp, buffer, sizeof(buffer));
  51. for (size_t i = 0; i < length_; i++) {
  52. EXPECT_EQ(json_[i], s.Peek());
  53. EXPECT_EQ(json_[i], s.Peek()); // 2nd time should be the same
  54. EXPECT_EQ(json_[i], s.Take());
  55. }
  56. EXPECT_EQ(length_, s.Tell());
  57. EXPECT_EQ('\0', s.Peek());
  58. fclose(fp);
  59. }
  60. TEST_F(FileStreamTest, FileWriteStream) {
  61. char filename[L_tmpnam];
  62. tmpnam(filename);
  63. FILE *fp = fopen(filename, "wb");
  64. char buffer[65536];
  65. FileWriteStream os(fp, buffer, sizeof(buffer));
  66. for (size_t i = 0; i < length_; i++)
  67. os.Put(json_[i]);
  68. os.Flush();
  69. fclose(fp);
  70. // Read it back to verify
  71. fp = fopen(filename, "rb");
  72. FileReadStream is(fp, buffer, sizeof(buffer));
  73. for (size_t i = 0; i < length_; i++)
  74. EXPECT_EQ(json_[i], is.Take());
  75. EXPECT_EQ(length_, is.Tell());
  76. fclose(fp);
  77. //std::cout << filename << std::endl;
  78. remove(filename);
  79. }