blob: a1d173bc3295e51b958be0efe125a1513c3ebb1f [file] [log] [blame]
Brian Duddiecd3a43f2016-12-07 16:53:11 -08001/*
2 * Copyright (C) 2017 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 "contexthub_hidl_hal_test"
18
19#include <android-base/logging.h>
20#include <android/hardware/contexthub/1.0/IContexthub.h>
21#include <android/hardware/contexthub/1.0/IContexthubCallback.h>
22#include <android/hardware/contexthub/1.0/types.h>
23#include <android/log.h>
Dan Shie10b1d62019-12-12 10:12:52 -080024#include <gtest/gtest.h>
25#include <hidl/GtestPrinter.h>
26#include <hidl/ServiceManagement.h>
Steven Moreland3eb7df72017-04-06 12:15:23 -070027#include <log/log.h>
Brian Duddiecd3a43f2016-12-07 16:53:11 -080028
29#include <cinttypes>
30#include <future>
31#include <utility>
32
33using ::android::hardware::Return;
34using ::android::hardware::Void;
35using ::android::hardware::hidl_string;
36using ::android::hardware::hidl_vec;
37using ::android::hardware::contexthub::V1_0::AsyncEventType;
38using ::android::hardware::contexthub::V1_0::ContextHub;
39using ::android::hardware::contexthub::V1_0::ContextHubMsg;
40using ::android::hardware::contexthub::V1_0::HubAppInfo;
41using ::android::hardware::contexthub::V1_0::IContexthub;
42using ::android::hardware::contexthub::V1_0::IContexthubCallback;
43using ::android::hardware::contexthub::V1_0::NanoAppBinary;
44using ::android::hardware::contexthub::V1_0::Result;
45using ::android::hardware::contexthub::V1_0::TransactionResult;
46using ::android::sp;
47
Brian Duddiecd3a43f2016-12-07 16:53:11 -080048#define ASSERT_OK(result) ASSERT_EQ(result, Result::OK)
49#define EXPECT_OK(result) EXPECT_EQ(result, Result::OK)
50
51namespace {
52
53// App ID with vendor "GoogT" (Google Testing), app identifier 0x555555. This
54// app ID is reserved and must never appear in the list of loaded apps.
55constexpr uint64_t kNonExistentAppId = 0x476f6f6754555555;
56
57// Helper that does explicit conversion of an enum class to its underlying/base
58// type. Useful for stream output of enum values.
59template<typename EnumType>
60constexpr typename std::underlying_type<EnumType>::type asBaseType(
61 EnumType value) {
62 return static_cast<typename std::underlying_type<EnumType>::type>(value);
63}
64
65// Synchronously queries IContexthub::getHubs() and returns the result
66hidl_vec<ContextHub> getHubsSync(sp<IContexthub> hubApi) {
67 hidl_vec<ContextHub> hubList;
68 std::promise<void> barrier;
69
70 hubApi->getHubs([&hubList, &barrier](const hidl_vec<ContextHub>& hubs) {
71 hubList = hubs;
72 barrier.set_value();
73 });
74 barrier.get_future().wait_for(std::chrono::seconds(1));
75
76 return hubList;
77}
78
79// Gets a list of valid hub IDs in the system
Dan Shie10b1d62019-12-12 10:12:52 -080080std::vector<std::string> getHubIds(const std::string& service_name) {
81 std::vector<std::string> hubIds;
Brian Duddiecd3a43f2016-12-07 16:53:11 -080082
Dan Shie10b1d62019-12-12 10:12:52 -080083 sp<IContexthub> hubApi = IContexthub::getService(service_name);
Brian Duddiecd3a43f2016-12-07 16:53:11 -080084
85 if (hubApi != nullptr) {
Dan Shie10b1d62019-12-12 10:12:52 -080086 for (const ContextHub& hub : getHubsSync(hubApi)) {
87 hubIds.push_back(std::to_string(hub.hubId));
88 }
Brian Duddiecd3a43f2016-12-07 16:53:11 -080089 }
Brian Duddiecd3a43f2016-12-07 16:53:11 -080090
Dan Shie10b1d62019-12-12 10:12:52 -080091 ALOGD("Running tests against all %zu reported hubs for service %s", hubIds.size(),
92 service_name.c_str());
93 return hubIds;
Brian Duddiecd3a43f2016-12-07 16:53:11 -080094}
95
Dan Shie10b1d62019-12-12 10:12:52 -080096// Test fixture parameterized by hub ID, initializes the HAL and makes the context hub API handle
97// available.
98class ContexthubHidlTest : public ::testing::TestWithParam<std::tuple<std::string, std::string>> {
99 public:
100 virtual void SetUp() override {
101 hubApi = IContexthub::getService(std::get<0>(GetParam()));
102 ASSERT_NE(hubApi, nullptr);
Zhuoyao Zhangebae6472018-02-08 20:48:38 -0800103
Dan Shie10b1d62019-12-12 10:12:52 -0800104 // getHubs() must be called at least once for proper initialization of the
105 // HAL implementation
106 getHubsSync(hubApi);
107 }
Zhuoyao Zhangebae6472018-02-08 20:48:38 -0800108
Dan Shie10b1d62019-12-12 10:12:52 -0800109 uint32_t getHubId() { return std::stoi(std::get<1>(GetParam())); }
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800110
Dan Shie10b1d62019-12-12 10:12:52 -0800111 Result registerCallback(sp<IContexthubCallback> cb) {
112 Result result = hubApi->registerCallback(getHubId(), cb);
113 ALOGD("Registered callback, result %" PRIu32, result);
114 return result;
115 }
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800116
Dan Shie10b1d62019-12-12 10:12:52 -0800117 sp<IContexthub> hubApi;
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800118};
119
120// Base callback implementation that just logs all callbacks by default
121class ContexthubCallbackBase : public IContexthubCallback {
122 public:
123 virtual Return<void> handleClientMsg(const ContextHubMsg& /*msg*/) override {
124 ALOGD("Got client message callback");
125 return Void();
126 }
127
128 virtual Return<void> handleTxnResult(
129 uint32_t txnId, TransactionResult result) override {
130 ALOGD("Got transaction result callback for txnId %" PRIu32 " with result %"
131 PRId32, txnId, result);
132 return Void();
133 }
134
135 virtual Return<void> handleHubEvent(AsyncEventType evt) override {
136 ALOGD("Got hub event callback for event type %" PRIu32, evt);
137 return Void();
138 }
139
140 virtual Return<void> handleAppAbort(uint64_t appId, uint32_t abortCode)
141 override {
142 ALOGD("Got app abort notification for appId 0x%" PRIx64 " with abort code "
143 "0x%" PRIx32, appId, abortCode);
144 return Void();
145 }
146
147 virtual Return<void> handleAppsInfo(const hidl_vec<HubAppInfo>& /*appInfo*/)
148 override {
149 ALOGD("Got app info callback");
150 return Void();
151 }
152};
153
154// Wait for a callback to occur (signaled by the given future) up to the
155// provided timeout. If the future is invalid or the callback does not come
156// within the given time, returns false.
157template<class ReturnType>
158bool waitForCallback(
159 std::future<ReturnType> future,
160 ReturnType *result,
161 std::chrono::milliseconds timeout = std::chrono::seconds(5)) {
162 auto expiration = std::chrono::system_clock::now() + timeout;
163
164 EXPECT_NE(result, nullptr);
165 EXPECT_TRUE(future.valid());
166 if (result != nullptr && future.valid()) {
167 std::future_status status = future.wait_until(expiration);
168 EXPECT_NE(status, std::future_status::timeout)
169 << "Timed out waiting for callback";
170
171 if (status == std::future_status::ready) {
172 *result = future.get();
173 return true;
174 }
175 }
176
177 return false;
178}
179
180// Ensures that the metadata reported in getHubs() is sane
Dan Shie10b1d62019-12-12 10:12:52 -0800181TEST_P(ContexthubHidlTest, TestGetHubs) {
182 hidl_vec<ContextHub> hubs = getHubsSync(hubApi);
183 ALOGD("System reports %zu hubs", hubs.size());
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800184
Dan Shie10b1d62019-12-12 10:12:52 -0800185 for (const ContextHub& hub : hubs) {
186 ALOGD("Checking hub ID %" PRIu32, hub.hubId);
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800187
Dan Shie10b1d62019-12-12 10:12:52 -0800188 EXPECT_FALSE(hub.name.empty());
189 EXPECT_FALSE(hub.vendor.empty());
190 EXPECT_FALSE(hub.toolchain.empty());
191 EXPECT_GT(hub.peakMips, 0);
192 EXPECT_GE(hub.stoppedPowerDrawMw, 0);
193 EXPECT_GE(hub.sleepPowerDrawMw, 0);
194 EXPECT_GT(hub.peakPowerDrawMw, 0);
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800195
Dan Shie10b1d62019-12-12 10:12:52 -0800196 // Minimum 128 byte MTU as required by CHRE API v1.0
197 EXPECT_GE(hub.maxSupportedMsgLen, UINT32_C(128));
198 }
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800199}
200
201TEST_P(ContexthubHidlTest, TestRegisterCallback) {
202 ALOGD("TestRegisterCallback called, hubId %" PRIu32, getHubId());
203 ASSERT_OK(registerCallback(new ContexthubCallbackBase()));
204}
205
206TEST_P(ContexthubHidlTest, TestRegisterNullCallback) {
207 ALOGD("TestRegisterNullCallback called, hubId %" PRIu32, getHubId());
208 ASSERT_OK(registerCallback(nullptr));
209}
210
211// Helper callback that puts the async appInfo callback data into a promise
212class QueryAppsCallback : public ContexthubCallbackBase {
213 public:
214 virtual Return<void> handleAppsInfo(const hidl_vec<HubAppInfo>& appInfo)
215 override {
216 ALOGD("Got app info callback with %zu apps", appInfo.size());
217 promise.set_value(appInfo);
218 return Void();
219 }
220
221 std::promise<hidl_vec<HubAppInfo>> promise;
222};
223
224// Calls queryApps() and checks the returned metadata
225TEST_P(ContexthubHidlTest, TestQueryApps) {
226 ALOGD("TestQueryApps called, hubId %u", getHubId());
227 sp<QueryAppsCallback> cb = new QueryAppsCallback();
228 ASSERT_OK(registerCallback(cb));
229
230 Result result = hubApi->queryApps(getHubId());
231 ASSERT_OK(result);
232
233 ALOGD("Waiting for app info callback");
234 hidl_vec<HubAppInfo> appList;
235 ASSERT_TRUE(waitForCallback(cb->promise.get_future(), &appList));
236 for (const HubAppInfo &appInfo : appList) {
237 EXPECT_NE(appInfo.appId, UINT64_C(0));
238 EXPECT_NE(appInfo.appId, kNonExistentAppId);
239 }
240}
241
242// Helper callback that puts the TransactionResult for the expectedTxnId into a
243// promise
244class TxnResultCallback : public ContexthubCallbackBase {
245 public:
246 virtual Return<void> handleTxnResult(
247 uint32_t txnId, TransactionResult result) override {
248 ALOGD("Got transaction result callback for txnId %" PRIu32 " (expecting %"
249 PRIu32 ") with result %" PRId32, txnId, expectedTxnId, result);
250 if (txnId == expectedTxnId) {
251 promise.set_value(result);
252 }
253 return Void();
254 }
255
256 uint32_t expectedTxnId = 0;
257 std::promise<TransactionResult> promise;
258};
259
260// Parameterized fixture that sets the callback to TxnResultCallback
261class ContexthubTxnTest : public ContexthubHidlTest {
262 public:
263 virtual void SetUp() override {
264 ContexthubHidlTest::SetUp();
265 ASSERT_OK(registerCallback(cb));
266 }
267
268 sp<TxnResultCallback> cb = new TxnResultCallback();
269};
270
271
272// Checks cases where the hub implementation is expected to return an error, but
273// that error can be returned either synchronously or in the asynchronous
274// transaction callback. Returns an AssertionResult that can be used in
275// ASSERT/EXPECT_TRUE. Allows checking the sync result against 1 additional
276// allowed error code apart from OK and TRANSACTION_FAILED, which are always
277// allowed.
278::testing::AssertionResult checkFailureSyncOrAsync(
279 Result result, Result allowedSyncResult,
280 std::future<TransactionResult>&& future) {
281 if (result == Result::OK) {
282 // No error reported synchronously - this is OK, but then we should get an
283 // async callback with a failure status
284 TransactionResult asyncResult;
285 if (!waitForCallback(std::forward<std::future<TransactionResult>>(future),
286 &asyncResult)) {
287 return ::testing::AssertionFailure()
288 << "Got successful sync result, then failed to receive async cb";
289 } else if (asyncResult == TransactionResult::SUCCESS) {
290 return ::testing::AssertionFailure()
291 << "Got successful sync result, then unexpected successful async "
292 "result";
293 }
294 } else if (result != allowedSyncResult &&
295 result != Result::TRANSACTION_FAILED) {
296 return ::testing::AssertionFailure() << "Got sync result "
297 << asBaseType(result) << ", expected TRANSACTION_FAILED or "
298 << asBaseType(allowedSyncResult);
299 }
300
301 return ::testing::AssertionSuccess();
302}
303
304TEST_P(ContexthubTxnTest, TestSendMessageToNonExistentNanoApp) {
305 ContextHubMsg msg;
306 msg.appName = kNonExistentAppId;
307 msg.msgType = 1;
308 msg.msg.resize(4);
309 std::fill(msg.msg.begin(), msg.msg.end(), 0);
310
311 ALOGD("Sending message to non-existent nanoapp");
312 Result result = hubApi->sendMessageToHub(getHubId(), msg);
313 if (result != Result::OK &&
314 result != Result::BAD_PARAMS &&
315 result != Result::TRANSACTION_FAILED) {
316 FAIL() << "Got result " << asBaseType(result) << ", expected OK, BAD_PARAMS"
317 << ", or TRANSACTION_FAILED";
318 }
319}
320
321TEST_P(ContexthubTxnTest, TestLoadEmptyNanoApp) {
322 cb->expectedTxnId = 0123;
323 NanoAppBinary emptyApp;
324
325 emptyApp.appId = kNonExistentAppId;
326 emptyApp.appVersion = 1;
327 emptyApp.flags = 0;
328 emptyApp.targetChreApiMajorVersion = 1;
329 emptyApp.targetChreApiMinorVersion = 0;
330
331 ALOGD("Loading empty nanoapp");
332 Result result = hubApi->loadNanoApp(getHubId(), emptyApp, cb->expectedTxnId);
333 EXPECT_TRUE(checkFailureSyncOrAsync(result, Result::BAD_PARAMS,
334 cb->promise.get_future()));
335}
336
337TEST_P(ContexthubTxnTest, TestUnloadNonexistentNanoApp) {
338 cb->expectedTxnId = 1234;
339
340 ALOGD("Unloading nonexistent nanoapp");
341 Result result = hubApi->unloadNanoApp(getHubId(), kNonExistentAppId,
342 cb->expectedTxnId);
343 EXPECT_TRUE(checkFailureSyncOrAsync(result, Result::BAD_PARAMS,
344 cb->promise.get_future()));
345}
346
347TEST_P(ContexthubTxnTest, TestEnableNonexistentNanoApp) {
348 cb->expectedTxnId = 2345;
349
350 ALOGD("Enabling nonexistent nanoapp");
351 Result result = hubApi->enableNanoApp(getHubId(), kNonExistentAppId,
352 cb->expectedTxnId);
353 EXPECT_TRUE(checkFailureSyncOrAsync(result, Result::BAD_PARAMS,
354 cb->promise.get_future()));
355}
356
357TEST_P(ContexthubTxnTest, TestDisableNonexistentNanoApp) {
358 cb->expectedTxnId = 3456;
359
360 ALOGD("Disabling nonexistent nanoapp");
361 Result result = hubApi->disableNanoApp(getHubId(), kNonExistentAppId,
362 cb->expectedTxnId);
363 EXPECT_TRUE(checkFailureSyncOrAsync(result, Result::BAD_PARAMS,
364 cb->promise.get_future()));
365}
366
Dan Shie10b1d62019-12-12 10:12:52 -0800367// Return the test parameters of a vecter of tuples for all IContexthub services and each of its hub
368// id: <service name of IContexthub, hub id of the IContexthub service>
369static std::vector<std::tuple<std::string, std::string>> get_parameters() {
370 std::vector<std::tuple<std::string, std::string>> parameters;
371 std::vector<std::string> service_names =
372 android::hardware::getAllHalInstanceNames(IContexthub::descriptor);
373 for (const std::string& service_name : service_names) {
374 std::vector<std::string> ids = getHubIds(service_name);
375 for (const std::string& id : ids) {
376 parameters.push_back(std::make_tuple(service_name, id));
377 }
378 }
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800379
Dan Shie10b1d62019-12-12 10:12:52 -0800380 return parameters;
Brian Duddiecd3a43f2016-12-07 16:53:11 -0800381}
382
Dan Shie10b1d62019-12-12 10:12:52 -0800383static std::vector<std::tuple<std::string, std::string>> kTestParameters = get_parameters();
384
385INSTANTIATE_TEST_SUITE_P(HubIdSpecificTests, ContexthubHidlTest, testing::ValuesIn(kTestParameters),
386 android::hardware::PrintInstanceTupleNameToString<>);
387
388INSTANTIATE_TEST_SUITE_P(HubIdSpecificTests, ContexthubTxnTest, testing::ValuesIn(kTestParameters),
389 android::hardware::PrintInstanceTupleNameToString<>);
390
391} // anonymous namespace