code:
<?php

/**
 * Tests for the Nonce implementation.
 *
 * PHP versions 4 and 5
 *
 * LICENSE: See the COPYING file included in this distribution.
 *
 * @package OpenID
 * @author JanRain, Inc. <openid@janrain.com>
 * @copyright 2006 Janrain, Inc.
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
 */

require_once 'Auth/OpenID/Nonce.php';

define('Tests_Auth_OpenID_nonce_re',
       '/\A\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ/');

class Tests_Auth_OpenID_Nonce extends PHPUnit_Framework_TestSuite {
    function Tests_Auth_OpenID_Nonce()
    {
        $this->addTestSuite('Tests_Auth_OpenID_NonceTests');
        $this->makeSplitTests();
        $this->makeCheckTimestampTests();
        $this->setName('Tests_Auth_OpenID_Nonce');
    }

    function makeSplitTests()
    {
        $cases = array(
                       '',
                       '1970-01-01T00:00:00+1:00',
                       '1969-01-01T00:00:00Z',
                       '1970-00-01T00:00:00Z',
                       '1970.01-01T00:00:00Z',
                       'Thu Sep  7 13:29:31 PDT 2006',
                       'monkeys',
                       );

        foreach ($cases as $nonce_str) {
            $this->_mkSplitTest($nonce_str);
        }
    }

    function _mkSplitTest($nonce_str)
    {
        $test = new Tests_Auth_OpenID_Nonce_BadSplitCase($nonce_str);
        $test->setName('BadNonceSplit ' . var_export($nonce_str, true));
        $this->addTest($test);
    }

    function makeCheckTimestampTests()
    {
        $cases = array(
                       // exact, no allowed skew
                       array('1970-01-01T00:00:00Z', 0, 0, true),

                       // exact, large skew
                       array('1970-01-01T00:00:00Z', 1000, 0, true),

                       // no allowed skew, one second old
                       array('1970-01-01T00:00:00Z', 0, 1, false),

                       // many seconds old, outside of skew
                       array('1970-01-01T00:00:00Z', 10, 50, false),

                       // one second old, one second skew allowed
                       array('1970-01-01T00:00:00Z', 1, 1, true),

                       // One second in the future, one second skew allowed
                       array('1970-01-01T00:00:02Z', 1, 1, true),

                       // two seconds in the future, one second skew allowed
                       array('1970-01-01T00:00:02Z', 1, 0, false),

                       // malformed nonce string
                       array('monkeys', 0, 0, false)
                       );

        foreach ($cases as $case) {
            $this->_mkCheckTest($case);
        }
    }

    function _mkCheckTest($case)
    {
        list($nonce_str, $skew, $now, $expected) = $case;
        $test = new Tests_Auth_OpenID_Nonce_TimestampCase(
            $nonce_str, $skew, $now, $expected);
        $test->setName('CheckTimestamp ' . var_export($nonce_str, true));
        $this->addTest($test);
    }
}

class Tests_Auth_OpenID_Nonce_TimestampCase extends PHPUnit_Framework_TestCase {
    function Tests_Auth_OpenID_Nonce_TimestampCase(
        $nonce_str, $skew, $now, $expected)
    {
        $this->nonce_string = $nonce_str;
        $this->allowed_skew = $skew;
        $this->now = $now;
        $this->expected = $expected;
    }

    function runTest()
    {
        $actual = Auth_OpenID_checkTimestamp($this->nonce_string,
                                             $this->allowed_skew,
                                             $this->now);
        $this->assertEquals($this->expected, $actual);
    }
}

class Tests_Auth_OpenID_NonceTests extends PHPUnit_Framework_TestCase {
    function test_mkNonce()
    {
        $nonce_str = Auth_OpenID_mkNonce();
        $this->assertTrue(preg_match(Tests_Auth_OpenID_nonce_re, $nonce_str));
    }

    function test_mkNonce_when()
    {
        $nonce_str = Auth_OpenID_mkNonce(0);
        $this->assertTrue(preg_match(Tests_Auth_OpenID_nonce_re, $nonce_str));
        $tpart = substr($nonce_str, 0, 20);
        $this->assertEquals('1970-01-01T00:00:00Z', $tpart);
    }

    function test_splitNonce()
    {
        $s = '1970-01-01T00:00:00Z';
        $expected_t = 0;
        $expected_salt = '';
        list($actual_t, $actual_salt) = Auth_OpenID_splitNonce($s);
        $this->assertEquals($expected_t, $actual_t);
        $this->assertEquals($expected_salt, $actual_salt);
    }

    function test_mkSplit()
    {
        $t = 42;;
        $nonce_str = Auth_OpenID_mkNonce($t);
        $this->assertTrue(preg_match(Tests_Auth_OpenID_nonce_re, $nonce_str));
        list($et, $salt) = Auth_OpenID_splitNonce($nonce_str);
        $this->assertEquals(6, strlen($salt));
        $this->assertEquals($et, $t);
    }
}

class Tests_Auth_OpenID_Nonce_BadSplitCase extends PHPUnit_Framework_TestCase {
    function Tests_Auth_OpenID_Nonce_BadSplitCase($nonce_str)
    {
        $this->nonce_str = $nonce_str;
    }

    function runTest()
    {
        $result = Auth_OpenID_splitNonce($this->nonce_str);
        $this->assertNull($result);
    }
}


code:
<?php

/**
 * Tests for the combination of Yadis discovery and the OpenID
 * protocol.
 */

require_once "Auth/Yadis/XRDS.php";
require_once "Auth/OpenID/Discover.php";

global $__XRDS_BOILERPLATE;
$__XRDS_BOILERPLATE = '<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS xmlns:xrds="xri://$xrds"
           xmlns="xri://$xrd*($v*2.0)"
           xmlns:openid="http://openid.net/xmlns/1.0">
    <XRD>
%s
    </XRD>
</xrds:XRDS>
';

// Different sets of server URLs for use in the URI tag
global $__server_url_options;
$__server_url_options = array(
           array(), // This case should not generate an endpoint object
           array('http://server.url/'),
           array('https://server.url/'),
           array('https://server.url/', 'http://server.url/'),
           array('https://server.url/',
                 'http://server.url/',
                 'http://example.server.url/'),
           );

// A couple of example extension type URIs. These are not at all
// official, but are just here for testing.
global $__ext_types;
$__ext_types = array(
                     'http://janrain.com/extension/blah',
                     'http://openid.net/sreg/1.0');

// All valid combinations of Type tags that should produce an OpenID
// endpoint
global $__openid_types;
$__openid_types = array(
                        Auth_OpenID_TYPE_1_0,
                        Auth_OpenID_TYPE_1_1);

$temp = array();
foreach (__subsets($__ext_types) as $exts) {
    foreach (__subsets($__openid_types) as $ts) {
        if ($ts) {
            $temp[] = array_merge($exts, $ts);
        }
    }
}

global $__type_uri_options;
$__type_uri_options = $temp;

// Range of valid Delegate tag values for generating test data
global $__delegate_options;
$__delegate_options = array(
                            null,
                            'http://vanity.domain/',
                            'https://somewhere/yadis/');

