1// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <vector>
6
7#include "base/file_util.h"
8#include "base/path_service.h"
9#include "base/perftimer.h"
10#include "base/string_util.h"
11#include "base/values.h"
12#include "chrome/common/chrome_paths.h"
13#include "chrome/common/logging_chrome.h"
14#include "content/common/json_value_serializer.h"
15#include "testing/gtest/include/gtest/gtest.h"
16
17namespace {
18class JSONValueSerializerTests : public testing::Test {
19 protected:
20  virtual void SetUp() {
21    static const char* const kTestFilenames[] = {
22      "serializer_nested_test.js",
23      "serializer_test.js",
24      "serializer_test_nowhitespace.js",
25    };
26
27    // Load test cases
28    for (size_t i = 0; i < arraysize(kTestFilenames); ++i) {
29      FilePath filename;
30      EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &filename));
31      filename = filename.AppendASCII(kTestFilenames[i]);
32
33      std::string test_case;
34      EXPECT_TRUE(file_util::ReadFileToString(filename, &test_case));
35      test_cases_.push_back(test_case);
36    }
37  }
38
39  // Holds json strings to be tested.
40  std::vector<std::string> test_cases_;
41};
42
43}  // namespace
44
45// Test deserialization of a json string into a Value object.  We run the test
46// using 3 sample strings for both the current decoder and jsoncpp's decoder.
47TEST_F(JSONValueSerializerTests, Reading) {
48  printf("\n");
49  const int kIterations = 100000;
50
51  // Test chrome json implementation
52  PerfTimeLogger chrome_timer("chrome");
53  for (int i = 0; i < kIterations; ++i) {
54    for (size_t j = 0; j < test_cases_.size(); ++j) {
55      JSONStringValueSerializer reader(test_cases_[j]);
56      scoped_ptr<Value> root(reader.Deserialize(NULL, NULL));
57      ASSERT_TRUE(root.get());
58    }
59  }
60  chrome_timer.Done();
61}
62
63TEST_F(JSONValueSerializerTests, CompactWriting) {
64  printf("\n");
65  const int kIterations = 100000;
66  // Convert test cases to Value objects.
67  std::vector<Value*> test_cases;
68  for (size_t i = 0; i < test_cases_.size(); ++i) {
69    JSONStringValueSerializer reader(test_cases_[i]);
70    Value* root = reader.Deserialize(NULL, NULL);
71    ASSERT_TRUE(root);
72    test_cases.push_back(root);
73  }
74
75  PerfTimeLogger chrome_timer("chrome");
76  for (int i = 0; i < kIterations; ++i) {
77    for (size_t j = 0; j < test_cases.size(); ++j) {
78      std::string json;
79      JSONStringValueSerializer reader(&json);
80      ASSERT_TRUE(reader.Serialize(*test_cases[j]));
81    }
82  }
83  chrome_timer.Done();
84
85  // Clean up test cases.
86  for (size_t i = 0; i < test_cases.size(); ++i) {
87    delete test_cases[i];
88    test_cases[i] = NULL;
89  }
90}
91