safescript_test.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2014 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Unit tests for goog.html.SafeScript and its builders.
  16. */
  17. goog.provide('goog.html.safeScriptTest');
  18. goog.require('goog.html.SafeScript');
  19. goog.require('goog.object');
  20. goog.require('goog.string.Const');
  21. goog.require('goog.testing.jsunit');
  22. goog.setTestOnly('goog.html.safeScriptTest');
  23. function testSafeScript() {
  24. var script = 'var string = \'hello\';';
  25. var safeScript =
  26. goog.html.SafeScript.fromConstant(goog.string.Const.from(script));
  27. var extracted = goog.html.SafeScript.unwrap(safeScript);
  28. assertEquals(script, extracted);
  29. assertEquals(script, safeScript.getTypedStringValue());
  30. assertEquals('SafeScript{' + script + '}', String(safeScript));
  31. // Interface marker is present.
  32. assertTrue(safeScript.implementsGoogStringTypedString);
  33. }
  34. /** @suppress {checkTypes} */
  35. function testUnwrap() {
  36. var privateFieldName = 'privateDoNotAccessOrElseSafeScriptWrappedValue_';
  37. var markerFieldName = 'SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_';
  38. var propNames = goog.object.getKeys(
  39. goog.html.SafeScript.fromConstant(goog.string.Const.from('')));
  40. assertContains(privateFieldName, propNames);
  41. assertContains(markerFieldName, propNames);
  42. var evil = {};
  43. evil[privateFieldName] = 'var string = \'evil\';';
  44. evil[markerFieldName] = {};
  45. var exception =
  46. assertThrows(function() { goog.html.SafeScript.unwrap(evil); });
  47. assertContains('expected object of type SafeScript', exception.message);
  48. }
  49. function testFromConstant_allowsEmptyString() {
  50. assertEquals(
  51. goog.html.SafeScript.EMPTY,
  52. goog.html.SafeScript.fromConstant(goog.string.Const.from('')));
  53. }
  54. function testEmpty() {
  55. assertEquals('', goog.html.SafeScript.unwrap(goog.html.SafeScript.EMPTY));
  56. }