$temp = array();
foreach ($__delegate_options as $delegate) {
    foreach ($__type_uri_options as $type_uris) {
        foreach ($__server_url_options as $uris) {
            $temp[] = array($uris, $type_uris, $delegate);
        }
    }
}

// All combinations of valid URIs, Type URIs and Delegate tags
global $__data;
$__data = $temp;

function _mkXRDS($services_str)
{
    global $__XRDS_BOILERPLATE;
    return sprintf($__XRDS_BOILERPLATE, $services_str);
}

function _mkService($uris = null, $type_uris = null,
                    $delegate = null, $dent = '        ')
{
    $chunks = array($dent, "<Service>\n");
    $dent2 = $dent . '    ';
    if ($type_uris) {
        foreach ($type_uris as $type_uri) {
            $chunks = array_merge($chunks,
                                  array($dent2 . '<Type>',
                                        $type_uri, "</Type>\n"));
        }
    }

    if ($uris) {
        foreach ($uris as $uri) {
            if (is_array($uri)) {
                list($uri, $prio) = $uri;
            } else {
                $prio = null;
            }
            $chunks = array_merge($chunks, array($dent2, '<URI'));
            if ($prio !== null) {
                    $chunks = array_merge($chunks, array(' priority="', strval($prio), '"'));
            }
            $chunks = array_merge($chunks, array('>', $uri, "</URI>\n"));
        }
    }

    if ($delegate) {
        $chunks = array_merge($chunks,
                              array($dent2, '<openid:Delegate>',
                                    $delegate, "</openid:Delegate>\n"));
    }

    $chunks = array_merge($chunks, array($dent, "</Service>\n"));

    return implode("", $chunks);
}

// Used for generating test data
function __subsets($list)
{
    // Generate all non-empty sublists of a list
    $subsets_list = array(array());
    foreach ($list as $elem) {

        $temp = array();
        foreach ($subsets_list as $t) {
            $temp[] = array_merge(array($elem), $t);
        }

        $subsets_list = array_merge($subsets_list, $temp);
    }

    return $subsets_list;
}

class Tests_Auth_OpenID_Tester extends PHPUnit_Framework_TestCase {
    function Tests_Auth_OpenID_Tester($uris, $type_uris, $delegate)
    {
        parent::__construct();
        $this->uris = $uris;
        $this->type_uris = $type_uris;
        $this->local_id = $delegate;
    }

    function setUp()
    {
        $this->yadis_url = 'http://unit.test/';

        // Create an XRDS document to parse
        $services = _mkService($this->uris,
                               $this->type_uris,
                               $this->local_id);
        $this->xrds = _mkXRDS($services);
    }

    function runTest()
    {
        // Parse into endpoint objects that we will check
        $xrds_object = Auth_Yadis_XRDS::parseXRDS($this->xrds);

        $endpoints = array();

        if ($xrds_object) {
            $endpoints = $xrds_object->services(array('filter_MatchesAnyOpenIDType'));
            $endpoints = Auth_OpenID_makeOpenIDEndpoints($this->yadis_url, $endpoints);
        }

        // make sure there are the same number of endpoints as
        // URIs. This assumes that the type_uris contains at least one
        // OpenID type.
        $this->assertEquals(count($this->uris), count($endpoints),
                            "URI <-> Endpoint count");

        // So that we can check equality on the endpoint types
        $type_uris = $this->type_uris;
        sort($type_uris);

        $seen_uris = array();
        foreach ($endpoints as $endpoint) {
            $seen_uris[] = $endpoint->server_url;

            // All endpoints will have same yadis_url
            $this->assertEquals($this->yadis_url, $endpoint->claimed_id);

            // and delegate
            $this->assertEquals($this->local_id, $endpoint->local_id);

            // and types
            $actual_types = $endpoint->type_uris;
            sort($actual_types);
            $this->assertEquals($actual_types, $type_uris);
        }

        // So that they will compare equal, because we don't care what
        // order they are in
        sort($seen_uris);
        $uris = $this->uris;
        sort($uris);

        // Make sure we saw all URIs, and saw each one once
        $this->assertEquals($uris, $seen_uris);
    }
}

class Tests_Auth_OpenID_OpenID_Yadis extends PHPUnit_Framework_TestSuite {
    function Tests_Auth_OpenID_OpenID_Yadis()
    {
        global $__data;
        foreach ($__data as $case) {
            $this->addTest(new Tests_Auth_OpenID_Tester($case[0], $case[1], $case[2]));
        }
    }

    function getName()
    {
        return 'Tests_Auth_OpenID_OpenID_Yadis';
    }

}

repo_name: ksuudilla/gnu

license: mit


code:
<?php

require_once "Auth/OpenID/PAPE.php";
require_once "Auth/OpenID/Message.php";
require_once "Auth/OpenID/Server.php";

class PapeRequestTestCase extends PHPUnit_Framework_TestCase {
    function setUp()
    {
        $this->req = new Auth_OpenID_PAPE_Request();
    }

    function test_construct()
    {
      $this->assertEquals(array(), $this->req->preferred_auth_policies);
      $this->assertEquals(null, $this->req->max_auth_age);
      $this->assertEquals('pape', $this->req->ns_alias);

      $req2 = new Auth_OpenID_PAPE_Request(array(PAPE_AUTH_MULTI_FACTOR), 1000);
      $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR), $req2->preferred_auth_policies);
      $this->assertEquals(1000, $req2->max_auth_age);
    }

    function test_add_policy_uri()
    {
      $this->assertEquals(array(), $this->req->preferred_auth_policies);
      $this->req->addPolicyURI(PAPE_AUTH_MULTI_FACTOR);
      $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR), $this->req->preferred_auth_policies);
      $this->req->addPolicyURI(PAPE_AUTH_MULTI_FACTOR);
      $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR), $this->req->preferred_auth_policies);
      $this->req->addPolicyURI(PAPE_AUTH_PHISHING_RESISTANT);
      $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT),
                          $this->req->preferred_auth_policies);
      $this->req->addPolicyURI(PAPE_AUTH_MULTI_FACTOR);
      $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT),
                          $this->req->preferred_auth_policies);
    }

    function test_getExtensionArgs() {
      $this->assertEquals(array('preferred_auth_policies' => ''), $this->req->getExtensionArgs());
      $this->req->addPolicyURI('http://uri');
      $this->assertEquals(array('preferred_auth_policies' => 'http://uri'), $this->req->getExtensionArgs());
      $this->req->addPolicyURI('http://zig');
      $this->assertEquals(array('preferred_auth_policies' => 'http://uri http://zig'), $this->req->getExtensionArgs());
      $this->req->max_auth_age = 789;
      $this->assertEquals(array('preferred_auth_policies' => 'http://uri http://zig', 'max_auth_age' => '789'), $this->req->getExtensionArgs());
    }

    function test_parseExtensionArgs() {
      $args = array('preferred_auth_policies' => 'http://foo http://bar',
                    'max_auth_age' => '9');
      $this->req->parseExtensionArgs($args);
      $this->assertEquals(9, $this->req->max_auth_age);
      $this->assertEquals(array('http://foo','http://bar'), $this->req->preferred_auth_policies);
    }

    function test_parseExtensionArgs_empty() {
      $this->req->parseExtensionArgs(array());
      $this->assertEquals(null, $this->req->max_auth_age);
      $this->assertEquals(array(), $this->req->preferred_auth_policies);
    }

    function test_fromOpenIDRequest() {
      $openid_req_msg = Auth_OpenID_Message::fromOpenIDArgs(array(
          'mode' => 'checkid_setup',
          'ns' => Auth_OpenID_OPENID2_NS,
          'ns.pape' => Auth_OpenID_PAPE_NS_URI,
          'pape.preferred_auth_policies' => implode(' ', array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT)),
          'pape.max_auth_age' => '5476'
          ));
      $oid_req = new Auth_OpenID_Request();
      $oid_req->message = $openid_req_msg;
      $req = Auth_OpenID_PAPE_Request::fromOpenIDRequest($oid_req);
      $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT), $req->preferred_auth_policies);
      $this->assertEquals(5476, $req->max_auth_age);
    }

    function test_fromOpenIDRequest_no_pape() {
      $message = new Auth_OpenID_Message();
      $openid_req = new Auth_OpenID_Request();
      $openid_req->message = $message;
      $pape_req = Auth_OpenID_PAPE_Request::fromOpenIDRequest($openid_req);
      $this->assertTrue($pape_req === null);
    }

    function test_preferred_types() {
        $this->req->addPolicyURI(PAPE_AUTH_PHISHING_RESISTANT);
        $this->req->addPolicyURI(PAPE_AUTH_MULTI_FACTOR);
        $pt = $this->req->preferredTypes(array(PAPE_AUTH_MULTI_FACTOR,
                                               PAPE_AUTH_MULTI_FACTOR_PHYSICAL));
        $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR), $pt);
    }
}

