<?php
/**
* SeekQuarry/Yioop --
* Open Source Pure PHP Search Engine, Crawler, and Indexer
*
* Copyright (C) 2009 - 2026 Chris Pollett chris@pollett.org
*
* LICENSE:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* END LICENSE
*
* @author Chris Pollett chris@pollett.org
* @license https://www.gnu.org/licenses/ GPL3
* @link https://www.seekquarry.com/
* @copyright 2009 - 2026
* @filesource
*/
namespace seekquarry\yioop\tests;
use seekquarry\yioop\library\JavascriptUnitTest;
/**
* Used to test the Javascript implementation of the sha1 function.
* @author Akash Patel
*/
class Sha1JavascriptTest extends JavascriptUnitTest
{
/**
* Number of test cases
* @var int
*/
const NUM_TEST_CASES = 5;
/**
* This test case generates random strings and computes their sha1 hash
* in PHP-land. It then sends the strings and their hashes to Javascript
* land to test if the Javascript implementation of Sha1 gets the same
* answer.
*
* @return string html and Javascript that checks each generated string
* in a browser or, from the command line, under node
*/
public function sha1TestCase()
{
$time = time();
$input_value = [];
$case_number = 0;
for ($i = 0; $i < self::NUM_TEST_CASES; $i++) {
$random_string = md5($time . rand(1, 1000));
$sha1 = sha1($random_string);
$input_value[$case_number++] = $sha1;
$input_value[$case_number++] = $random_string;
}
$js_array = json_encode($input_value);
ob_start();
?>
<div id="sha1Test">
</div>
<script src="../scripts/basic.js" ></script>
<script src="../scripts/sha1.js" ></script>
<script src="../scripts/hash_captcha.js" ></script>
<script src="../scripts/javascript_unit_test.js" ></script>
<script>
var input_array = <?= $js_array ?>;
var results = [];
for (let index = 0; index < input_array.length; index += 2) {
let expected = input_array[index];
let source = input_array[index + 1];
results.push({ name: "sha1 of string " + ((index / 2) + 1),
pass: generateSha1(source) === expected });
}
reportUnitTestResults("sha1Test", "sha1TestCase", results);
</script>
<?php
$out_data = ob_get_contents();
ob_end_clean();
return $out_data;
}
}