summaryrefslogtreecommitdiff
path: root/modules/simpletest/tests/common.test
diff options
context:
space:
mode:
Diffstat (limited to 'modules/simpletest/tests/common.test')
-rw-r--r--modules/simpletest/tests/common.test52
1 files changed, 52 insertions, 0 deletions
diff --git a/modules/simpletest/tests/common.test b/modules/simpletest/tests/common.test
index e74b053d1..aa43a62eb 100644
--- a/modules/simpletest/tests/common.test
+++ b/modules/simpletest/tests/common.test
@@ -1723,3 +1723,55 @@ class DrupalAttributesUnitTest extends DrupalUnitTestCase {
$this->assertIdentical(drupal_attributes(array()), '', t('Empty attributes array.'));
}
}
+
+/**
+ * Tests converting PHP variables to JSON strings and back.
+ */
+class DrupalJSONTest extends DrupalUnitTestCase {
+ public static function getInfo() {
+ return array(
+ 'name' => 'JSON',
+ 'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
+ 'group' => 'System',
+ );
+ }
+
+ /**
+ * Tests converting PHP variables to JSON strings and back.
+ */
+ function testJSON() {
+ // Setup a string with the full ASCII table.
+ // @todo: Add tests for non-ASCII characters and Unicode.
+ $str = '';
+ for ($i=0; $i < 128; $i++) {
+ $str .= chr($i);
+ }
+ // Characters that must be escaped.
+ $html_unsafe = array('<', '>', '&');
+
+ // Verify there aren't character encoding problems with the source string.
+ $this->assertIdentical(strlen($str), 128, t('A string with the full ASCII table has the correct length.'));
+ foreach ($html_unsafe as $char) {
+ $this->assertTrue(strpos($str, $char) > 0, t('A string with the full ASCII table includes @s.', array('@s' => $char)));
+ }
+
+ // Verify that JSON encoding produces a string with all of the characters.
+ $json = drupal_json_encode($str);
+ $this->assertTrue(strlen($json) > strlen($str), t('A JSON encoded string is larger than the source string.'));
+
+ // Verify that encoding/decoding is reversible.
+ $json_decoded = drupal_json_decode($json);
+ $this->assertIdentical($str, $json_decoded, t('Encoding a string to JSON and decoding back results in the original string.'));
+
+ // Verify reversibility for structured data. Also verify that necessary
+ // characters are escaped.
+ $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
+ $json = drupal_json_encode($source);
+ foreach ($html_unsafe as $char) {
+ $this->assertTrue(strpos($json, $char) === FALSE, t('A JSON encoded string does not contain @s.', array('@s' => $char)));
+ }
+ $json_decoded = drupal_json_decode($json);
+ $this->assertNotIdentical($source, $json, t('An array encoded in JSON is not identical to the source.'));
+ $this->assertIdentical($source, $json_decoded, t('Encoding structured data to JSON and decoding back results in the original data.'));
+ }
+}