class PAPE_DummySuccessResponse {
  function PAPE_DummySuccessResponse($message, $signed_stuff)
  {
    $this->message = $message;
    $this->signed_stuff = $signed_stuff;
  }

  function getSignedNS($ns_uri)
  {
    return $this->signed_stuff;
  }
}

class PapeResponseTestCase extends PHPUnit_Framework_TestCase {
  function setUp() {
    $this->req = new Auth_OpenID_PAPE_Response();
  }

  function test_construct() {
    $this->assertEquals(array(), $this->req->auth_policies);
    $this->assertEquals(null, $this->req->auth_time);
    $this->assertEquals('pape', $this->req->ns_alias);
    $this->assertEquals(null, $this->req->nist_auth_level);

    $req2 = new Auth_OpenID_PAPE_Response(array(PAPE_AUTH_MULTI_FACTOR),
                                          '2001-01-01T04:05:23Z',
                                          3);
    $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR), $req2->auth_policies);
    $this->assertEquals('2001-01-01T04:05:23Z', $req2->auth_time);
    $this->assertEquals(3, $req2->nist_auth_level);
  }

  function test_add_policy_uri() {
    $this->assertEquals(array(), $this->req->auth_policies);
    $this->req->addPolicyURI(PAPE_AUTH_MULTI_FACTOR);
    $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR), $this->req->auth_policies);
    $this->req->addPolicyURI(PAPE_AUTH_MULTI_FACTOR);
    $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR), $this->req->auth_policies);
    $this->req->addPolicyURI(PAPE_AUTH_PHISHING_RESISTANT);
    $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT), $this->req->auth_policies);
    $this->req->addPolicyURI(PAPE_AUTH_MULTI_FACTOR);
    $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT), $this->req->auth_policies);
  }

  function test_getExtensionArgs() {
    $this->assertEquals(array('auth_policies' => 'none'), $this->req->getExtensionArgs());
    $this->req->addPolicyURI('http://uri');
    $this->assertEquals(array('auth_policies' => 'http://uri'), $this->req->getExtensionArgs());
    $this->req->addPolicyURI('http://zig');
    $this->assertEquals(array('auth_policies' => 'http://uri http://zig'), $this->req->getExtensionArgs());
    $this->req->auth_time = '2008-03-02T12:34:56Z';
    $this->assertEquals(array('auth_policies' => 'http://uri http://zig', 'auth_time' => '2008-03-02T12:34:56Z'), $this->req->getExtensionArgs());
    $this->req->nist_auth_level = 3;
    $this->assertEquals(array('auth_policies' => 'http://uri http://zig', 'auth_time' => '2008-03-02T12:34:56Z', 'nist_auth_level' => '3'), $this->req->getExtensionArgs());
  }

  function test_getExtensionArgs_error_auth_age() {
    $this->req->auth_time = "foo2008-03-02T12:34:56Z";
    $this->assertEquals(false, $this->req->getExtensionArgs());
    $this->req->auth_time = "2008-03-02T12:34:56Zbar";
    $this->assertEquals(false, $this->req->getExtensionArgs());
  }

  function test_getExtensionArgs_error_nist_auth_level() {
    $this->req->nist_auth_level = "high as a kite";
    $this->assertEquals(false, $this->req->getExtensionArgs());
    $this->req->nist_auth_level = 5;
    $this->assertEquals(false, $this->req->getExtensionArgs());
    $this->req->nist_auth_level = -1;
    $this->assertEquals(false, $this->req->getExtensionArgs());
  }

  function test_parseExtensionArgs() {
    $args = array('auth_policies' => 'http://foo http://bar',
                  'auth_time' => '2008-03-02T12:34:56Z');
    $this->req->parseExtensionArgs($args);
    $this->assertEquals('2008-03-02T12:34:56Z', $this->req->auth_time);
    $this->assertEquals(array('http://foo','http://bar'), $this->req->auth_policies);
  }

  function test_parseExtensionArgs_empty() {
    $this->req->parseExtensionArgs(array());
    $this->assertEquals(null, $this->req->auth_time);
    $this->assertEquals(array(), $this->req->auth_policies);
  }

  function test_parseExtensionArgs_strict_bogus1() {
    $args = array('auth_policies' => 'http://foo http://bar',
                  'auth_time' => 'yesterday');
    $this->assertEquals(false, $this->req->parseExtensionArgs($args, true));
  }

  function test_parseExtensionArgs_strict_bogus2() {
    $args = array('auth_policies' => 'http://foo http://bar',
                  'auth_time' => '63',
                  'nist_auth_level' => 'some');
    $this->assertEquals(false, $this->req->parseExtensionArgs($args, true));
  }

  function test_parseExtensionArgs_strict_good() {
    $args = array('auth_policies' => 'http://foo http://bar',
                  'auth_time' => '2008-03-02T12:34:56Z',
                  'nist_auth_level' => '0');
    $this->req->parseExtensionArgs($args, true);
    $this->assertEquals(array('http://foo','http://bar'), $this->req->auth_policies);
    $this->assertEquals('2008-03-02T12:34:56Z', $this->req->auth_time);
    $this->assertEquals(0, $this->req->nist_auth_level);
  }

  function test_parseExtensionArgs_nostrict_bogus() {
    $args = array('auth_policies' => 'http://foo http://bar',
                  'auth_time' => 'the other day',
                  'nist_auth_level' => 'some');
    $this->req->parseExtensionArgs($args);
    $this->assertEquals(array('http://foo','http://bar'), $this->req->auth_policies);
    $this->assertEquals(null, $this->req->auth_time);
    $this->assertEquals(null, $this->req->nist_auth_level);
  }

  function test_fromSuccessResponse() {
    $openid_req_msg = Auth_OpenID_Message::fromOpenIDArgs(array(
          'mode' => 'id_res',
          'ns' => Auth_OpenID_OPENID2_NS,
          'ns.pape' => Auth_OpenID_PAPE_NS_URI,
          'auth_policies' => implode(' ', array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT)),
          'auth_time' => '2008-03-02T12:34:56Z'
          ));
    $signed_stuff = array(
          'auth_policies' => implode(' ', array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT)),
          'auth_time' => '2008-03-02T12:34:56Z'
        );
    $oid_req = new PAPE_DummySuccessResponse($openid_req_msg, $signed_stuff);
    $req = Auth_OpenID_PAPE_Response::fromSuccessResponse($oid_req);
    $this->assertEquals(array(PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_PHISHING_RESISTANT), $req->auth_policies);
    $this->assertEquals('2008-03-02T12:34:56Z', $req->auth_time);
  }
}

