ostreamwrappertest.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #include "unittest.h"
  15. #include "rapidjson/ostreamwrapper.h"
  16. #include "rapidjson/encodedstream.h"
  17. #include "rapidjson/document.h"
  18. #include <sstream>
  19. #include <fstream>
  20. using namespace rapidjson;
  21. using namespace std;
  22. template <typename StringStreamType>
  23. static void TestStringStream() {
  24. typedef typename StringStreamType::char_type Ch;
  25. Ch s[] = { 'A', 'B', 'C', '\0' };
  26. StringStreamType oss(s);
  27. BasicOStreamWrapper<StringStreamType> os(oss);
  28. for (size_t i = 0; i < 3; i++)
  29. os.Put(s[i]);
  30. os.Flush();
  31. for (size_t i = 0; i < 3; i++)
  32. EXPECT_EQ(s[i], oss.str()[i]);
  33. }
  34. TEST(OStreamWrapper, ostringstream) {
  35. TestStringStream<ostringstream>();
  36. }
  37. TEST(OStreamWrapper, stringstream) {
  38. TestStringStream<stringstream>();
  39. }
  40. TEST(OStreamWrapper, wostringstream) {
  41. TestStringStream<wostringstream>();
  42. }
  43. TEST(OStreamWrapper, wstringstream) {
  44. TestStringStream<wstringstream>();
  45. }
  46. TEST(OStreamWrapper, cout) {
  47. OStreamWrapper os(cout);
  48. const char* s = "Hello World!\n";
  49. while (*s)
  50. os.Put(*s++);
  51. os.Flush();
  52. }
  53. template <typename FileStreamType>
  54. static void TestFileStream() {
  55. char filename[L_tmpnam];
  56. FILE* fp = TempFile(filename);
  57. fclose(fp);
  58. const char* s = "Hello World!\n";
  59. {
  60. ofstream ofs(filename, ios::out | ios::binary);
  61. BasicOStreamWrapper<ofstream> osw(ofs);
  62. for (const char* p = s; *p; p++)
  63. osw.Put(*p);
  64. osw.Flush();
  65. }
  66. fp = fopen(filename, "r");
  67. for (const char* p = s; *p; p++)
  68. EXPECT_EQ(*p, static_cast<char>(fgetc(fp)));
  69. fclose(fp);
  70. }
  71. TEST(OStreamWrapper, ofstream) {
  72. TestFileStream<ofstream>();
  73. }
  74. TEST(OStreamWrapper, fstream) {
  75. TestFileStream<fstream>();
  76. }