Codebase list mozc / debian/2.23.2815.102+dfsg-9 src / usage_stats / usage_stats_uploader_test.cc
debian/2.23.2815.102+dfsg-9

Tree @debian/2.23.2815.102+dfsg-9 (Download .tar.gz)

usage_stats_uploader_test.cc @debian/2.23.2815.102+dfsg-9raw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// Copyright 2010-2018, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "usage_stats/usage_stats_uploader.h"

#ifdef OS_ANDROID
#include <jni.h>
#endif  // OS_ANDROID

#include <algorithm>
#include <map>
#include <string>
#include <utility>
#include <vector>

#include "base/clock.h"
#include "base/port.h"
#include "base/singleton.h"
#include "base/system_util.h"
#include "base/util.h"
#include "base/version.h"
#include "base/win_util.h"
#include "config/config_handler.h"
#include "net/http_client.h"
#include "storage/registry.h"
#include "storage/storage_interface.h"
#include "testing/base/public/gunit.h"
#include "usage_stats/usage_stats.h"
#include "usage_stats/usage_stats.pb.h"
#include "usage_stats/usage_stats_testing_util.h"

#ifdef OS_ANDROID
#include "base/android_jni_mock.h"
#include "base/android_jni_proxy.h"
#include "base/android_util.h"
#endif  // OS_ANDROID

DECLARE_string(test_tmpdir);

namespace mozc {
namespace usage_stats {
namespace {

class TestableUsageStatsUploader : public UsageStatsUploader {
 public:
  // Change access rights.
  using UsageStatsUploader::LoadStats;
  using UsageStatsUploader::GetClientId;
};

class TestHTTPClient : public HTTPClientInterface {
 public:
  bool Get(const string &url, const HTTPClient::Option &option,
           string *output) const { return true; }
  bool Head(const string &url, const HTTPClient::Option &option,
            string *output) const { return true; }
  bool Post(const string &url, const string &data,
            const HTTPClient::Option &option, string *output) const {
    LOG(INFO) << "url: " << url;
    LOG(INFO) << "data: " << data;
    if (result_.expected_url != url) {
      LOG(INFO) << "expected_url: " << result_.expected_url;
      return false;
    }

    std::vector<string> data_set;
    Util::SplitStringUsing(data, "&", &data_set);
    for (size_t i = 0; i < expected_data_.size(); ++i) {
      std::vector<string>::const_iterator itr =
          std::find(data_set.begin(), data_set.end(), expected_data_[i]);
      const bool found = (itr != data_set.end());
      // we can't compile EXPECT_NE(itr, data_set.end()), so we use EXPECT_TRUE
      EXPECT_TRUE(found) << expected_data_[i];
    }

    *output = result_.expected_result;
    return true;
  }

  struct Result {
    string expected_url;
    string expected_result;
  };

  void set_result(const Result &result) {
    result_ = result;
  }

  // TODO(toshiyuki): integrate with struct Result
  void AddExpectedData(const string &data) {
    expected_data_.push_back(data);
  }

 private:
  // usage stats key and value parameter
  // format is "<key>:<type>=<value>"
  std::vector<string> expected_data_;
  Result result_;
};

const uint32 kOneDaySec = 24 * 60 * 60;  // 24 hours
const uint32 kHalfDaySec = 12 * 60 * 60;  // 12 hours
const char kBaseUrl[] =
#ifdef OS_NACL
    "https://clients4.google.com/tbproxy/usagestats";
#else  // OS_NACL
    "http://clients4.google.com/tbproxy/usagestats";
#endif  // OS_NACL
const char kTestClientId[] = "TestClientId";
const char kCountStatsKey[] = "Commit";
const uint32 kCountStatsDefaultValue = 100;
const char kIntegerStatsKey[] = "UserRegisteredWord";
const int kIntegerStatsDefaultValue = 2;

void SetUpMetaDataWithMozcVersion(uint32 last_upload_time,
                                  const string &mozc_version) {
  EXPECT_TRUE(storage::Registry::Insert("usage_stats.last_upload",
                                        last_upload_time));
  EXPECT_TRUE(storage::Registry::Insert("usage_stats.mozc_version",
                                        mozc_version));
}

void SetUpMetaData(uint32 last_upload_time) {
  SetUpMetaDataWithMozcVersion(last_upload_time, Version::GetMozcVersion());
}

class TestClientId : public ClientIdInterface {
 public:
  TestClientId() {}
  virtual ~TestClientId() {}
  void GetClientId(string *output) {
    *output = kTestClientId;
  }
};

class UsageStatsUploaderTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);