class Tests_Auth_OpenID_PAPE extends PHPUnit_Framework_TestSuite {
  function getName() {
    return "Tests_Auth_OpenID_PAPE";
  }

  function Tests_Auth_OpenID_PAPE() {
    $this->addTestSuite('PapeRequestTestCase');
    $this->addTestSuite('PapeResponseTestCase');
  }
}


code:
<?php

/**
 * Tests for the Consumer parsing functions.
 *
 * PHP versions 4 and 5
 *
 * LICENSE: See the COPYING file included in this distribution.
 *
 * @package OpenID
 * @author JanRain, Inc. <openid@janrain.com>
 * @copyright 2005-2008 Janrain, Inc.
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
 */

require_once 'Tests/Auth/OpenID/TestUtil.php';
require_once 'Auth/OpenID/Parse.php';

class Tests_Auth_OpenID_Link extends PHPUnit_Framework_TestCase {
    function Tests_Auth_OpenID_Link($case)
    {
        list($desc, $markup, $links, $case_text) = $case;
        $this->desc = $desc;
        $this->markup = $markup;
        $this->expected_links = $links;
        $this->case_text = $case_text;
        $this->parser = new Auth_OpenID_Parse();
    }

    function getName()
    {
        return $this->desc;
    }

    function runTest()
    {
        $parsed = $this->parser->parseLinkAttrs($this->markup);
        $i = 0;

        foreach ($this->expected_links as $expected) {
            list($is_optional_link, $expected_link) = $expected;
            if ($is_optional_link &&
                ($i >= count($parsed))) {
                continue;
            }

            if (count($parsed) <= $i) {
                $i++;
                continue;
            }

            $act_link = $parsed[$i];

            $increment = true;
            foreach ($expected_link as $attr => $data) {
                list($is_optional_attr, $value) = $data;

                if ($is_optional_attr) {
                    $actual_value = null;
                    if (array_key_exists($attr, $act_link)) {
                        $actual_value = $act_link[$attr];
                    } else {
                        continue;
                    }
                } else {
                    $actual_value = $act_link[$attr];
                }

                if ($is_optional_link &&
                    ($value != $actual_value)) {
                    $increment = false;
                    break;
                }

                $this->assertEquals($value, $actual_value);
            }

            if ($increment) {
                $i++;
            }
        }

        $this->assertEquals($i, count($parsed));
    }
}

class NumTestCases extends PHPUnit_Framework_TestCase {
    function NumTestCases($test_cases, $num_tests)
    {
        $this->test_cases = $test_cases;
        $this->num_tests = $num_tests;
    }

    function runTest()
    {
        $this->assertEquals(count($this->test_cases),
                            $this->num_tests);
    }
}

class Tests_Auth_OpenID_Parse extends PHPUnit_Framework_TestSuite {

    function getName()
    {
        return "Tests_Auth_OpenID_Parse";
    }

    function _parseCheck($cond, $where)
    {
        if (!$cond) {
            trigger_error('Parse error in ' . $where, E_USER_ERROR);
        }
    }

    function parseLink($line)
    {
        $parts = explode(" ", $line);
        $optional = intval($parts[0] == 'Link*:');
        $this->_parseCheck($optional || ($parts[0] == 'Link:'), __FUNCTION__);

        $attrs = array();
        foreach (array_slice($parts, 1) as $attr) {
            list($k, $v) = explode("=", $attr, 2);
            if ($k[strlen($k) - 1] == '*') {
                $attr_optional = 1;
                $k = substr($k, 0, strlen($k) - 1);
            } else {
                $attr_optional = 0;
            }

            $attrs[$k] = array($attr_optional, $v);
        }

        return array($optional, $attrs);
    }

    function parseCase($s)
    {
        list($header, $markup) = explode("\n\n", $s, 2);
        $lines = explode("\n", $header);
        $name = array_shift($lines);
        $this->_parseCheck(strpos($name, 'Name: ') == 0, __FUNCTION__);
        $desc = substr($name, 6);
        $parsed = array();
        foreach ($lines as $line) {
            $parsed[] = $this->parseLink($line);
        }

        return array($desc, $markup, $parsed);
    }

    function parseTests($s)
    {
        $tests = array();

        $cases = explode("\n\n\n", $s);
        $header = array_shift($cases);
        list($tests_line, $unused) = explode("\n", $header, 2);
        list($k, $v) = explode(": ", $tests_line);
        $this->_parseCheck(('Num Tests' == $k), __FUNCTION__);
        $num_tests = intval($v);

        foreach (array_slice($cases, 0, count($cases) - 1) as $case) {
            list($desc, $markup, $links) = $this->parseCase($case);
            $tests[] = array($desc, $markup, $links, $case);
        }

        return array($num_tests, $tests);
    }

    function Tests_Auth_OpenID_Parse()
    {
        $test_data = Tests_Auth_OpenID_readdata('linkparse.txt');

        list($num_tests, $test_cases) = $this->parseTests($test_data);

        $this->addTest(new NumTestCases($test_cases, $num_tests));

        foreach ($test_cases as $case) {
            $this->addTest(new Tests_Auth_OpenID_Link($case));
        }
    }
}


code:
<?php

/*
 * Unit tests for verification of return_to URLs for a realm.
 */

require_once 'Auth/OpenID/Discover.php';
require_once 'Auth/OpenID/TrustRoot.php';

require_once 'Auth/Yadis/Yadis.php';

/*
 * Tests for building the discovery URL from a realm and a return_to
 * URL
 */
class Tests_Auth_OpenID_BuildDiscoveryURL extends PHPUnit_Framework_TestCase {
    /*
     * Build a discovery URL out of the realm and a return_to and make
     * sure that it matches the expected discovery URL
     */
    function failUnlessDiscoURL($realm, $expected_discovery_url)
    {
        $actual_discovery_url = Auth_OpenID_TrustRoot::buildDiscoveryURL($realm);
        $this->assertEquals($expected_discovery_url, $actual_discovery_url);
    }

