1/*
2 * Copyright (C) 2016 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
17package com.android.server.telecom.tests;
18
19import android.telecom.Logging.EventManager;
20import android.test.suitebuilder.annotation.SmallTest;
21
22import java.util.List;
23import java.util.concurrent.LinkedBlockingQueue;
24import java.util.stream.Collectors;
25
26/**
27 * Unit tests for android.telecom.Logging.EventManager.
28 */
29
30public class EventManagerTest extends TelecomTestCase {
31
32    private EventManager mTestEventManager;
33    // A reference to the recently added event record, populated from the eventRecordAdded callback
34    private EventManager.EventRecord mAddedEventRecord;
35
36    private static final String TEST_EVENT = "testEvent";
37    private static final String TEST_START_EVENT = "testStartEvent";
38    private static final String TEST_END_EVENT = "testEndEvent";
39    private static final String TEST_TIMED_EVENT = "TimedEvent";
40    private static final int TEST_DELAY_TIME = 100; // ms
41
42    private class TestRecord implements EventManager.Loggable {
43        private String mId;
44        private String mDescription;
45
46        TestRecord(String id, String description) {
47            mId = id;
48            mDescription = description;
49        }
50
51        @Override
52        public String getId() {
53            return mId;
54        }
55
56        @Override
57        public String getDescription() {
58            return mDescription;
59        }
60    }
61
62    @Override
63    public void setUp() throws Exception {
64        super.setUp();
65        mTestEventManager = new EventManager(() -> "");
66        mTestEventManager.registerEventListener((e) -> mAddedEventRecord = e);
67    }
68
69    @Override
70    public void tearDown() throws Exception {
71        mTestEventManager = null;
72        mAddedEventRecord = null;
73        super.tearDown();
74    }
75
76    /**
77     * Tests EventManager#addEventRecord to make sure that new events are added properly and that
78     * the eventRecordAdded callback is working.
79     */
80    @SmallTest
81    public void testAddEventRecord() throws Exception {
82        TestRecord testRecord = new TestRecord("testId", "testDescription");
83        mTestEventManager.event(testRecord, TEST_EVENT, null);
84
85        assertNotNull(mAddedEventRecord);
86        assertEquals(testRecord, mAddedEventRecord.getRecordEntry());
87        assertTrue(mTestEventManager.getEventRecords().contains(mAddedEventRecord));
88        assertTrue(mTestEventManager.getCallEventRecordMap().containsKey(
89                mAddedEventRecord.getRecordEntry()));
90    }
91
92    /**
93     * Tests EventManager#addEventRecord for the case when we overflow the cached record entries and
94     * the oldest entry is dropped.
95     */
96    @SmallTest
97    public void testAddEventRecordOverflowMaxEvents() throws Exception {
98        TestRecord oldestRecordEntry = new TestRecord("id0", "desc0");
99        // Add the oldest record separately so that we can verify it is dropped later
100        mTestEventManager.event(oldestRecordEntry, TEST_EVENT, null);
101        // Record the EventRecord created by the oldest event
102        assertNotNull(mAddedEventRecord);
103        EventManager.EventRecord oldestRecord = mAddedEventRecord;
104        for (int i = 1; i < EventManager.DEFAULT_EVENTS_TO_CACHE; i++) {
105            mTestEventManager.event(new TestRecord("id" + i, "desc" + i), TEST_EVENT, null);
106        }
107
108        // Add a new event that overflows the cache
109        TestRecord overflowRecord = new TestRecord("newestId", "newestDesc");
110        // Add the oldest record separately so that we can verify it is dropped later
111        mTestEventManager.event(overflowRecord, TEST_EVENT, null);
112
113        assertFalse(mTestEventManager.getEventRecords().contains(oldestRecord));
114        assertTrue(mTestEventManager.getEventRecords().contains(mAddedEventRecord));
115    }
116
117    /**
118     * Tests the restructuring of the record entry queue when it is changed (usually in debugging).
119     * If the queue is resized to be smaller, the oldest records are dropped.
120     */
121    @SmallTest
122    public void testChangeQueueSize() throws Exception {
123        TestRecord oldestRecordEntry = new TestRecord("id0", "desc0");
124        // Add the oldest record separately so that we can verify it is dropped later
125        mTestEventManager.event(oldestRecordEntry, TEST_EVENT, null);
126        // Record the EventRecord created by the oldest event
127        assertNotNull(mAddedEventRecord);
128        EventManager.EventRecord oldestRecord = mAddedEventRecord;
129        for (int i = 1; i < EventManager.DEFAULT_EVENTS_TO_CACHE; i++) {
130            mTestEventManager.event(new TestRecord("id" + i, "desc" + i), TEST_EVENT, null);
131        }
132
133        mTestEventManager.changeEventCacheSize(EventManager.DEFAULT_EVENTS_TO_CACHE - 1);
134
135        assertFalse(mTestEventManager.getEventRecords().contains(oldestRecord));
136        // Check to make sure the other event records are there (id1-9)
137        LinkedBlockingQueue<EventManager.EventRecord> eventRecords =
138                mTestEventManager.getEventRecords();
139        for (int i = 1; i < EventManager.DEFAULT_EVENTS_TO_CACHE; i++) {
140            final int index = i;
141            List<EventManager.EventRecord> filteredEvent = eventRecords.stream()
142                    .filter(e -> e.getRecordEntry().getId().equals("id" + index))
143                    .collect(Collectors.toList());
144            assertEquals(1, filteredEvent.size());
145            assertEquals("desc" + index, filteredEvent.get(0).getRecordEntry().getDescription());
146        }
147    }
148
149    /**
150     * Tests adding TimedEventPairs and generating the paired events as well as verifies that the
151     * timing response is correct.
152     */
153    @SmallTest
154    public void testExtractEventTimings() throws Exception {
155        TestRecord testRecord = new TestRecord("testId", "testDesc");
156        // Add unassociated event
157        mTestEventManager.event(testRecord, TEST_EVENT, null);
158        mTestEventManager.addRequestResponsePair(new EventManager.TimedEventPair(TEST_START_EVENT,
159                TEST_END_EVENT, TEST_TIMED_EVENT));
160
161        // Add Start/End Event
162        mTestEventManager.event(testRecord, TEST_START_EVENT, null);
163        try {
164            Thread.sleep(TEST_DELAY_TIME);
165        } catch (InterruptedException ignored) { }
166        mTestEventManager.event(testRecord, TEST_END_EVENT, null);
167
168        // Verify that the events were captured and that the timing is correct.
169        List<EventManager.EventRecord.EventTiming> timings =
170                mAddedEventRecord.extractEventTimings();
171        assertEquals(1, timings.size());
172        assertEquals(TEST_TIMED_EVENT, timings.get(0).name);
173        // Verify that the timing is correct with a +-10 ms buffer
174        assertTrue(timings.get(0).time >= TEST_DELAY_TIME - 10);
175        assertTrue(timings.get(0).time <= TEST_DELAY_TIME + 10);
176    }
177
178    /**
179     * Verify that adding events to different records does not create a valid TimedEventPair
180     */
181    @SmallTest
182    public void testExtractEventTimingsDifferentRecords() throws Exception {
183        TestRecord testRecord = new TestRecord("testId", "testDesc");
184        TestRecord testRecord2 = new TestRecord("testId2", "testDesc2");
185        mTestEventManager.addRequestResponsePair(new EventManager.TimedEventPair(TEST_START_EVENT,
186                TEST_END_EVENT, TEST_TIMED_EVENT));
187
188        // Add Start event for two separate records
189        mTestEventManager.event(testRecord, TEST_START_EVENT, null);
190        EventManager.EventRecord eventRecord1 = mAddedEventRecord;
191        mTestEventManager.event(testRecord2, TEST_END_EVENT, null);
192        EventManager.EventRecord eventRecord2 = mAddedEventRecord;
193
194        // Verify that the events were captured and that the timing is correct.
195        List<EventManager.EventRecord.EventTiming> timings1 =
196                eventRecord1.extractEventTimings();
197        List<EventManager.EventRecord.EventTiming> timings2 =
198                eventRecord2.extractEventTimings();
199        assertEquals(0, timings1.size());
200        assertEquals(0, timings2.size());
201    }
202}