Home | History | Annotate | Download | only in rappor
      1 // Copyright 2014 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 "components/rappor/rappor_service.h"
      6 
      7 #include "base/base64.h"
      8 #include "base/prefs/testing_pref_service.h"
      9 #include "components/rappor/byte_vector_utils.h"
     10 #include "components/rappor/proto/rappor_metric.pb.h"
     11 #include "components/rappor/rappor_parameters.h"
     12 #include "components/rappor/rappor_pref_names.h"
     13 #include "testing/gtest/include/gtest/gtest.h"
     14 
     15 namespace rappor {
     16 
     17 class TestRapporService : public RapporService {
     18  public:
     19   TestRapporService() : RapporService(&prefs_) {
     20     RegisterPrefs(prefs_.registry());
     21     prefs_.SetInteger(prefs::kRapporCohortSeed, 0);
     22     std::string secret = HmacByteVectorGenerator::GenerateEntropyInput();
     23     std::string secret_base64;
     24     base::Base64Encode(secret, &secret_base64);
     25     prefs_.SetString(prefs::kRapporSecret, secret_base64);
     26     LoadCohort();
     27     LoadSecret();
     28   }
     29 
     30   void GetReports(RapporReports* reports) {
     31     ExportMetrics(reports);
     32   }
     33 
     34   void TestRecordSample(const std::string& metric_name,
     35                         const RapporParameters& parameters,
     36                         const std::string& sample) {
     37     RecordSampleInternal(metric_name, parameters, sample);
     38   }
     39 
     40  protected:
     41   TestingPrefServiceSimple prefs_;
     42 
     43  private:
     44   DISALLOW_COPY_AND_ASSIGN(TestRapporService);
     45 };
     46 
     47 TEST(RapporServiceTest, RecordAndExportMetrics) {
     48   const RapporParameters kTestRapporParameters = {
     49       1 /* Num cohorts */,
     50       16 /* Bloom filter size bytes */,
     51       4 /* Bloom filter hash count */,
     52       PROBABILITY_75 /* Fake data probability */,
     53       PROBABILITY_50 /* Fake one probability */,
     54       PROBABILITY_75 /* One coin probability */,
     55       PROBABILITY_50 /* Zero coin probability */};
     56 
     57   TestRapporService rappor_service;
     58 
     59   rappor_service.TestRecordSample("MyMetric", kTestRapporParameters, "foo");
     60   rappor_service.TestRecordSample("MyMetric", kTestRapporParameters, "bar");
     61 
     62   RapporReports reports;
     63   rappor_service.GetReports(&reports);
     64   EXPECT_EQ(1, reports.report_size());
     65 
     66   const RapporReports::Report& report = reports.report(0);
     67   EXPECT_TRUE(report.name_hash());
     68   EXPECT_EQ(16u, report.bits().size());
     69 }
     70 
     71 }  // namespace rappor
     72