    /*
     * There is no wildcard and the realm is the same as the return_to
     * URL
     */
    function test_trivial()
    {
        $this->failUnlessDiscoURL('http://example.com/foo',
                                  'http://example.com/foo');
    }

    /*
     * There is a wildcard
     */
    function test_wildcard()
    {
        $this->failUnlessDiscoURL('http://*.example.com/foo',
                                  'http://www.example.com/foo');
    }
}

class _MockDiscover {
    function _MockDiscover($data) {
        $this->data =& $data;
    }

    function mockDiscover($uri, $fetcher, $discover_function=null)
    {
        $result = new Auth_Yadis_DiscoveryResult($uri);
        $result->response_text = $this->data;
        $result->normalized_uri = $uri;
        return $result;
    }
}

class Tests_Auth_OpenID_ExtractReturnToURLs extends PHPUnit_Framework_TestCase {
    var $disco_url = 'http://example.com/';

    function failUnlessXRDSHasReturnURLs($data, $expected_return_urls)
    {
        $discover_object = new _MockDiscover($data);
        $actual_return_urls = Auth_OpenID_getAllowedReturnURLs($this->disco_url, null, array($discover_object, 'mockDiscover'));

        $this->assertEquals($expected_return_urls, $actual_return_urls);
    }

    function failUnlessDiscoveryFailure($text)
    {
        $discover_object = new _MockDiscover($text);
        $this->assertFalse(Auth_OpenID_getAllowedReturnURLs($this->disco_url, null, array($discover_object, 'mockDiscover')));
    }

    function test_empty()
    {
        $this->failUnlessDiscoveryFailure('');
    }

    function test_badXML()
    {
        $this->failUnlessDiscoveryFailure('>');
    }

    function test_noEntries()
    {
        $this->failUnlessXRDSHasReturnURLs('<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS xmlns:xrds="xri://$xrds"
           xmlns="xri://$xrd*($v*2.0)"
           >
  <XRD>
  </XRD>
</xrds:XRDS>
', array());
    }

    function test_noReturnToEntries()
    {
        $this->failUnlessXRDSHasReturnURLs('<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS xmlns:xrds="xri://$xrds"
           xmlns="xri://$xrd*($v*2.0)"
           >
  <XRD>
    <Service priority="10">
      <Type>http://specs.openid.net/auth/2.0/server</Type>
      <URI>http://www.myopenid.com/server</URI>
    </Service>
  </XRD>
</xrds:XRDS>
', array());
    }

    function test_oneEntry()
    {
        $this->failUnlessXRDSHasReturnURLs('<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS xmlns:xrds="xri://$xrds"
           xmlns="xri://$xrd*($v*2.0)"
           >
  <XRD>
    <Service>
      <Type>http://specs.openid.net/auth/2.0/return_to</Type>
      <URI>http://rp.example.com/return</URI>
    </Service>
  </XRD>
</xrds:XRDS>
', array('http://rp.example.com/return'));
    }

    function test_twoEntries()
    {
        $this->failUnlessXRDSHasReturnURLs('<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS xmlns:xrds="xri://$xrds"
           xmlns="xri://$xrd*($v*2.0)"
           >
  <XRD>
    <Service priority="0">
      <Type>http://specs.openid.net/auth/2.0/return_to</Type>
      <URI>http://rp.example.com/return</URI>
    </Service>
    <Service priority="1">
      <Type>http://specs.openid.net/auth/2.0/return_to</Type>
      <URI>http://other.rp.example.com/return</URI>
    </Service>
  </XRD>
</xrds:XRDS>
', array('http://rp.example.com/return',
         'http://other.rp.example.com/return'));
    }

    function test_twoEntries_withOther()
    {
        $this->failUnlessXRDSHasReturnURLs('<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS xmlns:xrds="xri://$xrds"
           xmlns="xri://$xrd*($v*2.0)"
           >
  <XRD>
    <Service priority="0">
      <Type>http://specs.openid.net/auth/2.0/return_to</Type>
      <URI>http://rp.example.com/return</URI>
    </Service>
    <Service priority="1">
      <Type>http://specs.openid.net/auth/2.0/return_to</Type>
      <URI>http://other.rp.example.com/return</URI>
    </Service>
    <Service priority="0">
      <Type>http://example.com/LOLCATS</Type>
      <URI>http://example.com/invisible+uri</URI>
    </Service>
  </XRD>
</xrds:XRDS>
', array('http://rp.example.com/return',
         'http://other.rp.example.com/return'));
    }
}

class Tests_Auth_OpenID_ReturnToMatches extends PHPUnit_Framework_TestCase {
    function test_noEntries()
    {
        $this->assertFalse(Auth_OpenID_returnToMatches(array(), 'anything'));
    }

    function test_exactMatch()
    {
        $r = 'http://example.com/return.to';
        $this->assertTrue(Auth_OpenID_returnToMatches(array($r), $r));
    }

    function test_garbageMatch()
    {
        $r = 'http://example.com/return.to';
        $this->assertTrue(Auth_OpenID_returnToMatches(
                   array('This is not a URL at all. In fact, it has characters, ' .
                         'like "<" that are not allowed in URLs', $r), $r));
    }

    function test_descendant()
    {
        $r = 'http://example.com/return.to';
        $this->assertTrue(Auth_OpenID_returnToMatches(array($r),
            'http://example.com/return.to/user:joe'));
    }

    function test_wildcard()
    {
        $this->assertFalse(Auth_OpenID_returnToMatches(
                                array('http://*.example.com/return.to'),
                                'http://example.com/return.to'));
    }

    function test_noMatch()
    {
        $r = 'http://example.com/return.to';
        $this->assertFalse(Auth_OpenID_returnToMatches(array($r),
            'http://example.com/xss_exploit'));
    }
}

class Verifier {
    function Verifier($test_case, $return_to)
    {
        $this->tc =& $test_case;
        $this->return_to = $return_to;
    }

    function verify($disco_url)
    {
        $this->tc->assertEquals('http://www.example.com/', $disco_url);

        if ($this->return_to === false) {
            return false;
        } else {
            return array($this->return_to);
        }
    }
}

class Tests_Auth_OpenID_VerifyReturnTo extends PHPUnit_Framework_TestCase {

    function test_bogusRealm()
    {
        $this->assertFalse(Auth_OpenID_verifyReturnTo('', 'http://example.com/', null));
    }

    function test_verifyWithDiscoveryCalled()
    {
        $realm = 'http://*.example.com/';
        $return_to = 'http://www.example.com/foo';

        $v = new Verifier($this, $return_to);

        $this->assertTrue(Auth_OpenID_verifyReturnTo($realm, $return_to, null, array($v, 'verify')));
    }

    function test_verifyFailWithDiscoveryCalled()
    {
        $realm = 'http://*.example.com/';
        $return_to = 'http://www.example.com/foo';

        $v = new Verifier($this, 'http://something-else.invalid/');

        $this->assertFalse(Auth_OpenID_verifyReturnTo($realm, $return_to, null, array($v, 'verify')));
    }

