1 /* 2 3 * Copyright (C) 2014 The Android Open Source Project 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package com.android.cts.verifier.sensors.base; 19 20 import android.content.ActivityNotFoundException; 21 import android.content.Context; 22 import android.content.Intent; 23 import android.content.pm.PackageManager; 24 import android.hardware.cts.helpers.ActivityResultMultiplexedLatch; 25 import android.media.MediaPlayer; 26 import android.opengl.GLSurfaceView; 27 import android.os.Bundle; 28 import android.os.SystemClock; 29 import android.os.Vibrator; 30 import android.provider.Settings; 31 import android.text.TextUtils; 32 import android.text.format.DateUtils; 33 import android.util.Log; 34 import android.view.View; 35 import android.widget.Button; 36 import android.widget.LinearLayout; 37 import android.widget.ScrollView; 38 import android.widget.TextView; 39 40 import com.android.cts.verifier.PassFailButtons; 41 import com.android.cts.verifier.R; 42 import com.android.cts.verifier.TestListActivity; 43 import com.android.cts.verifier.TestListAdapter; 44 import com.android.cts.verifier.TestResult; 45 import com.android.cts.verifier.sensors.helpers.SensorFeaturesDeactivator; 46 import com.android.cts.verifier.sensors.reporting.SensorTestDetails; 47 48 import junit.framework.Assert; 49 50 import java.util.ArrayList; 51 import java.util.concurrent.CountDownLatch; 52 import java.util.concurrent.ExecutorService; 53 import java.util.concurrent.Executors; 54 import java.util.concurrent.TimeUnit; 55 56 /** 57 * A base Activity that is used to build different methods to execute tests inside CtsVerifier. i.e. 58 * CTS tests, and semi-automated CtsVerifier tests. 59 * 60 * <p>This class provides access to the following flow: Activity set up Execute tests (implemented 61 * by sub-classes) Activity clean up 62 * 63 * <p>Currently the following class structure is available: - BaseSensorTestActivity : provides the 64 * platform to execute Sensor tests inside | CtsVerifier, and logging support | -- 65 * SensorCtsTestActivity : an activity that can be inherited from to wrap a CTS | sensor test, and 66 * execute it inside CtsVerifier | these tests do not require any operator interaction | -- 67 * SensorCtsVerifierTestActivity : an activity that can be inherited to write sensor tests that 68 * require operator interaction 69 */ 70 public abstract class BaseSensorTestActivity extends PassFailButtons.Activity 71 implements View.OnClickListener, Runnable, ISensorTestStateContainer { 72 /** 73 * @deprecated use subclass instead? 74 */ 75 @Deprecated protected static final String LOG_TAG = "SensorTest"; 76 77 protected final Class mTestClass; 78 79 private final int mLayoutId; 80 private final SensorFeaturesDeactivator mSensorFeaturesDeactivator; 81 82 private final ExecutorService mExecutorService = Executors.newSingleThreadExecutor(); 83 private final SensorTestLogger mTestLogger = new SensorTestLogger(); 84 private final ActivityResultMultiplexedLatch mActivityResultMultiplexedLatch = 85 new ActivityResultMultiplexedLatch(); 86 private final ArrayList<CountDownLatch> mWaitForUserLatches = new ArrayList<CountDownLatch>(); 87 88 private ScrollView mLogScrollView; 89 private LinearLayout mLogLayout; 90 private Button mNextButton; 91 private Button mPassButton; 92 private Button mFailButton; 93 private Button mRetryButton; 94 95 private GLSurfaceView mGLSurfaceView; 96 private boolean mUsingGlSurfaceView; 97 98 // Flag for Retry button appearance. 99 private boolean mShouldRetry = false; 100 private int mRetryCount = 0; 101 102 /** 103 * Constructor to be used by subclasses. 104 * 105 * @param testClass The class that contains the tests. It is dependant on test executor 106 * implemented by subclasses. 107 */ BaseSensorTestActivity(Class testClass)108 protected BaseSensorTestActivity(Class testClass) { 109 this(testClass, R.layout.sensor_test); 110 } 111 112 /** 113 * Constructor to be used by subclasses. It allows to provide a custom layout for the test UI. 114 * 115 * @param testClass The class that contains the tests. It is dependant on test executor 116 * implemented by subclasses. 117 * @param layoutId The Id of the layout to use for the test UI. The layout must contain all the 118 * elements in the base layout {@code R.layout.sensor_test}. 119 */ BaseSensorTestActivity(Class testClass, int layoutId)120 protected BaseSensorTestActivity(Class testClass, int layoutId) { 121 mTestClass = testClass; 122 mLayoutId = layoutId; 123 mSensorFeaturesDeactivator = new SensorFeaturesDeactivator(this); 124 } 125 126 @Override onCreate(Bundle savedInstanceState)127 protected void onCreate(Bundle savedInstanceState) { 128 super.onCreate(savedInstanceState); 129 setContentView(mLayoutId); 130 131 mLogScrollView = (ScrollView) findViewById(R.id.log_scroll_view); 132 mLogLayout = (LinearLayout) findViewById(R.id.log_layout); 133 mNextButton = (Button) findViewById(R.id.next_button); 134 mNextButton.setOnClickListener(this); 135 mPassButton = (Button) findViewById(R.id.pass_button); 136 mFailButton = (Button) findViewById(R.id.fail_button); 137 mGLSurfaceView = (GLSurfaceView) findViewById(R.id.gl_surface_view); 138 mRetryButton = (Button) findViewById(R.id.retry_button); 139 mRetryButton.setOnClickListener(new retryButtonListener()); 140 141 updateNextButton(false /*enabled*/); 142 mExecutorService.execute(this); 143 } 144 145 @Override onDestroy()146 protected void onDestroy() { 147 super.onDestroy(); 148 mExecutorService.shutdownNow(); 149 } 150 151 @Override onPause()152 protected void onPause() { 153 super.onPause(); 154 if (mUsingGlSurfaceView) { 155 mGLSurfaceView.onPause(); 156 } 157 } 158 159 @Override onResume()160 protected void onResume() { 161 super.onResume(); 162 if (mUsingGlSurfaceView) { 163 mGLSurfaceView.onResume(); 164 } 165 } 166 167 @Override onClick(View target)168 public void onClick(View target) { 169 mShouldRetry = false; 170 171 synchronized (mWaitForUserLatches) { 172 for (CountDownLatch latch : mWaitForUserLatches) { 173 latch.countDown(); 174 } 175 mWaitForUserLatches.clear(); 176 } 177 } 178 179 private class retryButtonListener implements View.OnClickListener { 180 181 @Override onClick(View v)182 public void onClick(View v) { 183 mShouldRetry = true; 184 ++mRetryCount; 185 186 synchronized (mWaitForUserLatches) { 187 for (CountDownLatch latch : mWaitForUserLatches) { 188 latch.countDown(); 189 } 190 mWaitForUserLatches.clear(); 191 } 192 } 193 } 194 195 @Override onActivityResult(int requestCode, int resultCode, Intent data)196 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 197 mActivityResultMultiplexedLatch.onActivityResult(requestCode, resultCode); 198 } 199 200 /** 201 * The main execution {@link Thread}. 202 * 203 * <p>This function executes in a background thread, allowing the test run freely behind the 204 * scenes. It provides the following execution hooks: - Activity SetUp/CleanUp (not available in 205 * JUnit) - executeTests: to implement several execution engines 206 */ 207 @Override run()208 public void run() { 209 long startTimeNs = SystemClock.elapsedRealtimeNanos(); 210 String testName = getTestClassName(); 211 212 SensorTestDetails testDetails; 213 try { 214 mSensorFeaturesDeactivator.requestDeactivationOfFeatures(); 215 testDetails = new SensorTestDetails(testName, SensorTestDetails.ResultCode.PASS); 216 } catch (Throwable e) { 217 testDetails = new SensorTestDetails(testName, "DeactivateSensorFeatures", e); 218 } 219 220 SensorTestDetails.ResultCode resultCode = testDetails.getResultCode(); 221 if (resultCode == SensorTestDetails.ResultCode.SKIPPED) { 222 // this is an invalid state at this point of the test setup 223 throw new IllegalStateException("Deactivation of features cannot skip the test."); 224 } 225 if (resultCode == SensorTestDetails.ResultCode.PASS) { 226 testDetails = executeActivityTests(testName); 227 } 228 229 // we consider all remaining states at this point, because we could have been half way 230 // deactivating features 231 try { 232 mSensorFeaturesDeactivator.requestToRestoreFeatures(); 233 } catch (Throwable e) { 234 testDetails = new SensorTestDetails(testName, "RestoreSensorFeatures", e); 235 } 236 237 mTestLogger.logTestDetails(testDetails); 238 mTestLogger.logExecutionTime(startTimeNs); 239 240 // because we cannot enforce test failures in several devices, set the test UI so the 241 // operator can report the result of the test 242 promptUserToSetResult(testDetails); 243 } 244 245 /** 246 * A general set up routine. It executes only once before the first test case. 247 * 248 * <p>NOTE: implementers must be aware of the interrupted status of the worker thread, and let 249 * {@link InterruptedException} propagate. 250 * 251 * @throws Throwable An exception that denotes the failure of set up. No tests will be executed. 252 */ activitySetUp()253 protected void activitySetUp() throws Throwable {} 254 255 /** 256 * A general clean up routine. It executes upon successful execution of {@link #activitySetUp()} 257 * and after all the test cases. 258 * 259 * <p>NOTE: implementers must be aware of the interrupted status of the worker thread, and 260 * handle it in two cases: - let {@link InterruptedException} propagate - if it is invoked with 261 * the interrupted status, prevent from showing any UI 262 * 263 * @throws Throwable An exception that will be logged and ignored, for ease of implementation by 264 * subclasses. 265 */ activityCleanUp()266 protected void activityCleanUp() throws Throwable {} 267 268 /** 269 * Performs the work of executing the tests. Sub-classes implementing different execution 270 * methods implement this method. 271 * 272 * @return A {@link SensorTestDetails} object containing information about the executed tests. 273 */ executeTests()274 protected abstract SensorTestDetails executeTests() throws InterruptedException; 275 276 /** Get mShouldRetry to check if test is required to retry. */ getShouldRetry()277 protected boolean getShouldRetry() { 278 return mShouldRetry; 279 } 280 281 @Override getTestLogger()282 public SensorTestLogger getTestLogger() { 283 return mTestLogger; 284 } 285 286 @Deprecated appendText(int resId)287 protected void appendText(int resId) { 288 mTestLogger.logInstructions(resId); 289 } 290 291 @Deprecated appendText(String text)292 protected void appendText(String text) { 293 TextAppender textAppender = new TextAppender(R.layout.snsr_instruction); 294 textAppender.setText(text); 295 textAppender.append(); 296 } 297 298 @Deprecated clearText()299 protected void clearText() { 300 this.runOnUiThread( 301 new Runnable() { 302 @Override 303 public void run() { 304 mLogLayout.removeAllViews(); 305 } 306 }); 307 } 308 309 /** 310 * Waits for the operator to acknowledge a requested action. 311 * 312 * @param waitMessageResId The action requested to the operator. 313 */ waitForUser(int waitMessageResId)314 protected void waitForUser(int waitMessageResId) throws InterruptedException { 315 CountDownLatch latch = new CountDownLatch(1); 316 synchronized (mWaitForUserLatches) { 317 mWaitForUserLatches.add(latch); 318 } 319 320 mTestLogger.logInstructions(waitMessageResId); 321 setNextButtonText(waitMessageResId); 322 323 updateRetryButton(true); 324 updateNextButton(true); 325 latch.await(); 326 updateRetryButton(false); 327 updateNextButton(false); 328 } 329 330 /** Waits for the operator to acknowledge to begin execution. */ waitForUserToBegin()331 protected void waitForUserToBegin() throws InterruptedException { 332 waitForUser(R.string.snsr_wait_to_begin); 333 } 334 335 /** Waits for the operator to acknowledge to retry execution. */ waitForUserToRetry()336 protected void waitForUserToRetry() throws InterruptedException { 337 mShouldRetry = true; 338 waitForUser(R.string.snsr_wait_to_retry); 339 } 340 341 /** Waits for the operator to acknowledge to finish execution. */ waitForUserToFinish()342 protected void waitForUserToFinish() throws InterruptedException { 343 mShouldRetry = true; 344 waitForUser(R.string.snsr_wait_to_finish); 345 } 346 347 /** {@inheritDoc} */ 348 @Override waitForUserToContinue()349 public void waitForUserToContinue() throws InterruptedException { 350 waitForUser(R.string.snsr_wait_for_user); 351 } 352 353 /** {@inheritDoc} */ 354 @Override executeActivity(String action)355 public int executeActivity(String action) throws InterruptedException { 356 return executeActivity(new Intent(action)); 357 } 358 359 /** {@inheritDoc} */ 360 @Override executeActivity(Intent intent)361 public int executeActivity(Intent intent) throws InterruptedException { 362 ActivityResultMultiplexedLatch.Latch latch = mActivityResultMultiplexedLatch.bindThread(); 363 try { 364 startActivityForResult(intent, latch.getRequestCode()); 365 } catch (ActivityNotFoundException e) { 366 // handle exception gracefully 367 // Among all defined activity results, RESULT_CANCELED offers the semantic closest to 368 // represent absent setting activity. 369 return RESULT_CANCELED; 370 } 371 return latch.await(); 372 } 373 374 /** {@inheritDoc} */ 375 @Override hasSystemFeature(String feature)376 public boolean hasSystemFeature(String feature) { 377 PackageManager pm = getPackageManager(); 378 return pm.hasSystemFeature(feature); 379 } 380 381 /** {@inheritDoc} */ 382 @Override hasActivity(String action)383 public boolean hasActivity(String action) { 384 PackageManager pm = getPackageManager(); 385 return pm.resolveActivity(new Intent(action), PackageManager.MATCH_DEFAULT_ONLY) != null; 386 } 387 388 /** 389 * Initializes and shows the {@link GLSurfaceView} available to tests. NOTE: initialization can 390 * be performed only once, usually inside {@link #activitySetUp()}. 391 */ initializeGlSurfaceView(final GLSurfaceView.Renderer renderer)392 protected void initializeGlSurfaceView(final GLSurfaceView.Renderer renderer) { 393 runOnUiThread( 394 new Runnable() { 395 @Override 396 public void run() { 397 mGLSurfaceView.setVisibility(View.VISIBLE); 398 mGLSurfaceView.setRenderer(renderer); 399 mUsingGlSurfaceView = true; 400 } 401 }); 402 } 403 404 /** Closes and hides the {@link GLSurfaceView}. */ closeGlSurfaceView()405 protected void closeGlSurfaceView() { 406 runOnUiThread( 407 new Runnable() { 408 @Override 409 public void run() { 410 if (!mUsingGlSurfaceView) { 411 return; 412 } 413 mGLSurfaceView.setVisibility(View.GONE); 414 mGLSurfaceView.onPause(); 415 mUsingGlSurfaceView = false; 416 } 417 }); 418 } 419 420 /** Plays a (default) sound as a notification for the operator. */ playSound()421 protected void playSound() throws InterruptedException { 422 MediaPlayer player = MediaPlayer.create(this, Settings.System.DEFAULT_NOTIFICATION_URI); 423 if (player == null) { 424 Log.e(LOG_TAG, "MediaPlayer unavailable."); 425 return; 426 } 427 player.start(); 428 try { 429 Thread.sleep(500); 430 } finally { 431 player.stop(); 432 } 433 } 434 435 /** Makes the device vibrate for the given amount of time. */ vibrate(int timeInMs)436 protected void vibrate(int timeInMs) { 437 Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 438 vibrator.vibrate(timeInMs); 439 } 440 441 /** 442 * Makes the device vibrate following the given pattern. See {@link Vibrator#vibrate(long[], 443 * int)} for more information. 444 */ vibrate(long[] pattern)445 protected void vibrate(long[] pattern) { 446 Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 447 vibrator.vibrate(pattern, -1); 448 } 449 450 // TODO: move to sensor assertions assertTimestampSynchronization( long eventTimestamp, long receivedTimestamp, long deltaThreshold, String sensorName)451 protected String assertTimestampSynchronization( 452 long eventTimestamp, long receivedTimestamp, long deltaThreshold, String sensorName) { 453 long timestampDelta = Math.abs(eventTimestamp - receivedTimestamp); 454 String timestampMessage = 455 getString( 456 R.string.snsr_event_time, 457 receivedTimestamp, 458 eventTimestamp, 459 timestampDelta, 460 deltaThreshold, 461 sensorName); 462 Assert.assertTrue(timestampMessage, timestampDelta < deltaThreshold); 463 return timestampMessage; 464 } 465 getTestClassName()466 protected String getTestClassName() { 467 if (mTestClass == null) { 468 return "<unknown>"; 469 } 470 return mTestClass.getName(); 471 } 472 setLogScrollViewListener(View.OnTouchListener listener)473 protected void setLogScrollViewListener(View.OnTouchListener listener) { 474 mLogScrollView.setOnTouchListener(listener); 475 } 476 setTestResult(SensorTestDetails testDetails)477 private void setTestResult(SensorTestDetails testDetails) { 478 // the name here, must be the Activity's name because it is what CtsVerifier expects 479 String name = 480 TestListAdapter.setTestNameSuffix( 481 TestListActivity.sCurrentDisplayMode, super.getClass().getName()); 482 String summary = mTestLogger.getOverallSummary(); 483 SensorTestDetails.ResultCode resultCode = testDetails.getResultCode(); 484 switch (resultCode) { 485 case SKIPPED: 486 TestResult.setPassedResult(this, name, summary); 487 break; 488 case PASS: 489 case WARNING: 490 TestResult.setPassedResult(this, name, summary); 491 break; 492 case FAIL: 493 TestResult.setFailedResult(this, name, summary); 494 break; 495 case INTERRUPTED: 496 // do not set a result, just return so the test can complete 497 break; 498 default: 499 throw new IllegalStateException("Unknown ResultCode: " + resultCode); 500 } 501 } 502 executeActivityTests(String testName)503 private SensorTestDetails executeActivityTests(String testName) { 504 SensorTestDetails testDetails; 505 try { 506 activitySetUp(); 507 testDetails = new SensorTestDetails(testName, SensorTestDetails.ResultCode.PASS); 508 } catch (Throwable e) { 509 testDetails = new SensorTestDetails(testName, "ActivitySetUp", e); 510 } 511 512 SensorTestDetails.ResultCode resultCode = testDetails.getResultCode(); 513 if (resultCode == SensorTestDetails.ResultCode.PASS) { 514 // TODO: implement execution filters: 515 // - execute all tests and report results officially 516 // - execute single test or failed tests only 517 try { 518 testDetails = executeTests(); 519 } catch (Throwable e) { 520 // we catch and continue because we have to guarantee a proper clean-up sequence 521 testDetails = new SensorTestDetails(testName, "TestExecution", e); 522 } 523 } 524 525 // clean-up executes for all states, even on SKIPPED and INTERRUPTED there might be some 526 // intermediate state that needs to be taken care of 527 try { 528 activityCleanUp(); 529 } catch (Throwable e) { 530 testDetails = new SensorTestDetails(testName, "ActivityCleanUp", e); 531 } 532 533 return testDetails; 534 } 535 promptUserToSetResult(SensorTestDetails testDetails)536 private void promptUserToSetResult(SensorTestDetails testDetails) { 537 SensorTestDetails.ResultCode resultCode = testDetails.getResultCode(); 538 if (resultCode == SensorTestDetails.ResultCode.FAIL) { 539 mTestLogger.logInstructions(R.string.snsr_test_complete_with_errors); 540 enableTestResultButton( 541 mFailButton, 542 R.string.fail_button_text, 543 testDetails.cloneAndChangeResultCode(SensorTestDetails.ResultCode.FAIL)); 544 } else if (resultCode != SensorTestDetails.ResultCode.INTERRUPTED) { 545 mTestLogger.logInstructions(R.string.snsr_test_complete); 546 enableTestResultButton( 547 mPassButton, 548 R.string.pass_button_text, 549 testDetails.cloneAndChangeResultCode(SensorTestDetails.ResultCode.PASS)); 550 } 551 } 552 updateNextButton(final boolean enabled)553 private void updateNextButton(final boolean enabled) { 554 runOnUiThread( 555 new Runnable() { 556 @Override 557 public void run() { 558 mNextButton.setEnabled(enabled); 559 } 560 }); 561 } 562 563 /** 564 * Set the text for next button by instruction message. During retry, next button text is 565 * changed to notify users. 566 * 567 * @param waitMessageResId The action requested to the operator. 568 */ setNextButtonText(int waitMessageResId)569 private void setNextButtonText(int waitMessageResId) { 570 int nextButtonText; 571 if (waitMessageResId == R.string.snsr_wait_to_retry) { 572 nextButtonText = R.string.fail_and_next_button_text; 573 } else if (waitMessageResId == R.string.snsr_wait_to_finish) { 574 nextButtonText = R.string.finish_button_text; 575 } else { 576 nextButtonText = R.string.next_button_text; 577 } 578 579 runOnUiThread( 580 new Runnable() { 581 @Override 582 public void run() { 583 mNextButton.setText(nextButtonText); 584 } 585 }); 586 } 587 588 /** 589 * Update the retry button status. During retry, show retry execution count. If not to retry, 590 * make retry button invisible. 591 * 592 * @param enabled The status of button. 593 */ updateRetryButton(final boolean enabled)594 private void updateRetryButton(final boolean enabled) { 595 runOnUiThread( 596 new Runnable() { 597 @Override 598 public void run() { 599 if (mShouldRetry) { 600 String showRetryCount = 601 String.format( 602 "%s (%d)", 603 getResources().getText(R.string.retry_button_text), 604 mRetryCount); 605 mRetryButton.setText(showRetryCount); 606 mRetryButton.setVisibility(View.VISIBLE); 607 mRetryButton.setEnabled(enabled); 608 } else { 609 mRetryButton.setVisibility(View.GONE); 610 mRetryCount = 0; 611 } 612 } 613 }); 614 } 615 enableTestResultButton( final Button button, final int textResId, final SensorTestDetails testDetails)616 private void enableTestResultButton( 617 final Button button, final int textResId, final SensorTestDetails testDetails) { 618 final View.OnClickListener listener = 619 new View.OnClickListener() { 620 @Override 621 public void onClick(View v) { 622 setTestResult(testDetails); 623 finish(); 624 } 625 }; 626 627 runOnUiThread( 628 new Runnable() { 629 @Override 630 public void run() { 631 mNextButton.setVisibility(View.GONE); 632 mRetryButton.setVisibility(View.GONE); 633 button.setText(textResId); 634 button.setOnClickListener(listener); 635 button.setVisibility(View.VISIBLE); 636 } 637 }); 638 } 639 640 // a logger available until sensor reporting is in place 641 public class SensorTestLogger { 642 private static final String SUMMARY_SEPARATOR = " | "; 643 644 private final StringBuilder mOverallSummaryBuilder = new StringBuilder("\n"); 645 logCustomView(View view)646 public void logCustomView(View view) { 647 new ViewAppender(view).append(); 648 } 649 logTestStart(String testName)650 void logTestStart(String testName) { 651 // TODO: log the sensor information and expected execution time of each test 652 TextAppender textAppender = new TextAppender(R.layout.snsr_test_title); 653 textAppender.setText(testName); 654 textAppender.append(); 655 } 656 657 /** Logs the instructions by the given ID and the params. */ logInstructions(int instructionsResId, Object... params)658 public void logInstructions(int instructionsResId, Object... params) { 659 TextAppender textAppender = new TextAppender(R.layout.snsr_instruction); 660 textAppender.setText(getString(instructionsResId, params)); 661 textAppender.append(); 662 } 663 664 /** Logs the specific message with given params. */ logMessage(int messageResId, Object... params)665 public void logMessage(int messageResId, Object... params) { 666 TextAppender textAppender = new TextAppender(R.layout.snsr_message); 667 textAppender.setText(getString(messageResId, params)); 668 textAppender.append(); 669 } 670 logWaitForSound()671 public void logWaitForSound() { 672 logInstructions(R.string.snsr_test_play_sound); 673 } 674 logTestDetails(SensorTestDetails testDetails)675 public void logTestDetails(SensorTestDetails testDetails) { 676 String name = testDetails.getName(); 677 String summary = testDetails.getSummary(); 678 SensorTestDetails.ResultCode resultCode = testDetails.getResultCode(); 679 switch (resultCode) { 680 case SKIPPED: 681 logTestSkip(name, summary); 682 break; 683 case PASS: 684 case WARNING: 685 mShouldRetry = false; 686 logTestPass(name, summary); 687 break; 688 case FAIL: 689 logTestFail(name, summary); 690 break; 691 case INTERRUPTED: 692 // do nothing, the test was interrupted so do we 693 break; 694 default: 695 throw new IllegalStateException("Unknown ResultCode: " + resultCode); 696 } 697 } 698 logTestPass(String testName, String testSummary)699 void logTestPass(String testName, String testSummary) { 700 testSummary = getValidTestSummary(testSummary, R.string.snsr_test_pass); 701 logTestEnd(R.layout.snsr_success, testSummary); 702 Log.d(LOG_TAG, testSummary); 703 saveResult(testName, SensorTestDetails.ResultCode.PASS, testSummary); 704 } 705 logTestFail(String testName, String testSummary)706 public void logTestFail(String testName, String testSummary) { 707 testSummary = getValidTestSummary(testSummary, R.string.snsr_test_fail); 708 logTestEnd(R.layout.snsr_error, testSummary); 709 Log.e(LOG_TAG, testSummary); 710 saveResult(testName, SensorTestDetails.ResultCode.FAIL, testSummary); 711 } 712 logTestSkip(String testName, String testSummary)713 void logTestSkip(String testName, String testSummary) { 714 testSummary = getValidTestSummary(testSummary, R.string.snsr_test_skipped); 715 logTestEnd(R.layout.snsr_warning, testSummary); 716 Log.i(LOG_TAG, testSummary); 717 saveResult(testName, SensorTestDetails.ResultCode.SKIPPED, testSummary); 718 } 719 getOverallSummary()720 String getOverallSummary() { 721 return mOverallSummaryBuilder.toString(); 722 } 723 logExecutionTime(long startTimeNs)724 void logExecutionTime(long startTimeNs) { 725 if (Thread.currentThread().isInterrupted()) { 726 return; 727 } 728 long executionTimeNs = SystemClock.elapsedRealtimeNanos() - startTimeNs; 729 long executionTimeSec = TimeUnit.NANOSECONDS.toSeconds(executionTimeNs); 730 // TODO: find a way to format times with nanosecond accuracy and longer than 24hrs 731 String formattedElapsedTime = DateUtils.formatElapsedTime(executionTimeSec); 732 logMessage(R.string.snsr_execution_time, formattedElapsedTime); 733 } 734 logTestEnd(int textViewResId, String testSummary)735 private void logTestEnd(int textViewResId, String testSummary) { 736 TextAppender textAppender = new TextAppender(textViewResId); 737 textAppender.setText(testSummary); 738 textAppender.append(); 739 } 740 getValidTestSummary(String testSummary, int defaultSummaryResId)741 private String getValidTestSummary(String testSummary, int defaultSummaryResId) { 742 if (TextUtils.isEmpty(testSummary)) { 743 return getString(defaultSummaryResId); 744 } 745 return testSummary; 746 } 747 saveResult( String testName, SensorTestDetails.ResultCode resultCode, String summary)748 private void saveResult( 749 String testName, SensorTestDetails.ResultCode resultCode, String summary) { 750 mOverallSummaryBuilder.append(testName); 751 mOverallSummaryBuilder.append(SUMMARY_SEPARATOR); 752 mOverallSummaryBuilder.append(resultCode.name()); 753 mOverallSummaryBuilder.append(SUMMARY_SEPARATOR); 754 mOverallSummaryBuilder.append(summary); 755 mOverallSummaryBuilder.append("\n"); 756 } 757 } 758 759 private class ViewAppender { 760 protected final View mView; 761 ViewAppender(View view)762 public ViewAppender(View view) { 763 mView = view; 764 } 765 append()766 public void append() { 767 runOnUiThread( 768 new Runnable() { 769 @Override 770 public void run() { 771 mLogLayout.addView(mView); 772 mLogScrollView.post( 773 new Runnable() { 774 @Override 775 public void run() { 776 mLogScrollView.fullScroll(View.FOCUS_DOWN); 777 } 778 }); 779 } 780 }); 781 } 782 } 783 784 private class TextAppender extends ViewAppender { 785 private final TextView mTextView; 786 TextAppender(int textViewResId)787 public TextAppender(int textViewResId) { 788 super(getLayoutInflater().inflate(textViewResId, null /* viewGroup */)); 789 mTextView = (TextView) mView; 790 } 791 setText(String text)792 public void setText(String text) { 793 mTextView.setText(text); 794 } 795 setText(int textResId)796 public void setText(int textResId) { 797 mTextView.setText(textResId); 798 } 799 } 800 } 801