    TestableUsageStatsUploader::SetClientIdHandler(&client_id_);
    HTTPClient::SetHTTPClientHandler(&client_);
    EXPECT_TRUE(storage::Registry::Clear());

    // save test stats
    UsageStats::IncrementCountBy(kCountStatsKey, kCountStatsDefaultValue);
    EXPECT_COUNT_STATS(kCountStatsKey, kCountStatsDefaultValue);
    UsageStats::SetInteger(kIntegerStatsKey, kIntegerStatsDefaultValue);
    EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  }

  virtual void TearDown() {
    TestableUsageStatsUploader::SetClientIdHandler(NULL);
    HTTPClient::SetHTTPClientHandler(NULL);
    EXPECT_TRUE(storage::Registry::Clear());
  }

  void SetValidResult() {
    std::vector<std::pair<string, string> > params;
    params.push_back(std::make_pair("sourceid", "ime"));
    params.push_back(std::make_pair("hl", "ja"));
    params.push_back(std::make_pair("v", Version::GetMozcVersion()));
    params.push_back(std::make_pair("client_id", kTestClientId));
    params.push_back(
        std::make_pair("os_ver", SystemUtil::GetOSVersionString()));
#ifdef OS_ANDROID
    params.push_back(
        std::make_pair("model",
                       AndroidUtil::GetSystemProperty(
                           AndroidUtil::kSystemPropertyModel, "Unknown")));
#endif  // OS_ANDROID

    string url = string(kBaseUrl) + "?";
    Util::AppendCGIParams(params, &url);
    TestHTTPClient::Result result;
    result.expected_url = url;
    client_.set_result(result);
  }

  TestHTTPClient client_;
  TestClientId client_id_;
  scoped_usage_stats_enabler usage_stats_enabler_;
};

TEST_F(UsageStatsUploaderTest, SendTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  const uint32 last_upload_sec = current_sec - kOneDaySec;
  SetUpMetaData(last_upload_sec);
  SetValidResult();

  EXPECT_TRUE(TestableUsageStatsUploader::Send(NULL));

  // COUNT stats are cleared
  EXPECT_STATS_NOT_EXIST(kCountStatsKey);
  // INTEGER stats are not cleared
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  uint32 recorded_sec;
  string recorded_version;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.mozc_version",
                                        &recorded_version));
  EXPECT_LE(current_sec, recorded_sec);
  EXPECT_EQ(Version::GetMozcVersion(), recorded_version);
}

TEST_F(UsageStatsUploaderTest, FirstTimeSendTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  // Don't call SetUpMetaData()..
  SetValidResult();

  uint32 recorded_sec;
  string recorded_version;
  EXPECT_FALSE(storage::Registry::Lookup("usage_stats.last_upload",
                                         &recorded_sec));
  EXPECT_FALSE(storage::Registry::Lookup("usage_stats.mozc_version",
                                         &recorded_version));

  EXPECT_TRUE(TestableUsageStatsUploader::Send(NULL));

  EXPECT_STATS_NOT_EXIST(kCountStatsKey);
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.mozc_version",
                                        &recorded_version));
  EXPECT_LE(current_sec, recorded_sec);
  EXPECT_EQ(Version::GetMozcVersion(), recorded_version);
}

TEST_F(UsageStatsUploaderTest, SendFailTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  const uint32 last_upload_sec = current_sec - kHalfDaySec;
  SetUpMetaData(last_upload_sec);
  SetValidResult();

  EXPECT_FALSE(TestableUsageStatsUploader::Send(NULL));

  EXPECT_COUNT_STATS(kCountStatsKey, kCountStatsDefaultValue);
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  uint32 recorded_sec;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  EXPECT_EQ(last_upload_sec, recorded_sec);
}

TEST_F(UsageStatsUploaderTest, InvalidLastUploadTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  // future time
  // for example: time zone has changed
  const uint32 invalid_sec = current_sec + kHalfDaySec;
  SetUpMetaData(invalid_sec);
  SetValidResult();

  EXPECT_TRUE(TestableUsageStatsUploader::Send(NULL));

  EXPECT_STATS_NOT_EXIST(kCountStatsKey);
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  uint32 recorded_sec;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  // Save new last_upload_time
  EXPECT_LE(current_sec, recorded_sec);
}

TEST_F(UsageStatsUploaderTest, MozcVersionMismatchTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  const uint32 last_upload_sec = current_sec - kOneDaySec;
  SetUpMetaDataWithMozcVersion(last_upload_sec, "invalid_mozc_version");
  SetValidResult();

  EXPECT_TRUE(TestableUsageStatsUploader::Send(NULL));

  EXPECT_STATS_NOT_EXIST(kCountStatsKey);
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  uint32 recorded_sec;
  string recorded_version;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.mozc_version",
                                        &recorded_version));
  // Save new last_upload_time and recorded_version.
  EXPECT_LE(current_sec, recorded_sec);
  EXPECT_EQ(Version::GetMozcVersion(), recorded_version);
}