    function test_verifyFailIfDiscoveryRedirects()
    {
        $realm = 'http://*.example.com/';
        $return_to = 'http://www.example.com/foo';

        $v = new Verifier($this, false);

        $this->assertFalse(Auth_OpenID_verifyReturnTo($realm, $return_to, null, array($v, 'verify')));
    }
}

class Tests_Auth_OpenID_RPVerify extends PHPUnit_Framework_TestSuite {
    function getName()
    {
        return "Tests_Auth_OpenID_RPVerify";
    }

    function Tests_Auth_OpenID_RPVerify()
    {
        $this->addTestSuite('Tests_Auth_OpenID_VerifyReturnTo');
        $this->addTestSuite('Tests_Auth_OpenID_ReturnToMatches');
        $this->addTestSuite('Tests_Auth_OpenID_ExtractReturnToURLs');
        $this->addTestSuite('Tests_Auth_OpenID_BuildDiscoveryURL');
    }
}


code:
<?php

/**
 * SReg.php testing code.
 */

require_once 'Auth/OpenID/SReg.php';
require_once 'Auth/OpenID/Message.php';
require_once 'Auth/OpenID/Server.php';

class SRegURITest extends PHPUnit_Framework_TestCase {
    function test_is11()
    {
        $this->assertEquals(Auth_OpenID_SREG_NS_URI_1_1,
                            Auth_OpenID_SREG_NS_URI);
    }
}

class CheckFieldNameTest extends PHPUnit_Framework_TestCase {
    function test_goodNamePasses()
    {
        global $Auth_OpenID_sreg_data_fields;

        foreach ($Auth_OpenID_sreg_data_fields as $field_name => $desc) {
            $this->assertTrue(Auth_OpenID_checkFieldName($field_name));
        }
    }

    function test_badNameFails()
    {
        $this->assertfalse(Auth_OpenID_checkFieldName('INVALID'));
    }

    function test_badTypeFails()
    {
        $this->assertfalse(Auth_OpenID_checkFieldName(null));
    }
}

// For supportsSReg test
class FakeEndpoint {
    function FakeEndpoint($supported)
    {
        $this->supported = $supported;
        $this->checked_uris = array();
    }

    function usesExtension($namespace_uri)
    {
        $this->checked_uris[] = $namespace_uri;
        return in_array($namespace_uri, $this->supported);
    }
}

class SupportsSRegTest extends PHPUnit_Framework_TestCase {
    function test_unsupported()
    {
        $endpoint = new FakeEndpoint(array());
        $this->assertfalse(Auth_OpenID_supportsSReg($endpoint));
        $this->assertEquals(array(Auth_OpenID_SREG_NS_URI_1_1,
                                  Auth_OpenID_SREG_NS_URI_1_0),
                            $endpoint->checked_uris);
    }

    function test_supported_1_1()
    {
        $endpoint = new FakeEndpoint(array(Auth_OpenID_SREG_NS_URI_1_1));
        $this->assertTrue(Auth_OpenID_supportsSReg($endpoint));
        $this->assertEquals(array(Auth_OpenID_SREG_NS_URI_1_1),
                            $endpoint->checked_uris);
    }

    function test_supported_1_0()
    {
        $endpoint = new FakeEndpoint(array(Auth_OpenID_SREG_NS_URI_1_0));
        $this->assertTrue(Auth_OpenID_supportsSReg($endpoint));
        $this->assertEquals(array(Auth_OpenID_SREG_NS_URI_1_1,
                                     Auth_OpenID_SREG_NS_URI_1_0),
                               $endpoint->checked_uris);
    }
}

class FakeMessage {
    function FakeMessage()
    {
        $this->openid1 = false;
        $this->namespaces = new Auth_OpenID_NamespaceMap();
    }

    function isOpenID1()
    {
        return $this->openid1;
    }
}

class GetNSTest extends PHPUnit_Framework_TestCase {
    function setUp()
    {
        $this->msg = new FakeMessage();
    }

    function test_openID2Empty()
    {
        $ns_uri = Auth_OpenID_SRegBase::_getSRegNS($this->msg);
        $this->assertEquals($this->msg->namespaces->getAlias($ns_uri), 'sreg');
        $this->assertEquals(Auth_OpenID_SREG_NS_URI, $ns_uri);
    }

    function test_openID1Empty()
    {
        $this->msg->openid1 = true;
        $ns_uri = Auth_OpenID_SRegBase::_getSRegNS($this->msg);
        $this->assertEquals($this->msg->namespaces->getAlias($ns_uri), 'sreg');
        $this->assertEquals(Auth_OpenID_SREG_NS_URI, $ns_uri);
    }

    function test_openID1Defined_1_0()
    {
        $this->msg->openid1 = true;
        $this->msg->namespaces->add(Auth_OpenID_SREG_NS_URI_1_0);
        $ns_uri = Auth_OpenID_SRegBase::_getSRegNS($this->msg);
        $this->assertEquals(Auth_OpenID_SREG_NS_URI_1_0, $ns_uri);
    }

    function test_openID1Defined_1_0_overrideAlias()
    {
        foreach (array(true, false) as $openid_version) {
            foreach (array(Auth_OpenID_SREG_NS_URI_1_0,
                           Auth_OpenID_SREG_NS_URI_1_1) as $sreg_version) {
                foreach (array('sreg', 'bogus') as $alias) {
                    $this->setUp();

                    $this->msg->openid1 = $openid_version;
                    $this->assertTrue($this->msg->namespaces->addAlias($sreg_version, $alias) !== null);
                    $ns_uri = Auth_OpenID_SRegBase::_getSRegNS($this->msg);
                    $this->assertEquals($this->msg->namespaces->getAlias($ns_uri), $alias);
                    $this->assertEquals($sreg_version, $ns_uri);
                }
            }
        }
    }

    function test_openID1DefinedBadly()
    {
        $this->msg->openid1 = true;
        $this->msg->namespaces->addAlias('http://invalid/', 'sreg');
        $this->assertTrue(Auth_OpenID_SRegBase::_getSRegNS($this->msg) === null);
    }

    function test_openID2DefinedBadly()
    {
        $this->msg->openid1 = false;
        $this->msg->namespaces->addAlias('http://invalid/', 'sreg');
        $this->assertTrue(Auth_OpenID_SRegBase::_getSRegNS($this->msg) === null);
    }

    function test_openID2Defined_1_0()
    {
        $this->msg->namespaces->add(Auth_OpenID_SREG_NS_URI_1_0);
        $ns_uri = Auth_OpenID_SRegBase::_getSRegNS($this->msg);
        $this->assertEquals(Auth_OpenID_SREG_NS_URI_1_0, $ns_uri);
    }

