|
19 | 19 | import android.app.Activity; |
20 | 20 | import android.security.KeyStore; |
21 | 21 | import android.test.ActivityUnitTestCase; |
| 22 | +import android.test.AssertionFailedError; |
22 | 23 | import android.test.suitebuilder.annotation.MediumTest; |
23 | 24 | import java.nio.charset.Charsets; |
24 | 25 | import java.util.Arrays; |
| 26 | +import java.util.Date; |
25 | 27 | import java.util.HashSet; |
26 | 28 |
|
27 | 29 | /** |
@@ -403,4 +405,52 @@ public void testUngrant_DoubleGrantUngrant_Failure() throws Exception { |
403 | 405 | assertFalse("Should fail to ungrant key to other user second time", |
404 | 406 | mKeyStore.ungrant(TEST_KEYNAME, 0)); |
405 | 407 | } |
| 408 | + |
| 409 | + /** |
| 410 | + * The amount of time to allow before and after expected time for variance |
| 411 | + * in timing tests. |
| 412 | + */ |
| 413 | + private static final long SLOP_TIME_MILLIS = 15000L; |
| 414 | + |
| 415 | + public void testGetmtime_Success() throws Exception { |
| 416 | + assertTrue("Password should work for keystore", |
| 417 | + mKeyStore.password(TEST_PASSWD)); |
| 418 | + |
| 419 | + assertTrue("Should be able to import key when unlocked", |
| 420 | + mKeyStore.importKey(TEST_KEYNAME, PRIVKEY_BYTES)); |
| 421 | + |
| 422 | + long now = System.currentTimeMillis(); |
| 423 | + long actual = mKeyStore.getmtime(TEST_KEYNAME); |
| 424 | + |
| 425 | + long expectedAfter = now - SLOP_TIME_MILLIS; |
| 426 | + long expectedBefore = now + SLOP_TIME_MILLIS; |
| 427 | + |
| 428 | + assertLessThan("Time should be close to current time", expectedBefore, actual); |
| 429 | + assertGreaterThan("Time should be close to current time", expectedAfter, actual); |
| 430 | + } |
| 431 | + |
| 432 | + private static void assertLessThan(String explanation, long expectedBefore, long actual) { |
| 433 | + if (actual >= expectedBefore) { |
| 434 | + throw new AssertionFailedError(explanation + ": actual=" + actual |
| 435 | + + ", expected before: " + expectedBefore); |
| 436 | + } |
| 437 | + } |
| 438 | + |
| 439 | + private static void assertGreaterThan(String explanation, long expectedAfter, long actual) { |
| 440 | + if (actual <= expectedAfter) { |
| 441 | + throw new AssertionFailedError(explanation + ": actual=" + actual |
| 442 | + + ", expected after: " + expectedAfter); |
| 443 | + } |
| 444 | + } |
| 445 | + |
| 446 | + public void testGetmtime_NonExist_Failure() throws Exception { |
| 447 | + assertTrue("Password should work for keystore", |
| 448 | + mKeyStore.password(TEST_PASSWD)); |
| 449 | + |
| 450 | + assertTrue("Should be able to import key when unlocked", |
| 451 | + mKeyStore.importKey(TEST_KEYNAME, PRIVKEY_BYTES)); |
| 452 | + |
| 453 | + assertEquals("-1 should be returned for non-existent key", |
| 454 | + -1L, mKeyStore.getmtime(TEST_KEYNAME2)); |
| 455 | + } |
406 | 456 | } |
0 commit comments