class TestStorage: public storage::StorageInterface {
 public:
  bool Open(const string &filename) { return true; }
  bool Sync() { return true; }
  bool Lookup(const string &key, string *value) const { return false; }
  // return false
  bool Insert(const string &key, const string &value) { return false; }
  bool Erase(const string &key) { return true; }
  bool Clear() { return true; }
  size_t Size() const { return 0; }
  TestStorage() {}
  virtual ~TestStorage() {}
};

TEST_F(UsageStatsUploaderTest, SaveMetadataFailTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  const uint32 last_upload_sec = current_sec - kOneDaySec;
  const string current_version = Version::GetMozcVersion();
  SetUpMetaData(last_upload_sec);
  SetValidResult();

  // set the TestStorage as a storage handler.
  // writing to the registry will be failed.
  storage::Registry::SetStorage(Singleton<TestStorage>::get());
  // confirm that we can not insert.
  EXPECT_FALSE(storage::Registry::Insert("usage_stats.last_upload",
                                         last_upload_sec));
  EXPECT_FALSE(storage::Registry::Insert("usage_stats.mozc_version",
                                         current_version));

  EXPECT_FALSE(TestableUsageStatsUploader::Send(NULL));
  // restore
  storage::Registry::SetStorage(NULL);

  // stats data are kept
  EXPECT_COUNT_STATS(kCountStatsKey, kCountStatsDefaultValue);
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  uint32 recorded_sec;
  string recorded_version;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.mozc_version",
                                        &recorded_version));
  EXPECT_EQ(last_upload_sec, recorded_sec);
  EXPECT_EQ(current_version, recorded_version);
}

TEST_F(UsageStatsUploaderTest, UploadFailTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  const uint32 last_upload_sec = current_sec - kOneDaySec;
  SetUpMetaData(last_upload_sec);
  SetValidResult();

  TestHTTPClient::Result result;
  // set dummy result url so that upload will be failed.
  result.expected_url = "fail_url";
  client_.set_result(result);

  EXPECT_FALSE(TestableUsageStatsUploader::Send(NULL));

  // stats data are not cleared
  EXPECT_COUNT_STATS(kCountStatsKey, kCountStatsDefaultValue);
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  // "UsageStatsUploadFailed" is incremented
  EXPECT_COUNT_STATS("UsageStatsUploadFailed", 1);
  uint32 recorded_sec;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  // last_upload is not updated
  EXPECT_EQ(last_upload_sec, recorded_sec);
}

TEST_F(UsageStatsUploaderTest, UploadRetryTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  const uint32 last_upload_sec = current_sec - kOneDaySec;
  SetUpMetaData(last_upload_sec);
  SetValidResult();

  TestHTTPClient::Result result;
  // set dummy result url so that upload will be failed.
  result.expected_url = "fail_url";
  client_.set_result(result);

  EXPECT_FALSE(TestableUsageStatsUploader::Send(NULL));

  // stats data are not cleared
  EXPECT_COUNT_STATS(kCountStatsKey, kCountStatsDefaultValue);
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  uint32 recorded_sec;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  // last_upload is not updated
  EXPECT_EQ(last_upload_sec, recorded_sec);

  // retry
  SetValidResult();
  // We can send stats if network is available.
  EXPECT_TRUE(TestableUsageStatsUploader::Send(NULL));

  // Stats are cleared
  EXPECT_STATS_NOT_EXIST(kCountStatsKey);
  // However, INTEGER stats are not cleared
  EXPECT_INTEGER_STATS(kIntegerStatsKey, kIntegerStatsDefaultValue);
  // last upload is updated
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.last_upload",
                                        &recorded_sec));
  EXPECT_LE(last_upload_sec, recorded_sec);
}

TEST_F(UsageStatsUploaderTest, UploadDataTest) {
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  const uint32 last_upload_sec = current_sec - kOneDaySec;
  SetUpMetaData(last_upload_sec);
  SetValidResult();

#ifdef OS_WIN
  const string win64 = (string("WindowsX64:b=")
                        + (SystemUtil::IsWindowsX64()? "t" : "f"));
  client_.AddExpectedData(win64);
#endif
  client_.AddExpectedData(Util::StringPrintf("%s:c=%u", kCountStatsKey,
                                             kCountStatsDefaultValue));
  client_.AddExpectedData(Util::StringPrintf("%s:i=%d", kIntegerStatsKey,
                                             kIntegerStatsDefaultValue));
  client_.AddExpectedData("Daily");

  EXPECT_TRUE(TestableUsageStatsUploader::Send(NULL));
}