    function test_openID1_sregNSfromArgs()
    {
        $args = array(
            'sreg.optional' => 'nickname',
            'sreg.required' => 'dob');

        $m = Auth_OpenID_Message::fromOpenIDArgs($args);

        $this->assertTrue($m->getArg(Auth_OpenID_SREG_NS_URI_1_1, 'optional') == 'nickname');
        $this->assertTrue($m->getArg(Auth_OpenID_SREG_NS_URI_1_1, 'required') == 'dob');
    }
}

global $__args_sentinel;
global $__ns_sentinel;
$__args_sentinel = 'args_sentinel';
$__ns_sentinel = 'ns_sentinel';

class SentinelFakeMessage {
    function SentinelFakeMessage($test_case)
    {
        $this->test_case =& $test_case;
        $this->message = new Auth_OpenID_Message();
    }

    function getArgs($ns_uri)
    {
        global $__ns_sentinel, $__args_sentinel;
        $this->test_case->assertEquals($__ns_sentinel, $ns_uri);
        return $__args_sentinel;
    }
}

// XXX Ugly hack.  Thanks, PHP.
global $__TestingReq_TEST_CASE;
$__TestingReq_TEST_CASE = "FLUB";

function __setTestCase($thing) {
  global $__TestingReq_TEST_CASE;
  $__TestingReq_TEST_CASE = $thing;
}

function &__getTestCase() {
  global $__TestingReq_TEST_CASE;
  return $__TestingReq_TEST_CASE;
}

class TestingReq extends Auth_OpenID_SRegRequest {
    static function fromOpenIDRequest($thing, $test_case)
    {
        __setTestCase($test_case);
        $obj = parent::fromOpenIDRequest($thing, 'TestingReq');
        return $obj;
    }

    static function _getSRegNS($unused)
    {
        global $__ns_sentinel;
        return $__ns_sentinel;
    }

    function parseExtensionArgs($args)
    {
        global $__args_sentinel;
        $tc =& __getTestCase();
        $tc->assertEquals($__args_sentinel, $args);
    }
}

class SRegRequestTest extends PHPUnit_Framework_TestCase {
    function test_constructEmpty()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertEquals(array(), $req->optional);
        $this->assertEquals(array(), $req->required);
        $this->assertEquals(null, $req->policy_url);
        $this->assertEquals(Auth_OpenID_SREG_NS_URI, $req->ns_uri);
    }

    function test_constructFields()
    {
        $req = Auth_OpenID_SRegRequest::build(
                                              array('nickname'),
                                              array('gender'),
                                              'http://policy',
                                              'http://sreg.ns_uri');
        $this->assertEquals(array('gender'), $req->optional);
        $this->assertEquals(array('nickname'), $req->required);
        $this->assertEquals('http://policy', $req->policy_url);
        $this->assertEquals('http://sreg.ns_uri', $req->ns_uri);
    }

    function test_constructBadFields()
    {
        $this->assertTrue(Auth_OpenID_SRegRequest::build(array('elvis')) === null);
    }

    function test_fromOpenIDResponse()
    {
        $openid_req = new Auth_OpenID_Request();

        $msg = new SentinelFakeMessage($this);
        $openid_req->message =& $msg;

        $req = TestingReq::fromOpenIDRequest($openid_req, $this);
        $this->assertTrue(is_a($req, 'TestingReq'));
    }

    function test_parseExtensionArgs_empty()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array()));
    }

    function test_parseExtensionArgs_extraIgnored()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('janrain' => 'inc')));
    }

    function test_parseExtensionArgs_nonStrict()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('required' => 'beans')));
        $this->assertEquals(array(), $req->required);
    }

    function test_parseExtensionArgs_strict()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertFalse($req->parseExtensionArgs(array('required' => 'beans'),
                                                    true));
    }

    function test_parseExtensionArgs_policy()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(
                                array('policy_url' => 'http://policy'), true));
        $this->assertEquals('http://policy', $req->policy_url);
    }

    function test_parseExtensionArgs_requiredEmpty()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('required' => ''), true));
        $this->assertEquals(array(), $req->required);
    }

    function test_parseExtensionArgs_optionalEmpty()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('optional' => ''), true));
        $this->assertEquals(array(), $req->optional);
    }

    function test_parseExtensionArgs_optionalSingle()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('optional' => 'nickname'), true));
        $this->assertEquals(array('nickname'), $req->optional);
    }

    function test_parseExtensionArgs_optionalList()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('optional' => 'nickname,email'), true));
        $this->assertEquals(array('nickname','email'), $req->optional);
    }

    function test_parseExtensionArgs_optionalListBadNonStrict()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('optional' => 'nickname,email,beer')));
        $this->assertEquals(array('nickname','email'), $req->optional);
    }

    function test_parseExtensionArgs_optionalListBadStrict()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertFalse($req->parseExtensionArgs(array('optional' => 'nickname,email,beer'),
                                                    true));
    }

    function test_parseExtensionArgs_bothNonStrict()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('optional' => 'nickname',
                                                         'required' => 'nickname')));
        $this->assertEquals(array(), $req->optional);
        $this->assertEquals(array('nickname'), $req->required);
    }

    function test_parseExtensionArgs_bothStrict()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertFalse($req->parseExtensionArgs(
                                                    array('optional' => 'nickname',
                                                          'required' => 'nickname'),
                                                    true));
    }

    function test_parseExtensionArgs_bothList()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertTrue($req->parseExtensionArgs(array('optional' => 'nickname,email',
                                                         'required' => 'country,postcode'),
                                                   true));
        $this->assertEquals(array('nickname','email'), $req->optional);
        $this->assertEquals(array('country','postcode'), $req->required);
    }

    function test_allRequestedFields()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertEquals(array(), $req->allRequestedFields());
        $req->requestField('nickname');
        $this->assertEquals(array('nickname'), $req->allRequestedFields());
        $req->requestField('gender', true);
        $requested = $req->allRequestedFields();
        sort($requested);
        $this->assertEquals(array('gender', 'nickname'), $requested);
    }

    function test_wereFieldsRequested()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertFalse($req->wereFieldsRequested());
        $req->requestField('gender');
        $this->assertTrue($req->wereFieldsRequested());
    }

    function test_contains()
    {
        global $Auth_OpenID_sreg_data_fields;

        $req = Auth_OpenID_SRegRequest::build();
        foreach ($Auth_OpenID_sreg_data_fields as $field_name => $desc) {
            $this->assertFalse($req->contains($field_name));
        }

        $this->assertFalse($req->contains('something else'));

        $req->requestField('nickname');
        foreach ($Auth_OpenID_sreg_data_fields as $field_name => $desc) {
            if ($field_name == 'nickname') {
                $this->assertTrue($req->contains($field_name));
            } else {
                $this->assertFalse($req->contains($field_name));
            }
        }
    }

    function test_requestField_bogus()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertFalse($req->requestField('something else'));
        $this->assertFalse($req->requestField('something else', true));
    }

    function test_requestField()
    {
        global $Auth_OpenID_sreg_data_fields;

        // Add all of the fields, one at a time
        $req = Auth_OpenID_SRegRequest::build();
        $fields = array_keys($Auth_OpenID_sreg_data_fields);
        foreach ($fields as $field_name) {
            $req->requestField($field_name);
        }

        $this->assertEquals($fields, $req->optional);
        $this->assertEquals(array(), $req->required);

        // By default, adding the same fields over again has no effect
        foreach ($fields as $field_name) {
            $req->requestField($field_name);
        }

        $this->assertEquals($fields, $req->optional);
        $this->assertEquals(array(), $req->required);

        // Requesting a field as required overrides requesting it as
        // optional
        $expected = $fields;
        $overridden = array_pop($expected);

        $this->assertTrue($req->requestField($overridden, true));

        $this->assertEquals($expected, $req->optional);
        $this->assertEquals(array($overridden), $req->required);

        // Requesting a field as required overrides requesting it as
        // optional
        foreach ($fields as $field_name) {
            $this->assertTrue($req->requestField($field_name, true));
        }

        $this->assertEquals(array(), $req->optional);
        foreach ($fields as $f) {
            $this->assertTrue(in_array($f, $req->required));
        }

        // Requesting it as optional does not downgrade it to optional
        foreach ($fields as $field_name) {
            $req->requestField($field_name);
        }

        $this->assertEquals(array(), $req->optional);

        foreach ($fields as $f) {
            $this->assertTrue(in_array($f, $req->required));
        }
    }

    function test_requestFields_type()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertFalse($req->requestFields('nickname'));
    }

    function test_requestFields()
    {
        global $Auth_OpenID_sreg_data_fields;

        // Add all of the fields
        $req = Auth_OpenID_SRegRequest::build();

        $fields = array_keys($Auth_OpenID_sreg_data_fields);
        $req->requestFields($fields);

        $this->assertEquals($fields, $req->optional);
        $this->assertEquals(array(), $req->required);

        // By default, adding the same fields over again has no effect
        $req->requestFields($fields);

        $this->assertEquals($fields, $req->optional);
        $this->assertEquals(array(), $req->required);

        // Requesting a field as required overrides requesting it as
        // optional
        $expected = $fields;
        $overridden = array_shift($expected);
        $req->requestFields(array($overridden), true);

        foreach ($expected as $f) {
            $this->assertTrue(in_array($f, $req->optional));
        }

        $this->assertEquals(array($overridden), $req->required);

        // Requesting a field as required overrides requesting it as
        // optional
        $req->requestFields($fields, true);

        $this->assertEquals(array(), $req->optional);
        $this->assertEquals($fields, $req->required);

        // Requesting it as optional does not downgrade it to optional
        $req->requestFields($fields);

        $this->assertEquals(array(), $req->optional);
        $this->assertEquals($fields, $req->required);
    }

    function test_getExtensionArgs()
    {
        $req = Auth_OpenID_SRegRequest::build();
        $this->assertEquals(array(), $req->getExtensionArgs());

        $this->assertTrue($req->requestField('nickname'));
        $this->assertEquals(array('optional' => 'nickname'),
                            $req->getExtensionArgs());

        $this->assertTrue($req->requestField('email'));
        $this->assertEquals(array('optional' => 'nickname,email'),
                            $req->getExtensionArgs());

        $this->assertTrue($req->requestField('gender', true));
        $this->assertEquals(array('optional' => 'nickname,email',
                                  'required' => 'gender'),
                            $req->getExtensionArgs());

        $this->assertTrue($req->requestField('postcode', true));
        $this->assertEquals(array('optional' => 'nickname,email',
                                  'required' => 'gender,postcode'),
                            $req->getExtensionArgs());

        $req->policy_url = 'http://policy.invalid/';
        $this->assertEquals(array('optional' => 'nickname,email',
                                  'required' => 'gender,postcode',
                                  'policy_url' => 'http://policy.invalid/'),
                            $req->getExtensionArgs());
    }
}

