PHP Classes
elePHPant
Icontem

File: 5.3/enctest.php

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of CPK Smithies  >  zbase32  >  5.3/enctest.php  >  Download  
File: 5.3/enctest.php
Role: Unit test script
Content type: text/plain
Description: Functionality test
Class: zbase32
Encode and decode data using zbase32 algorithm
Author: By
Last change:
Date: 3 years ago
Size: 1,777 bytes
 

Contents

Class file image Download
<?php
require 'zbase32.php';

/**
 * Random string generator
 *
 * Used to generate random plaintext strings for testing encoding methods
 * @author CPKS
 * @version 1.0
 * @package testing
 * @license Public domain
 */
class random_string_generator {
 
/**
   * @var string random string data
   */
 
private $data;
 
/**
   * @var int length of random string data
   */
 
private $datalen;
 
 
/**
   * @param int $length length of random string data from which samples will be culled
   * @param int $bits Number of character bits in data, must be 4 <= $bits <= 8
   */
 
public function __construct($length, $bits) {
    if (
$bits < 4)
      throw new
InvalidArgumentException('Minimum bits = 4');
    if (
$bits > 8)
      throw new
InvalidArgumentException('Maximum bits = 8');
   
$bitmax = array(1, 2, 4, 8, 16, 32, 64, 128, 256);
   
$bitmax = $bitmax[$bits] - 1; // get max char code value for string
   
for ($i = 0; $i < $length; ++$i) $d[] = chr(rand(1, $bitmax));
   
$this->data = implode('', $d);
   
$this->datalen = $length;
  }
 
/**
   * @param int $length number of bytes of random string required for a test
   * @return string a random string of the specified length
   */
 
public function __invoke($length) {
    if (
$length > $this->datalen)
      throw new
BadMethodCallException("Requested length exceeds $this->datalen");
   
$maxoffset = $this->datalen - $length;
   
$start = rand(0, $maxoffset);
    return
substr($this->data, $start, $length);
  }
}

$rs = new random_string_generator(40, 7);
$errs = 0;
for (
$i = 20; $i > 2; --$i) {
 
$r = $rs($i);
 
$e = zbase32\encode($r);
  if (
$r !== zbase32\decode($e)) {
    echo
"Encode/decode failed on length $i.\n";
    ++
$errs;
  }
}
if (
$errs)
  echo
"$errs errors.\n";
else echo
"Looks good!\n";