void SetDoubleValueStats(
    uint32 num, double total, double square_total,
    usage_stats::Stats::DoubleValueStats *double_stats) {
  double_stats->set_num(num);
  double_stats->set_total(total);
  double_stats->set_square_total(square_total);
}

void SetEventStats(
    uint32 source_id,
    uint32 sx_num, double sx_total, double sx_square_total,
    uint32 sy_num, double sy_total, double sy_square_total,
    uint32 dx_num, double dx_total, double dx_square_total,
    uint32 dy_num, double dy_total, double dy_square_total,
    uint32 tl_num, double tl_total, double tl_square_total,
    usage_stats::Stats::TouchEventStats *event_stats) {
  event_stats->set_source_id(source_id);
  SetDoubleValueStats(sx_num, sx_total, sx_square_total,
                      event_stats->mutable_start_x_stats());
  SetDoubleValueStats(sy_num, sy_total, sy_square_total,
                      event_stats->mutable_start_y_stats());
  SetDoubleValueStats(dx_num, dx_total, dx_square_total,
                      event_stats->mutable_direction_x_stats());
  SetDoubleValueStats(dy_num, dy_total, dy_square_total,
                      event_stats->mutable_direction_y_stats());
  SetDoubleValueStats(tl_num, tl_total, tl_square_total,
                      event_stats->mutable_time_length_stats());
}

TEST_F(UsageStatsUploaderTest, UploadTouchEventStats) {
  // save last_upload
  const uint32 current_sec = static_cast<uint32>(Clock::GetTime());
  const uint32 last_upload_sec = current_sec - kOneDaySec;
  SetUpMetaData(last_upload_sec);
  SetValidResult();

  EXPECT_STATS_NOT_EXIST("VirtualKeyboardStats");
  EXPECT_STATS_NOT_EXIST("VirtualKeyboardMissStats");
  std::map<string, std::map<uint32, Stats::TouchEventStats> > touch_stats;
  std::map<string, std::map<uint32, Stats::TouchEventStats> > miss_touch_stats;

  Stats::TouchEventStats &event_stats1 = touch_stats["KEYBOARD_01"][10];
  SetEventStats(10, 2, 3, 8, 2, 4, 10, 2, 5, 16, 2, 2, 2,
                2, 3, 9, &event_stats1);

  Stats::TouchEventStats &event_stats2 = touch_stats["KEYBOARD_02"][20];
  SetEventStats(20, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
                114, 115, 116, &event_stats2);

  Stats::TouchEventStats &event_stats3 = touch_stats["KEYBOARD_01"][20];
  SetEventStats(20, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
                214, 215, 216, &event_stats3);

  Stats::TouchEventStats &event_stats4 = miss_touch_stats["KEYBOARD_01"][20];
  SetEventStats(20, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313,
                314, 315, 316, &event_stats4);

  Stats::TouchEventStats &event_stats5 = miss_touch_stats["KEYBOARD_01"][30];
  SetEventStats(30, 404, 406, 408, 410, 412, 414, 416, 418, 420, 422, 424, 426,
                428, 430, 432, &event_stats5);

  UsageStats::StoreTouchEventStats("VirtualKeyboardStats", touch_stats);
  UsageStats::StoreTouchEventStats("VirtualKeyboardMissStats",
                                   miss_touch_stats);

  Stats stats;
  EXPECT_TRUE(UsageStats::GetVirtualKeyboardForTest("VirtualKeyboardStats",
                                                    &stats));
  EXPECT_EQ(2, stats.virtual_keyboard_stats_size());
  EXPECT_EQ("KEYBOARD_01",
            stats.virtual_keyboard_stats(0).keyboard_name());
  EXPECT_EQ("KEYBOARD_02",
            stats.virtual_keyboard_stats(1).keyboard_name());
  EXPECT_EQ(2, stats.virtual_keyboard_stats(0).touch_event_stats_size());
  EXPECT_EQ(1, stats.virtual_keyboard_stats(1).touch_event_stats_size());

  EXPECT_EQ(event_stats1.DebugString(),
            stats.virtual_keyboard_stats(0).touch_event_stats(0).DebugString());
  EXPECT_EQ(event_stats3.DebugString(),
            stats.virtual_keyboard_stats(0).touch_event_stats(1).DebugString());
  EXPECT_EQ(event_stats2.DebugString(),
            stats.virtual_keyboard_stats(1).touch_event_stats(0).DebugString());

  EXPECT_TRUE(UsageStats::GetVirtualKeyboardForTest("VirtualKeyboardMissStats",
                                                    &stats));
  EXPECT_EQ(1, stats.virtual_keyboard_stats_size());
  EXPECT_EQ("KEYBOARD_01",
            stats.virtual_keyboard_stats(0).keyboard_name());
  EXPECT_EQ(2, stats.virtual_keyboard_stats(0).touch_event_stats_size());
  EXPECT_EQ(event_stats4.DebugString(),
            stats.virtual_keyboard_stats(0).touch_event_stats(0).DebugString());
  EXPECT_EQ(event_stats5.DebugString(),
            stats.virtual_keyboard_stats(0).touch_event_stats(1).DebugString());

  client_.AddExpectedData(string("vks%5Fname%5FKEYBOARD%5F01:i=0"));
  client_.AddExpectedData(string("vks%5Fname%5FKEYBOARD%5F02:i=1"));
  client_.AddExpectedData(string("vkms%5Fname%5FKEYBOARD%5F01:i=0"));

  // Average = total / num
  // Variance = square_total / num - (total / num) ^ 2
  // Because the current log analysis system can only deal with int values,
  // we multiply these values by a scale factor and send them to server.
  //   sxa, sya, dxa, dya : scale = 10000000
  //   sxv, syv, dxv, dyv : scale = 10000000
  //   tla, tlv : scale = 10000000

  // (3 / 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Fsxa:i=15000000"));
  // (8 / 2 - (3 / 2) ^ 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Fsxv:i=17500000"));
  // (4 / 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Fsya:i=20000000"));
  // (10 / 2 - (4 / 2) ^ 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Fsyv:i=10000000"));
  // (5 / 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Fdxa:i=25000000"));
  // (16 / 2 - (5 / 2) ^ 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Fdxv:i=17500000"));
  // (2 / 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Fdya:i=10000000"));
  // (2 / 2 - (2 / 2) ^ 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Fdyv:i=0"));
  // (3 / 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Ftla:i=15000000"));
  // (9 / 2 - (3 / 2) ^ 2) * 10000000
  client_.AddExpectedData(string("vks%5F0%5F10%5Ftlv:i=22500000"));
  EXPECT_TRUE(TestableUsageStatsUploader::Send(NULL));
}

