1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "mediametrics_tests"
18 #include <utils/Log.h>
19 
20 #include <stdio.h>
21 #include <string>
22 #include <unordered_set>
23 #include <vector>
24 
25 #include <gtest/gtest.h>
26 #include <media/MediaMetricsItem.h>
27 #include <mediametricsservice/AudioTypes.h>
28 #include <mediametricsservice/MediaMetricsService.h>
29 #include <mediametricsservice/StringUtils.h>
30 #include <mediametricsservice/ValidateId.h>
31 #include <system/audio.h>
32 
33 using namespace android;
34 using android::mediametrics::stringutils::parseVector;
35 
countNewlines(const char * s)36 static size_t countNewlines(const char *s) {
37     size_t count = 0;
38     while ((s = strchr(s, '\n')) != nullptr) {
39         ++s;
40         ++count;
41     }
42     return count;
43 }
44 
45 template <typename M>
countDuplicates(const M & map)46 ssize_t countDuplicates(const M& map) {
47     std::unordered_set<typename M::mapped_type> s;
48     for (const auto &m : map) {
49         s.emplace(m.second);
50     }
51     return map.size() - s.size();
52 }
53 
TEST(mediametrics_tests,startsWith)54 TEST(mediametrics_tests, startsWith) {
55   std::string s("test");
56   ASSERT_EQ(true, android::mediametrics::startsWith(s, "te"));
57   ASSERT_EQ(true, android::mediametrics::startsWith(s, std::string("tes")));
58   ASSERT_EQ(false, android::mediametrics::startsWith(s, "ts"));
59   ASSERT_EQ(false, android::mediametrics::startsWith(s, std::string("est")));
60 }
61 
TEST(mediametrics_tests,parseVector)62 TEST(mediametrics_tests, parseVector) {
63     {
64         std::vector<int32_t> values;
65         EXPECT_EQ(true, parseVector("0{4,300,0,-112343,350}9", &values));
66         EXPECT_EQ(values, std::vector<int32_t>({0, 4, 300, 0, -112343, 350, 9}));
67     }
68     {
69         std::vector<int32_t> values;
70         EXPECT_EQ(true, parseVector("53", &values));
71         EXPECT_EQ(values, std::vector<int32_t>({53}));
72     }
73     {
74         std::vector<int32_t> values;
75         EXPECT_EQ(false, parseVector("5{3,6*3}3", &values));
76         EXPECT_EQ(values, std::vector<int32_t>({}));
77     }
78     {
79         std::vector<int32_t> values = {1}; // should still be this when parsing fails
80         std::vector<int32_t> expected = {1};
81         EXPECT_EQ(false, parseVector("51342abcd,1232", &values));
82         EXPECT_EQ(values, std::vector<int32_t>({1}));
83     }
84     {
85         std::vector<int32_t> values = {2}; // should still be this when parsing fails
86         EXPECT_EQ(false, parseVector("12345678901234,12345678901234", &values));
87         EXPECT_EQ(values, std::vector<int32_t>({2}));
88     }
89 }
90 
TEST(mediametrics_tests,defer)91 TEST(mediametrics_tests, defer) {
92   bool check = false;
93   {
94       android::mediametrics::Defer defer([&] { check = true; });
95       ASSERT_EQ(false, check);
96   }
97   ASSERT_EQ(true, check);
98 }
99 
TEST(mediametrics_tests,shared_ptr_wrap)100 TEST(mediametrics_tests, shared_ptr_wrap) {
101   // Test shared pointer wrap with simple access
102   android::mediametrics::SharedPtrWrap<std::string> s("123");
103   ASSERT_EQ('1', s->at(0));
104   ASSERT_EQ('2', s->at(1));
105   s->push_back('4');
106   ASSERT_EQ('4', s->at(3));
107 
108   const android::mediametrics::SharedPtrWrap<std::string> s2("345");
109   ASSERT_EQ('3', s2->operator[](0));  // s2[0] == '3'
110   // we allow modification through a const shared pointer wrap
111   // for compatibility with shared_ptr.
112   s2->push_back('6');
113   ASSERT_EQ('6', s2->operator[](3));  // s2[3] == '6'
114 
115   android::mediametrics::SharedPtrWrap<std::string> s3("");
116   s3.set(std::make_shared<std::string>("abc"));
117   ASSERT_EQ('b', s3->operator[](1)); // s2[1] = 'b';
118 
119   // Use Thunk to check whether the destructor was called prematurely
120   // when setting the shared ptr wrap in the middle of a method.
121 
122   class Thunk {
123     std::function<void(int)> mF;
124     const int mFinal;
125 
126     public:
127       explicit Thunk(decltype(mF) f, int final) : mF(std::move(f)), mFinal(final) {}
128       ~Thunk() { mF(mFinal); }
129       void thunk(int value) { mF(value); }
130   };
131 
132   int counter = 0;
133   android::mediametrics::SharedPtrWrap<Thunk> s4(
134     [&](int value) {
135       s4.set(std::make_shared<Thunk>([](int){}, 0)); // recursively set s4 while in s4.
136       ++counter;
137       ASSERT_EQ(value, counter);  // on thunk() value is 1, on destructor this is 2.
138     }, 2);
139 
140   // This will fail if the shared ptr wrap doesn't hold a ref count during method access.
141   s4->thunk(1);
142 }
143 
TEST(mediametrics_tests,lock_wrap)144 TEST(mediametrics_tests, lock_wrap) {
145   // Test lock wrap with simple access
146   android::mediametrics::LockWrap<std::string> s("123");
147   ASSERT_EQ('1', s->at(0));
148   ASSERT_EQ('2', s->at(1));
149   s->push_back('4');
150   ASSERT_EQ('4', s->at(3));
151 
152   const android::mediametrics::LockWrap<std::string> s2("345");
153   ASSERT_EQ('3', s2->operator[](0));  // s2[0] == '3'
154   // note: we can't modify s2 due to const, s2->push_back('6');
155 
156   android::mediametrics::LockWrap<std::string> s3("");
157   s3->operator=("abc");
158   ASSERT_EQ('b', s3->operator[](1)); // s2[1] = 'b';
159 
160   // Check that we can recursively hold lock.
161   android::mediametrics::LockWrap<std::vector<int>> v{std::initializer_list<int>{1, 2}};
162   v->push_back(3);
163   v->push_back(4);
164   ASSERT_EQ(1, v->operator[](0));
165   ASSERT_EQ(2, v->operator[](1));
166   ASSERT_EQ(3, v->operator[](2));
167   ASSERT_EQ(4, v->operator[](3));
168   // The end of the full expression here requires recursive depth of 4.
169   ASSERT_EQ(10, v->operator[](0) + v->operator[](1) + v->operator[](2) + v->operator[](3));
170 
171   // Mikhail's note: a non-recursive lock implementation could be used if one obtains
172   // the LockedPointer helper object like this and directly hold the lock through RAII,
173   // though it is trickier in use.
174   //
175   // We include an example here for completeness.
176   {
177     auto l = v.operator->();
178     ASSERT_EQ(10, l->operator[](0) + l->operator[](1) + l->operator[](2) + l->operator[](3));
179   }
180 
181   // Use Thunk to check whether we have the lock when calling a method through LockWrap.
182 
183   class Thunk {
184     std::function<void()> mF;
185 
186     public:
187       explicit Thunk(decltype(mF) f) : mF(std::move(f)) {}
188       void thunk() { mF(); }
189   };
190 
191   android::mediametrics::LockWrap<Thunk> s4([&]{
192     ASSERT_EQ((size_t)1, s4.getRecursionDepth()); // we must be locked when thunk() is called.
193   });
194 
195   ASSERT_EQ((size_t)0, s4.getRecursionDepth());
196   // This will fail if we are not locked during method access.
197   s4->thunk();
198   ASSERT_EQ((size_t)0, s4.getRecursionDepth());
199 }
200 
TEST(mediametrics_tests,lock_wrap_multithread)201 TEST(mediametrics_tests, lock_wrap_multithread) {
202   class Accumulator {
203     int32_t value_ = 0;
204   public:
205     void add(int32_t incr) {
206       const int32_t temp = value_;
207       sleep(0);  // yield
208       value_ = temp + incr;
209     }
210     int32_t get() { return value_; }
211   };
212 
213   android::mediametrics::LockWrap<Accumulator> a{}; // locked accumulator succeeds
214   // auto a = std::make_shared<Accumulator>(); // this fails, only 50% adds atomic.
215 
216   constexpr size_t THREADS = 100;
217   constexpr size_t ITERATIONS = 10;
218   constexpr int32_t INCREMENT = 1;
219 
220   std::vector<std::future<void>> threads(THREADS);
221   for (size_t i = 0; i < THREADS; ++i) {
222     threads.push_back(std::async(std::launch::async, [&] {
223         for (size_t j = 0; j < ITERATIONS; ++j) {
224           a->add(INCREMENT);
225         }
226       }));
227   }
228   threads.clear();
229 
230   // If the add operations are not atomic, value will be smaller than expected.
231   ASSERT_EQ(INCREMENT * THREADS * ITERATIONS, (size_t)a->get());
232 }
233 
TEST(mediametrics_tests,instantiate)234 TEST(mediametrics_tests, instantiate) {
235   sp mediaMetrics = new MediaMetricsService();
236   status_t status;
237 
238   // random keys ignored when empty
239   std::unique_ptr<mediametrics::Item> random_key(mediametrics::Item::create("random_key"));
240   status = mediaMetrics->submit(random_key.get());
241   ASSERT_EQ(PERMISSION_DENIED, status);
242 
243   // random keys ignored with data
244   random_key->setInt32("foo", 10);
245   status = mediaMetrics->submit(random_key.get());
246   ASSERT_EQ(PERMISSION_DENIED, status);
247 
248   // known keys ignored if empty
249   std::unique_ptr<mediametrics::Item> audiotrack_key(mediametrics::Item::create("audiotrack"));
250   status = mediaMetrics->submit(audiotrack_key.get());
251   ASSERT_EQ(BAD_VALUE, status);
252 
253   // known keys not ignored if not empty
254   audiotrack_key->addInt32("foo", 10);
255   status = mediaMetrics->submit(audiotrack_key.get());
256   ASSERT_EQ(NO_ERROR, status);
257 
258 
259   /*
260   // fluent style that goes directly to mediametrics
261   ASSERT_EQ(true, mediametrics::Item("audiorecord")
262                      .setInt32("value", 2)
263                      .addInt32("bar", 1)
264                      .addInt32("value", 3)
265                      .selfrecord());
266   */
267 
268   mediaMetrics->dump(fileno(stdout), {} /* args */);
269 }
270 
TEST(mediametrics_tests,package_installer_check)271 TEST(mediametrics_tests, package_installer_check) {
272   ASSERT_EQ(false, MediaMetricsService::useUidForPackage(
273       "abcd", "installer"));  // ok, package name has no dot.
274   ASSERT_EQ(false, MediaMetricsService::useUidForPackage(
275       "android.com", "installer"));  // ok, package name starts with android
276 
277   ASSERT_EQ(false, MediaMetricsService::useUidForPackage(
278       "abc.def", "com.android.foo"));  // ok, installer name starts with com.android
279   ASSERT_EQ(false, MediaMetricsService::useUidForPackage(
280       "123.456", "com.google.bar"));  // ok, installer name starts with com.google
281   ASSERT_EQ(false, MediaMetricsService::useUidForPackage(
282       "r2.d2", "preload"));  // ok, installer name is preload
283 
284   ASSERT_EQ(true, MediaMetricsService::useUidForPackage(
285       "abc.def", "installer"));  // unknown installer
286   ASSERT_EQ(true, MediaMetricsService::useUidForPackage(
287       "123.456", "installer")); // unknown installer
288   ASSERT_EQ(true, MediaMetricsService::useUidForPackage(
289       "r2.d2", "preload23"));  // unknown installer
290 
291   ASSERT_EQ(true, MediaMetricsService::useUidForPackage(
292       "com.android.foo", "abc.def"));  // unknown installer
293   ASSERT_EQ(true, MediaMetricsService::useUidForPackage(
294       "com.google.bar", "123.456"));  // unknown installer
295 }
296 
TEST(mediametrics_tests,item_manipulation)297 TEST(mediametrics_tests, item_manipulation) {
298   mediametrics::Item item("audiorecord");
299 
300   item.setInt32("value", 2).addInt32("bar", 3).addInt32("value", 4);
301 
302   int32_t i32;
303   ASSERT_TRUE(item.getInt32("value", &i32));
304   ASSERT_EQ(6, i32);
305 
306   ASSERT_TRUE(item.getInt32("bar", &i32));
307   ASSERT_EQ(3, i32);
308 
309   item.setInt64("big", INT64_MAX).setInt64("smaller", INT64_MAX - 1).addInt64("smaller", -2);
310 
311   int64_t i64;
312   ASSERT_TRUE(item.getInt64("big", &i64));
313   ASSERT_EQ(INT64_MAX, i64);
314 
315   ASSERT_TRUE(item.getInt64("smaller", &i64));
316   ASSERT_EQ(INT64_MAX - 3, i64);
317 
318   item.setDouble("precise", 10.5).setDouble("small", 0.125).addDouble("precise", 0.25);
319 
320   double d;
321   ASSERT_TRUE(item.getDouble("precise", &d));
322   ASSERT_EQ(10.75, d);
323 
324   ASSERT_TRUE(item.getDouble("small", &d));
325   ASSERT_EQ(0.125, d);
326 
327   char *s;
328   item.setCString("name", "Frank").setCString("mother", "June").setCString("mother", "July");
329   ASSERT_TRUE(item.getCString("name", &s));
330   ASSERT_EQ(0, strcmp(s, "Frank"));
331   free(s);
332 
333   ASSERT_TRUE(item.getCString("mother", &s));
334   ASSERT_EQ(0, strcmp(s, "July"));  // "July" overwrites "June"
335   free(s);
336 
337   item.setRate("burgersPerHour", 5, 2);
338   int64_t b, h;
339   ASSERT_TRUE(item.getRate("burgersPerHour", &b, &h, &d));
340   ASSERT_EQ(5, b);
341   ASSERT_EQ(2, h);
342   ASSERT_EQ(2.5, d);
343 
344   item.addRate("burgersPerHour", 4, 2);
345   ASSERT_TRUE(item.getRate("burgersPerHour", &b, &h, &d));
346   ASSERT_EQ(9, b);
347   ASSERT_EQ(4, h);
348   ASSERT_EQ(2.25, d);
349 
350   printf("item: %s\n", item.toString().c_str());
351   fflush(stdout);
352 
353   sp mediaMetrics = new MediaMetricsService();
354   status_t status = mediaMetrics->submit(&item);
355   ASSERT_EQ(NO_ERROR, status);
356   mediaMetrics->dump(fileno(stdout), {} /* args */);
357 }
358 
TEST(mediametrics_tests,superbig_item)359 TEST(mediametrics_tests, superbig_item) {
360   mediametrics::Item item("TheBigOne");
361   constexpr size_t count = 10000;
362 
363   for (size_t i = 0; i < count; ++i) {
364     item.setInt32(std::to_string(i).c_str(), i);
365   }
366   for (size_t i = 0; i < count; ++i) {
367     int32_t i32;
368     ASSERT_TRUE(item.getInt32(std::to_string(i).c_str(), &i32));
369     ASSERT_EQ((int32_t)i, i32);
370   }
371 }
372 
TEST(mediametrics_tests,superbig_item_removal)373 TEST(mediametrics_tests, superbig_item_removal) {
374   mediametrics::Item item("TheOddBigOne");
375   constexpr size_t count = 10000;
376 
377   for (size_t i = 0; i < count; ++i) {
378     item.setInt32(std::to_string(i).c_str(), i);
379   }
380   for (size_t i = 0; i < count; i += 2) {
381     item.filter(std::to_string(i).c_str()); // filter out all the evens.
382   }
383   for (size_t i = 0; i < count; ++i) {
384     int32_t i32;
385     if (i & 1) { // check to see that only the odds are left.
386         ASSERT_TRUE(item.getInt32(std::to_string(i).c_str(), &i32));
387         ASSERT_EQ((int32_t)i, i32);
388     } else {
389         ASSERT_FALSE(item.getInt32(std::to_string(i).c_str(), &i32));
390     }
391   }
392 }
393 
TEST(mediametrics_tests,superbig_item_removal2)394 TEST(mediametrics_tests, superbig_item_removal2) {
395   mediametrics::Item item("TheOne");
396   constexpr size_t count = 10000;
397 
398   for (size_t i = 0; i < count; ++i) {
399     item.setInt32(std::to_string(i).c_str(), i);
400   }
401   static const char *attrs[] = { "1", };
402   item.filterNot(1, attrs);
403 
404   for (size_t i = 0; i < count; ++i) {
405     int32_t i32;
406     if (i == 1) { // check to see that there is only one
407         ASSERT_TRUE(item.getInt32(std::to_string(i).c_str(), &i32));
408         ASSERT_EQ((int32_t)i, i32);
409     } else {
410         ASSERT_FALSE(item.getInt32(std::to_string(i).c_str(), &i32));
411     }
412   }
413 }
414 
TEST(mediametrics_tests,item_transmutation)415 TEST(mediametrics_tests, item_transmutation) {
416   mediametrics::Item item("Alchemist's Stone");
417 
418   item.setInt64("convert", 123);
419   int64_t i64;
420   ASSERT_TRUE(item.getInt64("convert", &i64));
421   ASSERT_EQ(123, i64);
422 
423   item.addInt32("convert", 2);     // changes type of 'convert' from i64 to i32 (and re-init).
424   ASSERT_FALSE(item.getInt64("convert", &i64));  // should be false, no value in i64.
425 
426   int32_t i32;
427   ASSERT_TRUE(item.getInt32("convert", &i32));   // check it is i32 and 2 (123 is discarded).
428   ASSERT_EQ(2, i32);
429 }
430 
TEST(mediametrics_tests,item_binderization)431 TEST(mediametrics_tests, item_binderization) {
432   mediametrics::Item item;
433   item.setInt32("i32", 1)
434       .setInt64("i64", 2)
435       .setDouble("double", 3.1)
436       .setCString("string", "abc")
437       .setRate("rate", 11, 12);
438 
439   Parcel p;
440   item.writeToParcel(&p);
441 
442   p.setDataPosition(0); // rewind for reading
443   mediametrics::Item item2;
444   item2.readFromParcel(p);
445 
446   ASSERT_EQ(item, item2);
447 }
448 
TEST(mediametrics_tests,item_byteserialization)449 TEST(mediametrics_tests, item_byteserialization) {
450   mediametrics::Item item;
451   item.setInt32("i32", 1)
452       .setInt64("i64", 2)
453       .setDouble("double", 3.1)
454       .setCString("string", "abc")
455       .setRate("rate", 11, 12);
456 
457   char *data;
458   size_t length;
459   ASSERT_EQ(0, item.writeToByteString(&data, &length));
460   ASSERT_GT(length, (size_t)0);
461 
462   mediametrics::Item item2;
463   item2.readFromByteString(data, length);
464 
465   printf("item: %s\n", item.toString().c_str());
466   printf("item2: %s\n", item2.toString().c_str());
467   ASSERT_EQ(item, item2);
468 
469   free(data);
470 }
471 
TEST(mediametrics_tests,item_iteration)472 TEST(mediametrics_tests, item_iteration) {
473   mediametrics::Item item;
474   item.setInt32("i32", 1)
475       .setInt64("i64", 2)
476       .setDouble("double", 3.125)
477       .setCString("string", "abc")
478       .setRate("rate", 11, 12);
479 
480   int mask = 0;
481   for (auto &prop : item) {
482       const char *name = prop.getName();
483       if (!strcmp(name, "i32")) {
484           int32_t i32;
485           ASSERT_TRUE(prop.get(&i32));
486           ASSERT_EQ(1, i32);
487           ASSERT_EQ(1, std::get<int32_t>(prop.get()));
488           mask |= 1;
489       } else if (!strcmp(name, "i64")) {
490           int64_t i64;
491           ASSERT_TRUE(prop.get(&i64));
492           ASSERT_EQ(2, i64);
493           ASSERT_EQ(2, std::get<int64_t>(prop.get()));
494           mask |= 2;
495       } else if (!strcmp(name, "double")) {
496           double d;
497           ASSERT_TRUE(prop.get(&d));
498           ASSERT_EQ(3.125, d);
499           ASSERT_EQ(3.125, std::get<double>(prop.get()));
500           mask |= 4;
501       } else if (!strcmp(name, "string")) {
502           std::string s;
503           ASSERT_TRUE(prop.get(&s));
504           ASSERT_EQ("abc", s);
505           ASSERT_EQ(s, std::get<std::string>(prop.get()));
506           mask |= 8;
507       } else if (!strcmp(name, "rate")) {
508           std::pair<int64_t, int64_t> r;
509           ASSERT_TRUE(prop.get(&r));
510           ASSERT_EQ(11, r.first);
511           ASSERT_EQ(12, r.second);
512           ASSERT_EQ(r, std::get<decltype(r)>(prop.get()));
513           mask |= 16;
514       } else {
515           FAIL();
516       }
517   }
518   ASSERT_EQ(31, mask);
519 }
520 
TEST(mediametrics_tests,item_expansion)521 TEST(mediametrics_tests, item_expansion) {
522   mediametrics::LogItem<1> item("I");
523   item.set("i32", (int32_t)1)
524       .set("i64", (int64_t)2)
525       .set("double", (double)3.125)
526       .set("string", "abcdefghijklmnopqrstuvwxyz")
527       .set("rate", std::pair<int64_t, int64_t>(11, 12));
528   ASSERT_TRUE(item.updateHeader());
529 
530   mediametrics::Item item2;
531   item2.readFromByteString(item.getBuffer(), item.getLength());
532   ASSERT_EQ((pid_t)-1, item2.getPid());
533   ASSERT_EQ((uid_t)-1, item2.getUid());
534   int mask = 0;
535   for (auto &prop : item2) {
536       const char *name = prop.getName();
537       if (!strcmp(name, "i32")) {
538           int32_t i32;
539           ASSERT_TRUE(prop.get(&i32));
540           ASSERT_EQ(1, i32);
541           mask |= 1;
542       } else if (!strcmp(name, "i64")) {
543           int64_t i64;
544           ASSERT_TRUE(prop.get(&i64));
545           ASSERT_EQ(2, i64);
546           mask |= 2;
547       } else if (!strcmp(name, "double")) {
548           double d;
549           ASSERT_TRUE(prop.get(&d));
550           ASSERT_EQ(3.125, d);
551           mask |= 4;
552       } else if (!strcmp(name, "string")) {
553           std::string s;
554           ASSERT_TRUE(prop.get(&s));
555           ASSERT_EQ("abcdefghijklmnopqrstuvwxyz", s);
556           mask |= 8;
557       } else if (!strcmp(name, "rate")) {
558           std::pair<int64_t, int64_t> r;
559           ASSERT_TRUE(prop.get(&r));
560           ASSERT_EQ(11, r.first);
561           ASSERT_EQ(12, r.second);
562           mask |= 16;
563       } else {
564           FAIL();
565       }
566   }
567   ASSERT_EQ(31, mask);
568 }
569 
TEST(mediametrics_tests,item_expansion2)570 TEST(mediametrics_tests, item_expansion2) {
571   mediametrics::LogItem<1> item("Bigly");
572   item.setPid(123)
573       .setUid(456);
574   constexpr size_t count = 10000;
575 
576   for (size_t i = 0; i < count; ++i) {
577     // printf("recording %zu, %p, len:%zu of %zu  remaining:%zu \n", i, item.getBuffer(), item.getLength(), item.getCapacity(), item.getRemaining());
578     item.set(std::to_string(i).c_str(), (int32_t)i);
579   }
580   ASSERT_TRUE(item.updateHeader());
581 
582   mediametrics::Item item2;
583   printf("begin buffer:%p  length:%zu\n", item.getBuffer(), item.getLength());
584   fflush(stdout);
585   item2.readFromByteString(item.getBuffer(), item.getLength());
586 
587   ASSERT_EQ((pid_t)123, item2.getPid());
588   ASSERT_EQ((uid_t)456, item2.getUid());
589   for (size_t i = 0; i < count; ++i) {
590     int32_t i32;
591     ASSERT_TRUE(item2.getInt32(std::to_string(i).c_str(), &i32));
592     ASSERT_EQ((int32_t)i, i32);
593   }
594 }
595 
TEST(mediametrics_tests,time_machine_storage)596 TEST(mediametrics_tests, time_machine_storage) {
597   auto item = std::make_shared<mediametrics::Item>("Key");
598   (*item).set("i32", (int32_t)1)
599       .set("i64", (int64_t)2)
600       .set("double", (double)3.125)
601       .set("string", "abcdefghijklmnopqrstuvwxyz")
602       .set("rate", std::pair<int64_t, int64_t>(11, 12));
603 
604   // Let's put the item in
605   android::mediametrics::TimeMachine timeMachine;
606   ASSERT_EQ(NO_ERROR, timeMachine.put(item, true));
607 
608   // Can we read the values?
609   int32_t i32;
610   ASSERT_EQ(NO_ERROR, timeMachine.get("Key", "i32", &i32, -1));
611   ASSERT_EQ(1, i32);
612 
613   int64_t i64;
614   ASSERT_EQ(NO_ERROR, timeMachine.get("Key", "i64", &i64, -1));
615   ASSERT_EQ(2, i64);
616 
617   double d;
618   ASSERT_EQ(NO_ERROR, timeMachine.get("Key", "double", &d, -1));
619   ASSERT_EQ(3.125, d);
620 
621   std::string s;
622   ASSERT_EQ(NO_ERROR, timeMachine.get("Key", "string", &s, -1));
623   ASSERT_EQ("abcdefghijklmnopqrstuvwxyz", s);
624 
625   // Using fully qualified name?
626   i32 = 0;
627   ASSERT_EQ(NO_ERROR, timeMachine.get("Key.i32", &i32, -1));
628   ASSERT_EQ(1, i32);
629 
630   i64 = 0;
631   ASSERT_EQ(NO_ERROR, timeMachine.get("Key.i64", &i64, -1));
632   ASSERT_EQ(2, i64);
633 
634   d = 0.;
635   ASSERT_EQ(NO_ERROR, timeMachine.get("Key.double", &d, -1));
636   ASSERT_EQ(3.125, d);
637 
638   s.clear();
639   ASSERT_EQ(NO_ERROR, timeMachine.get("Key.string", &s, -1));
640   ASSERT_EQ("abcdefghijklmnopqrstuvwxyz", s);
641 }
642 
TEST(mediametrics_tests,time_machine_remote_key)643 TEST(mediametrics_tests, time_machine_remote_key) {
644   auto item = std::make_shared<mediametrics::Item>("Key1");
645   (*item).set("one", (int32_t)1)
646          .set("two", (int32_t)2);
647 
648   android::mediametrics::TimeMachine timeMachine;
649   ASSERT_EQ(NO_ERROR, timeMachine.put(item, true));
650 
651   auto item2 = std::make_shared<mediametrics::Item>("Key2");
652   (*item2).set("three", (int32_t)3)
653          .set("[Key1]four", (int32_t)4)   // affects Key1
654          .set("[Key1]five", (int32_t)5);  // affects key1
655 
656   ASSERT_EQ(NO_ERROR, timeMachine.put(item2, true));
657 
658   auto item3 = std::make_shared<mediametrics::Item>("Key2");
659   (*item3).set("six", (int32_t)6)
660          .set("[Key1]seven", (int32_t)7);   // affects Key1
661 
662   ASSERT_EQ(NO_ERROR, timeMachine.put(item3, false)); // remote keys not allowed.
663 
664   // Can we read the values?
665   int32_t i32;
666   ASSERT_EQ(NO_ERROR, timeMachine.get("Key1.one", &i32, -1));
667   ASSERT_EQ(1, i32);
668 
669   ASSERT_EQ(NO_ERROR, timeMachine.get("Key1.two", &i32, -1));
670   ASSERT_EQ(2, i32);
671 
672   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key1.three", &i32, -1));
673 
674   ASSERT_EQ(NO_ERROR, timeMachine.get("Key2.three", &i32, -1));
675   ASSERT_EQ(3, i32);
676 
677   ASSERT_EQ(NO_ERROR, timeMachine.get("Key1.four", &i32, -1));
678   ASSERT_EQ(4, i32);
679 
680   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key2.four", &i32, -1));
681 
682   ASSERT_EQ(NO_ERROR, timeMachine.get("Key1.five", &i32, -1));
683   ASSERT_EQ(5, i32);
684 
685   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key2.five", &i32, -1));
686 
687   ASSERT_EQ(NO_ERROR, timeMachine.get("Key2.six", &i32, -1));
688   ASSERT_EQ(6, i32);
689 
690   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key2.seven", &i32, -1));
691 }
692 
TEST(mediametrics_tests,time_machine_gc)693 TEST(mediametrics_tests, time_machine_gc) {
694   auto item = std::make_shared<mediametrics::Item>("Key1");
695   (*item).set("one", (int32_t)1)
696          .set("two", (int32_t)2)
697          .setTimestamp(10);
698 
699   android::mediametrics::TimeMachine timeMachine(1, 2); // keep at most 2 keys.
700 
701   ASSERT_EQ((size_t)0, timeMachine.size());
702 
703   ASSERT_EQ(NO_ERROR, timeMachine.put(item, true));
704 
705   ASSERT_EQ((size_t)1, timeMachine.size());
706 
707   auto item2 = std::make_shared<mediametrics::Item>("Key2");
708   (*item2).set("three", (int32_t)3)
709          .set("[Key1]three", (int32_t)3)
710          .setTimestamp(11);
711 
712   ASSERT_EQ(NO_ERROR, timeMachine.put(item2, true));
713   ASSERT_EQ((size_t)2, timeMachine.size());
714 
715   //printf("Before\n%s\n\n", timeMachine.dump().c_str());
716 
717   auto item3 = std::make_shared<mediametrics::Item>("Key3");
718   (*item3).set("six", (int32_t)6)
719           .set("[Key1]four", (int32_t)4)   // affects Key1
720           .set("[Key1]five", (int32_t)5)   // affects key1
721           .setTimestamp(12);
722 
723   ASSERT_EQ(NO_ERROR, timeMachine.put(item3, true));
724 
725   ASSERT_EQ((size_t)2, timeMachine.size());
726 
727   // Can we read the values?
728   int32_t i32;
729   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key1.one", &i32, -1));
730   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key1.two", &i32, -1));
731   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key1.three", &i32, -1));
732   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key1.four", &i32, -1));
733   ASSERT_EQ(BAD_VALUE, timeMachine.get("Key1.five", &i32, -1));
734 
735   ASSERT_EQ(NO_ERROR, timeMachine.get("Key2.three", &i32, -1));
736   ASSERT_EQ(3, i32);
737 
738   ASSERT_EQ(NO_ERROR, timeMachine.get("Key3.six", &i32, -1));
739   ASSERT_EQ(6, i32);
740 
741   printf("After\n%s\n", timeMachine.dump().first.c_str());
742 }
743 
TEST(mediametrics_tests,transaction_log_gc)744 TEST(mediametrics_tests, transaction_log_gc) {
745   auto item = std::make_shared<mediametrics::Item>("Key1");
746   (*item).set("one", (int32_t)1)
747          .set("two", (int32_t)2)
748          .setTimestamp(10);
749 
750   android::mediametrics::TransactionLog transactionLog(1, 2); // keep at most 2 items
751   ASSERT_EQ((size_t)0, transactionLog.size());
752 
753   ASSERT_EQ(NO_ERROR, transactionLog.put(item));
754   ASSERT_EQ((size_t)1, transactionLog.size());
755 
756   auto item2 = std::make_shared<mediametrics::Item>("Key2");
757   (*item2).set("three", (int32_t)3)
758          .set("[Key1]three", (int32_t)3)
759          .setTimestamp(11);
760 
761   ASSERT_EQ(NO_ERROR, transactionLog.put(item2));
762   ASSERT_EQ((size_t)2, transactionLog.size());
763 
764   auto item3 = std::make_shared<mediametrics::Item>("Key3");
765   (*item3).set("six", (int32_t)6)
766           .set("[Key1]four", (int32_t)4)   // affects Key1
767           .set("[Key1]five", (int32_t)5)   // affects key1
768           .setTimestamp(12);
769 
770   ASSERT_EQ(NO_ERROR, transactionLog.put(item3));
771   ASSERT_EQ((size_t)2, transactionLog.size());
772 }
773 
TEST(mediametrics_tests,analytics_actions)774 TEST(mediametrics_tests, analytics_actions) {
775   mediametrics::AnalyticsActions analyticsActions;
776   bool action1 = false;
777   bool action2 = false;
778   bool action3 = false;
779   bool action4 = false;
780 
781   // check to see whether various actions have been matched.
782   analyticsActions.addAction(
783       "audio.flinger.event",
784       std::string("AudioFlinger"),
785       std::make_shared<mediametrics::AnalyticsActions::Function>(
786           [&](const std::shared_ptr<const android::mediametrics::Item> &) {
787             action1 = true;
788           }));
789 
790   analyticsActions.addAction(
791       "audio.*.event",
792       std::string("AudioFlinger"),
793       std::make_shared<mediametrics::AnalyticsActions::Function>(
794           [&](const std::shared_ptr<const android::mediametrics::Item> &) {
795             action2 = true;
796           }));
797 
798   analyticsActions.addAction("audio.fl*n*g*r.event",
799       std::string("AudioFlinger"),
800       std::make_shared<mediametrics::AnalyticsActions::Function>(
801           [&](const std::shared_ptr<const android::mediametrics::Item> &) {
802             action3 = true;
803           }));
804 
805   analyticsActions.addAction("audio.fl*gn*r.event",
806       std::string("AudioFlinger"),
807       std::make_shared<mediametrics::AnalyticsActions::Function>(
808           [&](const std::shared_ptr<const android::mediametrics::Item> &) {
809             action4 = true;
810           }));
811 
812   // make a test item
813   auto item = std::make_shared<mediametrics::Item>("audio.flinger");
814   (*item).set("event", "AudioFlinger");
815 
816   // get the actions and execute them
817   auto actions = analyticsActions.getActionsForItem(item);
818   for (const auto& action : actions) {
819     action->operator()(item);
820   }
821 
822   // The following should match.
823   ASSERT_EQ(true, action1);
824   ASSERT_EQ(true, action2);
825   ASSERT_EQ(true, action3);
826   ASSERT_EQ(false, action4); // audio.fl*gn*r != audio.flinger
827 }
828 
TEST(mediametrics_tests,audio_analytics_permission)829 TEST(mediametrics_tests, audio_analytics_permission) {
830   auto item = std::make_shared<mediametrics::Item>("audio.1");
831   (*item).set("one", (int32_t)1)
832          .set("two", (int32_t)2)
833          .setTimestamp(10);
834 
835   auto item2 = std::make_shared<mediametrics::Item>("audio.1");
836   (*item2).set("three", (int32_t)3)
837          .setTimestamp(11);
838 
839   auto item3 = std::make_shared<mediametrics::Item>("audio.2");
840   (*item3).set("four", (int32_t)4)
841           .setTimestamp(12);
842 
843   std::shared_ptr<mediametrics::StatsdLog> statsdLog =
844           std::make_shared<mediametrics::StatsdLog>(10);
845   android::mediametrics::AudioAnalytics audioAnalytics{statsdLog};
846 
847   // untrusted entities cannot create a new key.
848   ASSERT_EQ(PERMISSION_DENIED, audioAnalytics.submit(item, false /* isTrusted */));
849   ASSERT_EQ(PERMISSION_DENIED, audioAnalytics.submit(item2, false /* isTrusted */));
850 
851   // TODO: Verify contents of AudioAnalytics.
852   // Currently there is no getter API in AudioAnalytics besides dump.
853   ASSERT_EQ(10, audioAnalytics.dump(1000).second /* lines */);
854 
855   ASSERT_EQ(NO_ERROR, audioAnalytics.submit(item, true /* isTrusted */));
856   // untrusted entities can add to an existing key
857   ASSERT_EQ(NO_ERROR, audioAnalytics.submit(item2, false /* isTrusted */));
858 
859   // Check that we have some info in the dump.
860   ASSERT_LT(9, audioAnalytics.dump(1000).second /* lines */);
861 }
862 
TEST(mediametrics_tests,audio_analytics_permission2)863 TEST(mediametrics_tests, audio_analytics_permission2) {
864   constexpr int32_t transactionUid = 1010; // arbitrary
865   auto item = std::make_shared<mediametrics::Item>("audio.1");
866   (*item).set("one", (int32_t)1)
867          .set("two", (int32_t)2)
868          .set(AMEDIAMETRICS_PROP_ALLOWUID, transactionUid)
869          .setTimestamp(10);
870 
871   // item2 submitted untrusted
872   auto item2 = std::make_shared<mediametrics::Item>("audio.1");
873   (*item2).set("three", (int32_t)3)
874          .setUid(transactionUid)
875          .setTimestamp(11);
876 
877   auto item3 = std::make_shared<mediametrics::Item>("audio.2");
878   (*item3).set("four", (int32_t)4)
879           .setTimestamp(12);
880 
881   std::shared_ptr<mediametrics::StatsdLog> statsdLog =
882           std::make_shared<mediametrics::StatsdLog>(10);
883   android::mediametrics::AudioAnalytics audioAnalytics{statsdLog};
884 
885   // untrusted entities cannot create a new key.
886   ASSERT_EQ(PERMISSION_DENIED, audioAnalytics.submit(item, false /* isTrusted */));
887   ASSERT_EQ(PERMISSION_DENIED, audioAnalytics.submit(item2, false /* isTrusted */));
888 
889   // TODO: Verify contents of AudioAnalytics.
890   // Currently there is no getter API in AudioAnalytics besides dump.
891   ASSERT_EQ(10, audioAnalytics.dump(1000).second /* lines */);
892 
893   ASSERT_EQ(NO_ERROR, audioAnalytics.submit(item, true /* isTrusted */));
894   // untrusted entities can add to an existing key
895   ASSERT_EQ(NO_ERROR, audioAnalytics.submit(item2, false /* isTrusted */));
896 
897   // Check that we have some info in the dump.
898   ASSERT_LT(9, audioAnalytics.dump(1000).second /* lines */);
899 }
900 
TEST(mediametrics_tests,audio_analytics_dump)901 TEST(mediametrics_tests, audio_analytics_dump) {
902   auto item = std::make_shared<mediametrics::Item>("audio.1");
903   (*item).set("one", (int32_t)1)
904          .set("two", (int32_t)2)
905          .setTimestamp(10);
906 
907   auto item2 = std::make_shared<mediametrics::Item>("audio.1");
908   (*item2).set("three", (int32_t)3)
909          .setTimestamp(11);
910 
911   auto item3 = std::make_shared<mediametrics::Item>("audio.2");
912   (*item3).set("four", (int32_t)4)
913           .setTimestamp(12);
914 
915   std::shared_ptr<mediametrics::StatsdLog> statsdLog =
916           std::make_shared<mediametrics::StatsdLog>(10);
917   android::mediametrics::AudioAnalytics audioAnalytics{statsdLog};
918 
919   ASSERT_EQ(NO_ERROR, audioAnalytics.submit(item, true /* isTrusted */));
920   // untrusted entities can add to an existing key
921   ASSERT_EQ(NO_ERROR, audioAnalytics.submit(item2, false /* isTrusted */));
922   ASSERT_EQ(NO_ERROR, audioAnalytics.submit(item3, true /* isTrusted */));
923 
924   // find out how many lines we have.
925   auto [string, lines] = audioAnalytics.dump(1000);
926   ASSERT_EQ(lines, (int32_t) countNewlines(string.c_str()));
927 
928   printf("AudioAnalytics: %s", string.c_str());
929   // ensure that dump operates over those lines.
930   for (int32_t ll = 0; ll < lines; ++ll) {
931       auto [s, l] = audioAnalytics.dump(ll);
932       ASSERT_EQ(ll, l);
933       ASSERT_EQ(ll, (int32_t) countNewlines(s.c_str()));
934   }
935 }
936 
TEST(mediametrics_tests,device_parsing)937 TEST(mediametrics_tests, device_parsing) {
938     auto devaddr = android::mediametrics::stringutils::getDeviceAddressPairs("(DEVICE, )");
939     ASSERT_EQ((size_t)1, devaddr.size());
940     ASSERT_EQ("DEVICE", devaddr[0].first);
941     ASSERT_EQ("", devaddr[0].second);
942 
943     devaddr = android::mediametrics::stringutils::getDeviceAddressPairs(
944             "(DEVICE1, A)|(D, ADDRB)");
945     ASSERT_EQ((size_t)2, devaddr.size());
946     ASSERT_EQ("DEVICE1", devaddr[0].first);
947     ASSERT_EQ("A", devaddr[0].second);
948     ASSERT_EQ("D", devaddr[1].first);
949     ASSERT_EQ("ADDRB", devaddr[1].second);
950 
951     devaddr = android::mediametrics::stringutils::getDeviceAddressPairs(
952             "(A,B)|(C,D)");
953     ASSERT_EQ((size_t)2, devaddr.size());
954     ASSERT_EQ("A", devaddr[0].first);
955     ASSERT_EQ("B", devaddr[0].second);
956     ASSERT_EQ("C", devaddr[1].first);
957     ASSERT_EQ("D", devaddr[1].second);
958 
959     devaddr = android::mediametrics::stringutils::getDeviceAddressPairs(
960             "  ( A1 , B )  | ( C , D2 )  ");
961     ASSERT_EQ((size_t)2, devaddr.size());
962     ASSERT_EQ("A1", devaddr[0].first);
963     ASSERT_EQ("B", devaddr[0].second);
964     ASSERT_EQ("C", devaddr[1].first);
965     ASSERT_EQ("D2", devaddr[1].second);
966 }
967 
TEST(mediametrics_tests,timed_action)968 TEST(mediametrics_tests, timed_action) {
969     android::mediametrics::TimedAction timedAction;
970     std::atomic_int value1 = 0;
971 
972     timedAction.postIn(std::chrono::seconds(0), [&value1] { ++value1; });
973     timedAction.postIn(std::chrono::seconds(1000), [&value1] { ++value1; });
974     usleep(100000);
975     ASSERT_EQ(1, value1);
976     ASSERT_EQ((size_t)1, timedAction.size());
977 }
978 
979 // Ensure we don't introduce unexpected duplicates into our maps.
TEST(mediametrics_tests,audio_types_tables)980 TEST(mediametrics_tests, audio_types_tables) {
981     using namespace android::mediametrics::types;
982 
983     ASSERT_EQ(0, countDuplicates(getAudioCallerNameMap()));
984     ASSERT_EQ(2, countDuplicates(getAudioDeviceInMap()));  // has dups
985     ASSERT_EQ(1, countDuplicates(getAudioDeviceOutMap())); // has dups
986     ASSERT_EQ(0, countDuplicates(getAudioThreadTypeMap()));
987     ASSERT_EQ(0, countDuplicates(getAudioTrackTraitsMap()));
988 }
989 
990 // Check our string validation (before logging to statsd).
991 // This variant checks the logged, possibly shortened string.
TEST(mediametrics_tests,audio_types_string)992 TEST(mediametrics_tests, audio_types_string) {
993     using namespace android::mediametrics::types;
994 
995     ASSERT_EQ("java", (lookup<CALLER_NAME, std::string>)("java"));
996     ASSERT_EQ("", (lookup<CALLER_NAME, std::string>)("random"));
997 
998     ASSERT_EQ("SPEECH", (lookup<CONTENT_TYPE, std::string>)("AUDIO_CONTENT_TYPE_SPEECH"));
999     ASSERT_EQ("", (lookup<CONTENT_TYPE, std::string>)("random"));
1000 
1001     ASSERT_EQ("FLAC", (lookup<ENCODING, std::string>)("AUDIO_FORMAT_FLAC"));
1002     ASSERT_EQ("", (lookup<ENCODING, std::string>)("random"));
1003 
1004     ASSERT_EQ("USB_DEVICE", (lookup<INPUT_DEVICE, std::string>)("AUDIO_DEVICE_IN_USB_DEVICE"));
1005     ASSERT_EQ("BUILTIN_MIC|WIRED_HEADSET", (lookup<INPUT_DEVICE, std::string>)(
1006             "AUDIO_DEVICE_IN_BUILTIN_MIC|AUDIO_DEVICE_IN_WIRED_HEADSET"));
1007     ASSERT_EQ("", (lookup<INPUT_DEVICE, std::string>)("random"));
1008 
1009     ASSERT_EQ("RAW", (lookup<INPUT_FLAG, std::string>)("AUDIO_INPUT_FLAG_RAW"));
1010     ASSERT_EQ("HW_AV_SYNC|VOIP_TX", (lookup<INPUT_FLAG, std::string>)(
1011             "AUDIO_INPUT_FLAG_HW_AV_SYNC|AUDIO_INPUT_FLAG_VOIP_TX"));
1012     ASSERT_EQ("", (lookup<INPUT_FLAG, std::string>)("random"));
1013 
1014     ASSERT_EQ("BLUETOOTH_SCO_CARKIT",
1015             (lookup<OUTPUT_DEVICE, std::string>)("AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT"));
1016     ASSERT_EQ("SPEAKER|HDMI", (lookup<OUTPUT_DEVICE, std::string>)(
1017             "AUDIO_DEVICE_OUT_SPEAKER|AUDIO_DEVICE_OUT_HDMI"));
1018     ASSERT_EQ("", (lookup<OUTPUT_DEVICE, std::string>)("random"));
1019 
1020     ASSERT_EQ("PRIMARY", (lookup<OUTPUT_FLAG, std::string>)("AUDIO_OUTPUT_FLAG_PRIMARY"));
1021     ASSERT_EQ("DEEP_BUFFER|NON_BLOCKING", (lookup<OUTPUT_FLAG, std::string>)(
1022             "AUDIO_OUTPUT_FLAG_DEEP_BUFFER|AUDIO_OUTPUT_FLAG_NON_BLOCKING"));
1023     ASSERT_EQ("", (lookup<OUTPUT_FLAG, std::string>)("random"));
1024 
1025     ASSERT_EQ("MIC", (lookup<SOURCE_TYPE, std::string>)("AUDIO_SOURCE_MIC"));
1026     ASSERT_EQ("", (lookup<SOURCE_TYPE, std::string>)("random"));
1027 
1028     ASSERT_EQ("TTS", (lookup<STREAM_TYPE, std::string>)("AUDIO_STREAM_TTS"));
1029     ASSERT_EQ("", (lookup<STREAM_TYPE, std::string>)("random"));
1030 
1031     ASSERT_EQ("DIRECT", (lookup<THREAD_TYPE, std::string>)("DIRECT"));
1032     ASSERT_EQ("", (lookup<THREAD_TYPE, std::string>)("random"));
1033 
1034     ASSERT_EQ("static", (lookup<TRACK_TRAITS, std::string>)("static"));
1035     ASSERT_EQ("", (lookup<TRACK_TRAITS, std::string>)("random"));
1036 
1037     ASSERT_EQ("VOICE_COMMUNICATION",
1038             (lookup<USAGE, std::string>)("AUDIO_USAGE_VOICE_COMMUNICATION"));
1039     ASSERT_EQ("", (lookup<USAGE, std::string>)("random"));
1040 }
1041 
1042 // Check our string validation (before logging to statsd).
1043 // This variant checks integral value logging.
TEST(mediametrics_tests,audio_types_integer)1044 TEST(mediametrics_tests, audio_types_integer) {
1045     using namespace android::mediametrics::types;
1046 
1047     ASSERT_EQ(2, (lookup<CALLER_NAME, int32_t>)("java"));
1048     ASSERT_EQ(0, (lookup<CALLER_NAME, int32_t>)("random")); // 0 == unknown
1049 
1050     ASSERT_EQ((int32_t)AUDIO_CONTENT_TYPE_SPEECH,
1051             (lookup<CONTENT_TYPE, int32_t>)("AUDIO_CONTENT_TYPE_SPEECH"));
1052     ASSERT_EQ((int32_t)AUDIO_CONTENT_TYPE_UNKNOWN, (lookup<CONTENT_TYPE, int32_t>)("random"));
1053 
1054     ASSERT_EQ((int32_t)AUDIO_FORMAT_FLAC, (lookup<ENCODING, int32_t>)("AUDIO_FORMAT_FLAC"));
1055     ASSERT_EQ((int32_t)AUDIO_FORMAT_INVALID, (lookup<ENCODING, int32_t>)("random"));
1056 
1057     ASSERT_EQ(getAudioDeviceInMap().at("AUDIO_DEVICE_IN_USB_DEVICE"),
1058             (lookup<INPUT_DEVICE, int64_t>)("AUDIO_DEVICE_IN_USB_DEVICE"));
1059     ASSERT_EQ(getAudioDeviceInMap().at("AUDIO_DEVICE_IN_BUILTIN_MIC")
1060             | getAudioDeviceInMap().at("AUDIO_DEVICE_IN_WIRED_HEADSET"),
1061             (lookup<INPUT_DEVICE, int64_t>)(
1062             "AUDIO_DEVICE_IN_BUILTIN_MIC|AUDIO_DEVICE_IN_WIRED_HEADSET"));
1063     ASSERT_EQ(0, (lookup<INPUT_DEVICE, int64_t>)("random"));
1064 
1065     ASSERT_EQ((int32_t)AUDIO_INPUT_FLAG_RAW,
1066             (lookup<INPUT_FLAG, int32_t>)("AUDIO_INPUT_FLAG_RAW"));
1067     ASSERT_EQ((int32_t)AUDIO_INPUT_FLAG_HW_AV_SYNC
1068             | (int32_t)AUDIO_INPUT_FLAG_VOIP_TX,
1069             (lookup<INPUT_FLAG, int32_t>)(
1070             "AUDIO_INPUT_FLAG_HW_AV_SYNC|AUDIO_INPUT_FLAG_VOIP_TX"));
1071     ASSERT_EQ(0, (lookup<INPUT_FLAG, int32_t>)("random"));
1072 
1073     ASSERT_EQ(getAudioDeviceOutMap().at("AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT"),
1074             (lookup<OUTPUT_DEVICE, int64_t>)("AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT"));
1075     ASSERT_EQ(getAudioDeviceOutMap().at("AUDIO_DEVICE_OUT_SPEAKER")
1076             | getAudioDeviceOutMap().at("AUDIO_DEVICE_OUT_HDMI"),
1077             (lookup<OUTPUT_DEVICE, int64_t>)(
1078             "AUDIO_DEVICE_OUT_SPEAKER|AUDIO_DEVICE_OUT_HDMI"));
1079     ASSERT_EQ(0, (lookup<OUTPUT_DEVICE, int64_t>)("random"));
1080 
1081     ASSERT_EQ((int32_t)AUDIO_OUTPUT_FLAG_PRIMARY,
1082             (lookup<OUTPUT_FLAG, int32_t>)("AUDIO_OUTPUT_FLAG_PRIMARY"));
1083     ASSERT_EQ((int32_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER | (int32_t)AUDIO_OUTPUT_FLAG_NON_BLOCKING,
1084             (lookup<OUTPUT_FLAG, int32_t>)(
1085             "AUDIO_OUTPUT_FLAG_DEEP_BUFFER|AUDIO_OUTPUT_FLAG_NON_BLOCKING"));
1086     ASSERT_EQ(0, (lookup<OUTPUT_FLAG, int32_t>)("random"));
1087 
1088     ASSERT_EQ((int32_t)AUDIO_SOURCE_MIC, (lookup<SOURCE_TYPE, int32_t>)("AUDIO_SOURCE_MIC"));
1089     ASSERT_EQ((int32_t)AUDIO_SOURCE_DEFAULT, (lookup<SOURCE_TYPE, int32_t>)("random"));
1090 
1091     ASSERT_EQ((int32_t)AUDIO_STREAM_TTS, (lookup<STREAM_TYPE, int32_t>)("AUDIO_STREAM_TTS"));
1092     ASSERT_EQ((int32_t)AUDIO_STREAM_DEFAULT, (lookup<STREAM_TYPE, int32_t>)("random"));
1093 
1094     ASSERT_EQ(1, (lookup<THREAD_TYPE, int32_t>)("DIRECT"));
1095     ASSERT_EQ(-1, (lookup<THREAD_TYPE, int32_t>)("random"));
1096 
1097     ASSERT_EQ(getAudioTrackTraitsMap().at("static"), (lookup<TRACK_TRAITS, int32_t>)("static"));
1098     ASSERT_EQ(0, (lookup<TRACK_TRAITS, int32_t>)("random"));
1099 
1100     ASSERT_EQ((int32_t)AUDIO_USAGE_VOICE_COMMUNICATION,
1101             (lookup<USAGE, int32_t>)("AUDIO_USAGE_VOICE_COMMUNICATION"));
1102     ASSERT_EQ((int32_t)AUDIO_USAGE_UNKNOWN, (lookup<USAGE, int32_t>)("random"));
1103 }
1104 
1105 #if 0
1106 // Stress test code for garbage collection, you need to enable AID_SHELL as trusted to run
1107 // in MediaMetricsService.cpp.
1108 //
1109 // TODO: Make a dedicated stress test.
1110 //
1111 TEST(mediametrics_tests, gc_same_key) {
1112   // random keys ignored when empty
1113   for (int i = 0; i < 10000000; ++i) {
1114       std::unique_ptr<mediametrics::Item> test_key(mediametrics::Item::create("audio.zzz.123"));
1115       test_key->set("event#", "hello");
1116       test_key->set("value",  (int)10);
1117       test_key->selfrecord();
1118   }
1119   //mediaMetrics->dump(fileno(stdout), {} /* args */);
1120 }
1121 #endif
1122 
1123 // Base64Url and isLogSessionId string utilities can be tested by static asserts.
1124 static_assert(mediametrics::stringutils::isBase64Url("abc"));
1125 static_assert(mediametrics::stringutils::InverseBase64UrlTable['A'] == 0);
1126 static_assert(mediametrics::stringutils::InverseBase64UrlTable['a'] == 26);
1127 static_assert(mediametrics::stringutils::InverseBase64UrlTable['!'] ==
1128         mediametrics::stringutils::Transpose::INVALID_CHAR);
1129 static_assert(mediametrics::stringutils::InverseBase64UrlTable['@'] ==
1130         mediametrics::stringutils::Transpose::INVALID_CHAR);
1131 static_assert(mediametrics::stringutils::InverseBase64UrlTable['#'] ==
1132         mediametrics::stringutils::Transpose::INVALID_CHAR);
1133 static_assert(!mediametrics::stringutils::isBase64Url("!@#"));
1134 
1135 static_assert(mediametrics::stringutils::isLogSessionId("0123456789abcdef"));
1136 static_assert(!mediametrics::stringutils::isLogSessionId("abc"));
1137 static_assert(!mediametrics::stringutils::isLogSessionId("!@#"));
1138 static_assert(!mediametrics::stringutils::isLogSessionId("0123456789abcde!"));
1139 
TEST(mediametrics_tests,sanitizeLogSessionId)1140 TEST(mediametrics_tests, sanitizeLogSessionId) {
1141    // invalid id returns empty string.
1142    ASSERT_EQ("", mediametrics::stringutils::sanitizeLogSessionId("abc"));
1143 
1144    // valid id passes through.
1145    std::string validId = "fedcba9876543210";
1146    ASSERT_EQ(validId, mediametrics::stringutils::sanitizeLogSessionId(validId));
1147 
1148    // one more char makes the id invalid
1149    ASSERT_EQ("", mediametrics::stringutils::sanitizeLogSessionId(validId + "A"));
1150 
1151    std::string validId2 = "ZYXWVUT123456789";
1152    ASSERT_EQ(validId2, mediametrics::stringutils::sanitizeLogSessionId(validId2));
1153 
1154    // one fewer char makes the id invalid
1155    ASSERT_EQ("", mediametrics::stringutils::sanitizeLogSessionId(validId.c_str() + 1));
1156 
1157    // replacing one character with an invalid character makes an invalid id.
1158    validId2[3] = '!';
1159    ASSERT_EQ("", mediametrics::stringutils::sanitizeLogSessionId(validId2));
1160 }
1161 
TEST(mediametrics_tests,LruSet)1162 TEST(mediametrics_tests, LruSet) {
1163     constexpr size_t LRU_SET_SIZE = 2;
1164     mediametrics::LruSet<std::string> lruSet(LRU_SET_SIZE);
1165 
1166     // test adding a couple strings.
1167     lruSet.add("abc");
1168     ASSERT_EQ(1u, lruSet.size());
1169     ASSERT_TRUE(lruSet.check("abc"));
1170     lruSet.add("def");
1171     ASSERT_EQ(2u, lruSet.size());
1172 
1173     // now adding the third string causes eviction of the oldest.
1174     lruSet.add("ghi");
1175     ASSERT_FALSE(lruSet.check("abc"));
1176     ASSERT_TRUE(lruSet.check("ghi"));
1177     ASSERT_TRUE(lruSet.check("def"));  // "def" is most recent.
1178     ASSERT_EQ(2u, lruSet.size());      // "abc" is correctly discarded.
1179 
1180     // adding another string will evict the oldest.
1181     lruSet.add("foo");
1182     ASSERT_FALSE(lruSet.check("ghi")); // note: "ghi" discarded when "foo" added.
1183     ASSERT_TRUE(lruSet.check("foo"));
1184     ASSERT_TRUE(lruSet.check("def"));
1185 
1186     // manual removing of a string works, too.
1187     ASSERT_TRUE(lruSet.remove("def"));
1188     ASSERT_FALSE(lruSet.check("def")); // we manually removed "def".
1189     ASSERT_TRUE(lruSet.check("foo"));  // "foo" is still there.
1190     ASSERT_EQ(1u, lruSet.size());
1191 
1192     // you can't remove a string that has not been added.
1193     ASSERT_FALSE(lruSet.remove("bar")); // Note: "bar" doesn't exist, so remove returns false.
1194     ASSERT_EQ(1u, lruSet.size());
1195 
1196     lruSet.add("foo");   // adding "foo" (which already exists) doesn't change size.
1197     ASSERT_EQ(1u, lruSet.size());
1198     lruSet.add("bar");   // add "bar"
1199     ASSERT_EQ(2u, lruSet.size());
1200     lruSet.add("glorp"); // add "glorp" evicts "foo".
1201     ASSERT_EQ(2u, lruSet.size());
1202     ASSERT_TRUE(lruSet.check("bar"));
1203     ASSERT_TRUE(lruSet.check("glorp"));
1204     ASSERT_FALSE(lruSet.check("foo"));
1205 }
1206 
TEST(mediametrics_tests,LruSet0)1207 TEST(mediametrics_tests, LruSet0) {
1208     constexpr size_t LRU_SET_SIZE = 0;
1209     mediametrics::LruSet<std::string> lruSet(LRU_SET_SIZE);
1210 
1211     lruSet.add("a");
1212     ASSERT_EQ(0u, lruSet.size());
1213     ASSERT_FALSE(lruSet.check("a"));
1214     ASSERT_FALSE(lruSet.remove("a")); // never added.
1215     ASSERT_EQ(0u, lruSet.size());
1216 }
1217 
1218 // Returns a 16 Base64Url string representing the decimal representation of value
1219 // (with leading 0s) e.g. 0000000000000000, 0000000000000001, 0000000000000002, ...
generateId(size_t value)1220 static std::string generateId(size_t value)
1221 {
1222     char id[16 + 1]; // to be filled with 16 Base64Url chars (and zero termination)
1223     char *sptr = id + 16; // start at the end.
1224     *sptr-- = 0; // zero terminate.
1225     // output the digits from least significant to most significant.
1226     while (value) {
1227         *sptr-- = value % 10;
1228         value /= 10;
1229     }
1230     // add leading 0's
1231     while (sptr > id) {
1232         *sptr-- = '0';
1233     }
1234     return std::string(id);
1235 }
1236 
TEST(mediametrics_tests,ValidateId)1237 TEST(mediametrics_tests, ValidateId) {
1238     constexpr size_t LRU_SET_SIZE = 3;
1239     constexpr size_t IDS = 10;
1240     static_assert(IDS > LRU_SET_SIZE);  // IDS must be greater than LRU_SET_SIZE.
1241     mediametrics::ValidateId validateId(LRU_SET_SIZE);
1242 
1243 
1244     // register IDs as integer strings counting from 0.
1245     for (size_t i = 0; i < IDS; ++i) {
1246         validateId.registerId(generateId(i));
1247     }
1248 
1249     // only the last LRU_SET_SIZE exist.
1250     for (size_t i = 0; i < IDS - LRU_SET_SIZE; ++i) {
1251         ASSERT_EQ("", validateId.validateId(generateId(i)));
1252     }
1253     for (size_t i = IDS - LRU_SET_SIZE; i < IDS; ++i) {
1254         const std::string id = generateId(i);
1255         ASSERT_EQ(id, validateId.validateId(id));
1256     }
1257 }
1258 
TEST(mediametrics_tests,StatusConversion)1259 TEST(mediametrics_tests, StatusConversion) {
1260     constexpr status_t statuses[] = {
1261         NO_ERROR,
1262         BAD_VALUE,
1263         DEAD_OBJECT,
1264         NO_MEMORY,
1265         PERMISSION_DENIED,
1266         INVALID_OPERATION,
1267         WOULD_BLOCK,
1268         UNKNOWN_ERROR,
1269     };
1270 
1271     auto roundTrip = [](status_t status) {
1272         return android::mediametrics::statusStringToStatus(
1273                 android::mediametrics::statusToStatusString(status));
1274     };
1275 
1276     // Primary status error categories.
1277     for (const auto status : statuses) {
1278         ASSERT_EQ(status, roundTrip(status));
1279     }
1280 
1281     // Status errors specially considered.
1282     ASSERT_EQ(DEAD_OBJECT, roundTrip(FAILED_TRANSACTION));
1283 }
1284 
TEST(mediametrics_tests,HeatMap)1285 TEST(mediametrics_tests, HeatMap) {
1286     constexpr size_t SIZE = 2;
1287     android::mediametrics::HeatMap heatMap{SIZE};
1288     constexpr uid_t UID = 0;
1289     constexpr int32_t SUBCODE = 1;
1290 
1291     ASSERT_EQ((size_t)0, heatMap.size());
1292     heatMap.add("someKey", "someSuffix", "someEvent",
1293             AMEDIAMETRICS_PROP_STATUS_VALUE_OK, UID, "message", SUBCODE);
1294     ASSERT_EQ((size_t)1, heatMap.size());
1295     heatMap.add("someKey", "someSuffix", "someEvent",
1296             AMEDIAMETRICS_PROP_STATUS_VALUE_OK, UID, "message", SUBCODE);
1297     heatMap.add("someKey", "someSuffix", "anotherEvent",
1298             AMEDIAMETRICS_PROP_STATUS_VALUE_ARGUMENT, UID, "message", SUBCODE);
1299     ASSERT_EQ((size_t)1, heatMap.size());
1300     heatMap.add("anotherKey", "someSuffix", "someEvent",
1301             AMEDIAMETRICS_PROP_STATUS_VALUE_OK, UID, "message", SUBCODE);
1302     ASSERT_EQ((size_t)2, heatMap.size());
1303     ASSERT_EQ((size_t)0, heatMap.rejected());
1304 
1305     heatMap.add("thirdKey", "someSuffix", "someEvent",
1306             AMEDIAMETRICS_PROP_STATUS_VALUE_OK, UID, "message", SUBCODE);
1307     ASSERT_EQ((size_t)2, heatMap.size());
1308     ASSERT_EQ((size_t)1, heatMap.rejected());
1309 
1310     android::mediametrics::HeatData heatData = heatMap.getData("someKey");
1311     ASSERT_EQ((size_t)2, heatData.size());
1312     auto count = heatData.heatCount();
1313     ASSERT_EQ((size_t)3, count.size()); // pairs in order { total, "anotherEvent", "someEvent" }
1314     // check total value
1315     ASSERT_EQ((size_t)2, count[0].first);  // OK
1316     ASSERT_EQ((size_t)1, count[0].second); // ERROR;
1317     // first key "anotherEvent"
1318     ASSERT_EQ((size_t)0, count[1].first);  // OK
1319     ASSERT_EQ((size_t)1, count[1].second); // ERROR;
1320     // second key "someEvent"
1321     ASSERT_EQ((size_t)2, count[2].first);  // OK
1322     ASSERT_EQ((size_t)0, count[2].second); // ERROR;
1323 
1324     heatMap.clear();
1325     ASSERT_EQ((size_t)0, heatMap.size());
1326 }
1327