tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

test_levenshtein.js (2285B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 // This file tests the Levenshtein Distance function we've registered.
      6 
      7 function createUtf16Database() {
      8  print("Creating the in-memory UTF-16-encoded database.");
      9  let conn = Services.storage.openSpecialDatabase("memory");
     10  conn.executeSimpleSQL("PRAGMA encoding = 'UTF-16'");
     11 
     12  print("Make sure the encoding was set correctly and is now UTF-16.");
     13  let stmt = conn.createStatement("PRAGMA encoding");
     14  Assert.ok(stmt.executeStep());
     15  let enc = stmt.getString(0);
     16  stmt.finalize();
     17 
     18  // The value returned will actually be UTF-16le or UTF-16be.
     19  Assert.ok(enc === "UTF-16le" || enc === "UTF-16be");
     20 
     21  return conn;
     22 }
     23 
     24 function check_levenshtein(db, s, t, expectedDistance) {
     25  var stmt = db.createStatement("SELECT levenshteinDistance(:s, :t) AS result");
     26  stmt.params.s = s;
     27  stmt.params.t = t;
     28  try {
     29    Assert.ok(stmt.executeStep());
     30    Assert.equal(expectedDistance, stmt.row.result);
     31  } finally {
     32    stmt.reset();
     33    stmt.finalize();
     34  }
     35 }
     36 
     37 function testLevenshtein(db) {
     38  // Basic tests.
     39  check_levenshtein(db, "", "", 0);
     40  check_levenshtein(db, "foo", "", 3);
     41  check_levenshtein(db, "", "bar", 3);
     42  check_levenshtein(db, "yellow", "hello", 2);
     43  check_levenshtein(db, "gumbo", "gambol", 2);
     44  check_levenshtein(db, "kitten", "sitten", 1);
     45  check_levenshtein(db, "sitten", "sittin", 1);
     46  check_levenshtein(db, "sittin", "sitting", 1);
     47  check_levenshtein(db, "kitten", "sitting", 3);
     48  check_levenshtein(db, "Saturday", "Sunday", 3);
     49  check_levenshtein(db, "YHCQPGK", "LAHYQQKPGKA", 6);
     50 
     51  // Test SQL NULL handling.
     52  check_levenshtein(db, "foo", null, null);
     53  check_levenshtein(db, null, "bar", null);
     54  check_levenshtein(db, null, null, null);
     55 
     56  // The levenshteinDistance function allocates temporary memory on the stack
     57  // if it can.  Test some strings long enough to force a heap allocation.
     58  var dots1000 = Array(1001).join(".");
     59  var dashes1000 = Array(1001).join("-");
     60  check_levenshtein(db, dots1000, dashes1000, 1000);
     61 }
     62 
     63 function run_test() {
     64  testLevenshtein(getOpenedDatabase());
     65  testLevenshtein(createUtf16Database());
     66 }