TEST(ClientIdTest, CreateClientIdTest) {
  // test default client id handler here
  TestableUsageStatsUploader::SetClientIdHandler(NULL);
  SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);
  EXPECT_TRUE(storage::Registry::Clear());
  string client_id1;
  TestableUsageStatsUploader::GetClientId(&client_id1);
  string client_id_in_storage1;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.client_id",
                                        &client_id_in_storage1));
  EXPECT_TRUE(storage::Registry::Clear());
  string client_id2;
  TestableUsageStatsUploader::GetClientId(&client_id2);
  string client_id_in_storage2;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.client_id",
                                        &client_id_in_storage2));

  EXPECT_NE(client_id1, client_id2);
  EXPECT_NE(client_id_in_storage1, client_id_in_storage2);
}

TEST(ClientIdTest, GetClientIdTest) {
  // test default client id handler here.
  TestableUsageStatsUploader::SetClientIdHandler(NULL);
  SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);
  EXPECT_TRUE(storage::Registry::Clear());
  string client_id1;
  TestableUsageStatsUploader::GetClientId(&client_id1);
  string client_id2;
  TestableUsageStatsUploader::GetClientId(&client_id2);
  // we can get same client id.
  EXPECT_EQ(client_id1, client_id2);

  string client_id_in_storage;
  EXPECT_TRUE(storage::Registry::Lookup("usage_stats.client_id",
                                        &client_id_in_storage));
  // encrypted value is in storage
  EXPECT_NE(client_id1, client_id_in_storage);
}

TEST(ClientIdTest, GetClientIdFailTest) {
  // test default client id handler here.
  TestableUsageStatsUploader::SetClientIdHandler(NULL);
  SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);
  EXPECT_TRUE(storage::Registry::Clear());
  string client_id1;
  TestableUsageStatsUploader::GetClientId(&client_id1);
  // insert invalid data
  EXPECT_TRUE(storage::Registry::Insert("usage_stats.client_id",
                                        "invalid_data"));

  string client_id2;
  // decript should be failed
  TestableUsageStatsUploader::GetClientId(&client_id2);
  // new id should be generated
  EXPECT_NE(client_id1, client_id2);
}

}  // namespace
}  // namespace usage_stats
}  // namespace mozc