Skip to content
This repository was archived by the owner on Aug 1, 2024. It is now read-only.

Commit a1f5a02

Browse files
shickscopybara-github
authored andcommitted
Fail fast in goog.crypt.stringToByteArray with unicode input when goog.DEBUG is true
This should prevent the possibility of flaky tests due to the async-throw only sometimes causing test failure, and it should catch possible issues more reliably. RELNOTES: n/a PiperOrigin-RevId: 479574546 Change-Id: I487f0ee249f3cfa07e98085015bdcd0783e1f239
1 parent 5087873 commit a1f5a02

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

closure/goog/crypt/crypt.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ goog.crypt.TEST_ONLY = {};
3535
goog.crypt.TEST_ONLY.throwException = goog.async.throwException;
3636

3737

38+
/** Configurable so that we can test the async-throw behavior. */
39+
goog.crypt.TEST_ONLY.alwaysThrowSynchronously = goog.DEBUG;
40+
41+
3842
/**
3943
* Turns a string into an array of bytes; a "byte" being a JS number in the
4044
* range 0-255. Multi-byte characters will throw.
@@ -63,7 +67,8 @@ goog.crypt.stringToByteArray = function(str, throwSync) {
6367
// NOTE: c <= 0xffff since JavaScript strings are UTF-16.
6468
if (c > 0xff) {
6569
var err = new Error('go/unicode-to-byte-error');
66-
if (throwSync) {
70+
// NOTE: fail faster in debug to catch errors reliably in tests.
71+
if (goog.crypt.TEST_ONLY.alwaysThrowSynchronously || throwSync) {
6772
throw err;
6873
} else if (goog.crypt.ASYNC_THROW_ON_UNICODE_TO_BYTE) {
6974
goog.crypt.TEST_ONLY.throwException(err);

closure/goog/crypt/crypt_test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,18 @@ testSuite({
196196
},
197197

198198
testStringToByteArray() {
199+
assertArrayEquals([], crypt.stringToByteArray(''));
200+
assertArrayEquals([97, 98, 99], crypt.stringToByteArray('abc'));
201+
assertArrayEquals(
202+
[0xa0, 0x12, 0xa1], crypt.stringToByteArray('\xa0\x12\xa1'));
203+
assertThrows(() => crypt.stringToByteArray('\u0102'));
204+
},
205+
206+
testStringToByteArray_asyncThrow() {
199207
const stubs = new PropertyReplacer();
200208
const stubThrowException = recordFunction();
201209
stubs.replace(crypt.TEST_ONLY, 'throwException', stubThrowException);
210+
stubs.replace(crypt.TEST_ONLY, 'alwaysThrowSynchronously', false);
202211
try {
203212
assertArrayEquals([], crypt.stringToByteArray(''));
204213
assertArrayEquals([97, 98, 99], crypt.stringToByteArray('abc'));

0 commit comments

Comments
 (0)