class DummySuccessResponse {
    function DummySuccessResponse($message, $signed_stuff)
    {
        $this->message = $message;
        $this->signed_stuff = $signed_stuff;
    }

    function getSignedNS($ns_uri)
    {
        return $this->signed_stuff;
    }
}

class SRegResponseTest extends PHPUnit_Framework_TestCase {
    function test_fromSuccessResponse_signed()
    {
        $message = Auth_OpenID_Message::fromOpenIDArgs(array(
            'sreg.nickname' => 'The Mad Stork',
            ));
        $success_resp = new DummySuccessResponse($message, array());
        $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($success_resp);
        $this->assertTrue(count($sreg_resp->contents()) === 0);
    }

    function test_fromSuccessResponse_unsigned()
    {
        $message = Auth_OpenID_Message::fromOpenIDArgs(array(
            'sreg.nickname' => 'The Mad Stork',
            ));

        $success_resp = new DummySuccessResponse($message, array());
        $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($success_resp,
                                                                   false);

        $this->assertEquals(array('nickname' => 'The Mad Stork'),
                            $sreg_resp->contents());
    }
}

class SendFieldsTest extends PHPUnit_Framework_TestCase {
    function _test($uri)
    {
        // Create a request message with simple registration fields
        $sreg_req = Auth_OpenID_SRegRequest::build(array('nickname', 'email'),
                                                   array('fullname'));
        $req_msg = new Auth_OpenID_Message($uri);
        $req_msg->updateArgs(Auth_OpenID_SREG_NS_URI,
                             $sreg_req->getExtensionArgs());

        $req = new Auth_OpenID_Request();
        $req->message =& $req_msg;
        $req->namespace = $req_msg->getOpenIDNamespace();

        // -> send checkid_* request

        // Create an empty response message
        $resp_msg = new Auth_OpenID_Message($uri);
        $resp = new Auth_OpenID_ServerResponse($req);
        $resp->fields = $resp_msg;

        $data = array(
                      'nickname' => 'linusaur',
                      'postcode' => '12345',
                      'country' => 'US',
                      'gender' => 'M',
                      'fullname' => 'Leonhard Euler',
                      'email' => 'president@whitehouse.gov',
                      'dob' => '0000-00-00',
                      'language' => 'en-us');

        // Put the requested data fields in the response message
        $sreg_resp = Auth_OpenID_SRegResponse::extractResponse($sreg_req, $data);
        $resp->addExtension($sreg_resp);

        // <- send id_res response

        // Extract the fields that were sent
        $sreg_data_resp = $resp->fields->getArgs(Auth_OpenID_SREG_NS_URI);
        $this->assertEquals(
                            array('nickname' => 'linusaur',
                                  'email' => 'president@whitehouse.gov',
                                  'fullname' => 'Leonhard Euler'),
                            $sreg_data_resp);
    }

    function test()
    {
        foreach (array(Auth_OpenID_OPENID1_NS,
                       Auth_OpenID_OPENID2_NS) as $uri) {
            $this->_test($uri);
        }
    }
}

class Tests_Auth_OpenID_SReg extends PHPUnit_Framework_TestSuite {
    function getName()
    {
        return "Tests_Auth_OpenID_SReg";
    }

    function Tests_Auth_OpenID_SReg()
    {
        $this->addTestSuite('SRegURITest');
        $this->addTestSuite('CheckFieldNameTest');
        $this->addTestSuite('SupportsSRegTest');
        $this->addTestSuite('GetNSTest');
        $this->addTestSuite('SRegRequestTest');
        $this->addTestSuite('SRegResponseTest');
        $this->addTestSuite('SendFieldsTest');
    }
}