summaryrefslogtreecommitdiff
path: root/plugins/OStatus/tests/remote-tests.php
blob: b064114911212580df7cece401e451c70e7d99b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
<?php

if (php_sapi_name() != 'cli') {
    die('not for web');
}

define('INSTALLDIR', dirname(dirname(dirname(dirname(__FILE__)))));
set_include_path(INSTALLDIR . '/extlib' . PATH_SEPARATOR . get_include_path());

require_once 'PEAR.php';
require_once 'Net/URL2.php';
require_once 'HTTP/Request2.php';


// ostatus test script, client-side :)

class TestBase
{
    function log($str)
    {
        $args = func_get_args();
        array_shift($args);

        $msg = vsprintf($str, $args);
        print $msg . "\n";
    }

    function assertEqual($a, $b)
    {
        if ($a != $b) {
            throw new Exception("Failed to assert equality: expected $a, got $b");
        }
        return true;
    }

    function assertNotEqual($a, $b)
    {
        if ($a == $b) {
            throw new Exception("Failed to assert inequality: expected not $a, got $b");
        }
        return true;
    }

    function assertTrue($a)
    {
        if (!$a) {
            throw new Exception("Failed to assert true: got false");
        }
    }

    function assertFalse($a)
    {
        if ($a) {
            throw new Exception("Failed to assert false: got true");
        }
    }
}

class OStatusTester extends TestBase
{
    /**
     * @param string $a base URL of test site A (eg http://localhost/mublog)
     * @param string $b base URL of test site B (eg http://localhost/mublog2)
     */
    function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;

        $base = 'test' . mt_rand(1, 1000000);
        $this->pub = new SNTestClient($this->a, 'pub' . $base, 'pw-' . mt_rand(1, 1000000));
        $this->sub = new SNTestClient($this->b, 'sub' . $base, 'pw-' . mt_rand(1, 1000000));
    }

    function run()
    {
        $this->setup();

        $this->testLocalPost();
        $this->testMentionUrl();
        $this->testSubscribe();
        $this->testUnsubscribe();

        $this->log("DONE!");
    }

    function setup()
    {
        $this->pub->register();
        $this->pub->assertRegistered();

        $this->sub->register();
        $this->sub->assertRegistered();
    }

    function testLocalPost()
    {
        $post = $this->pub->post("Local post, no subscribers yet.");
        $this->assertNotEqual('', $post);

        $post = $this->sub->post("Local post, no subscriptions yet.");
        $this->assertNotEqual('', $post);
    }

    /**
     * pub posts: @b/sub
     */
    function testMentionUrl()
    {
        $bits = parse_url($this->b);
        $base = $bits['host'];
        if (isset($bits['path'])) {
            $base .= $bits['path'];
        }
        $name = $this->sub->username;

        $post = $this->pub->post("@$base/$name should have this in home and replies");
        $this->sub->assertReceived($post);
    }

    function testSubscribe()
    {
        $this->assertFalse($this->sub->hasSubscription($this->pub->getProfileUri()));
        $this->assertFalse($this->pub->hasSubscriber($this->sub->getProfileUri()));
        $this->sub->subscribe($this->pub->getProfileLink());
        $this->assertTrue($this->sub->hasSubscription($this->pub->getProfileUri()));
        $this->assertTrue($this->pub->hasSubscriber($this->sub->getProfileUri()));
    }

    function testUnsubscribe()
    {
        $this->assertTrue($this->sub->hasSubscription($this->pub->getProfileUri()));
        $this->assertTrue($this->pub->hasSubscriber($this->sub->getProfileUri()));
        $this->sub->unsubscribe($this->pub->getProfileLink());
        $this->assertFalse($this->sub->hasSubscription($this->pub->getProfileUri()));
        $this->assertFalse($this->pub->hasSubscriber($this->sub->getProfileUri()));
    }

}

class SNTestClient extends TestBase
{
    function __construct($base, $username, $password)
    {
        $this->basepath = $base;
        $this->username = $username;
        $this->password = $password;

        $this->fullname = ucfirst($username) . ' Smith';
        $this->homepage = 'http://example.org/' . $username;
        $this->bio = 'Stub account for OStatus tests.';
        $this->location = 'Montreal, QC';
    }

    /**
     * Make a low-level web hit to this site, with authentication.
     * @param string $path URL fragment for something under the base path
     * @param array $params POST parameters to send
     * @param boolean $auth whether to include auth data
     * @return string
     * @throws Exception on low-level error conditions
     */
    protected function hit($path, $params=array(), $auth=false, $cookies=array())
    {
        $url = $this->basepath . '/' . $path;

        $http = new HTTP_Request2($url, 'POST');
        if ($auth) {
            $http->setAuth($this->username, $this->password, HTTP_Request2::AUTH_BASIC);
        }
        foreach ($cookies as $name => $val) {
            $http->addCookie($name, $val);
        }
        $http->addPostParameter($params);
        $response = $http->send();

        $code = $response->getStatus();
        if ($code < '200' || $code >= '400') {
            throw new Exception("Failed API hit to $url: $code\n" . $response->getBody());
        }

        return $response;
    }

    /**
     * Make a hit to a web form, without authentication but with a session.
     * @param string $path URL fragment relative to site base
     * @param string $form id of web form to pull initial parameters from
     * @param array $params POST parameters, will be merged with defaults in form
     */
    protected function web($path, $form, $params=array())
    {
        $url = $this->basepath . '/' . $path;
        $http = new HTTP_Request2($url, 'GET');
        $response = $http->send();

        $dom = $this->checkWeb($url, 'GET', $response);
        $cookies = array();
        foreach ($response->getCookies() as $cookie) {
            // @fixme check for expirations etc
            $cookies[$cookie['name']] = $cookie['value'];
        }

        $form = $dom->getElementById($form);
        if (!$form) {
            throw new Exception("Form $form not found on $url");
        }
        $inputs = $form->getElementsByTagName('input');
        foreach ($inputs as $item) {
            $type = $item->getAttribute('type');
            if ($type != 'check') {
                $name = $item->getAttribute('name');
                $val = $item->getAttribute('value');
                if ($name && $val && !isset($params[$name])) {
                    $params[$name] = $val;
                }
            }
        }

        $response = $this->hit($path, $params, false, $cookies);
        $dom = $this->checkWeb($url, 'POST', $response);

        return $dom;
    }

    protected function checkWeb($url, $method, $response)
    {
        $dom = new DOMDocument();
        if (!$dom->loadHTML($response->getBody())) {
            throw new Exception("Invalid HTML from $method to $url");
        }

        $xpath = new DOMXPath($dom);
        $error = $xpath->query('//p[@class="error"]');
        if ($error && $error->length) {
            throw new Exception("Error on $method to $url: " .
                                $error->item(0)->textContent);
        }

        return $dom;
    }

    protected function parseXml($path, $body)
    {
        $dom = new DOMDocument();
        if ($dom->loadXML($body)) {
            return $dom;
        } else {
            throw new Exception("Bogus XML data from $path:\n$body");
        }
    }

    /**
     * Make a hit to a REST-y XML page on the site, without authentication.
     * @param string $path URL fragment for something relative to base
     * @param array $params POST parameters to send
     * @return DOMDocument
     * @throws Exception on low-level error conditions
     */
    protected function xml($path, $params=array())
    {
        $response = $this->hit($path, $params, true);
        $body = $response->getBody();
        return $this->parseXml($path, $body);
    }

    protected function parseJson($path, $body)
    {
        $data = json_decode($body, true);
        if ($data !== null) {
            if (!empty($data['error'])) {
                throw new Exception("JSON API returned error: " . $data['error']);
            }
            return $data;
        } else {
            throw new Exception("Bogus JSON data from $path:\n$body");
        }
    }

    /**
     * Make an API hit to this site, with authentication.
     * @param string $path URL fragment for something under 'api' folder
     * @param string $style one of 'json', 'xml', or 'atom'
     * @param array $params POST parameters to send
     * @return mixed associative array for JSON, DOMDocument for XML/Atom
     * @throws Exception on low-level error conditions
     */
    protected function api($path, $style, $params=array())
    {
        $response = $this->hit("api/$path.$style", $params, true);
        $body = $response->getBody();
        if ($style == 'json') {
            return $this->parseJson($path, $body);
        } else if ($style == 'xml' || $style == 'atom') {
            return $this->parseXml($path, $body);
        } else {
            throw new Exception("API needs to be JSON, XML, or Atom");
        }
    }

    /**
     * Register the account.
     *
     * Unfortunately there's not an API method for registering, so we fake it.
     */
    function register()
    {
        $this->log("Registering user %s on %s",
                   $this->username,
                   $this->basepath);
        $ret = $this->web('main/register', 'form_register',
            array('nickname' => $this->username,
                  'password' => $this->password,
                  'confirm' => $this->password,
                  'fullname' => $this->fullname,
                  'homepage' => $this->homepage,
                  'bio' => $this->bio,
                  'license' => 1,
                  'submit' => 'Register'));
    }

    /**
     * @return string canonical URI/URL to profile page
     */
    function getProfileUri()
    {
        $data = $this->api('account/verify_credentials', 'json');
        $id = $data['id'];
        return $this->basepath . '/user/' . $id;
    }

    /**
     * @return string human-friendly URL to profile page
     */
    function getProfileLink()
    {
        return $this->basepath . '/' . $this->username;
    }

    /**
     * Check that the account has been registered and can be used.
     * On failure, throws a test failure exception.
     */
    function assertRegistered()
    {
        $this->log("Confirming %s is registered on %s",
                   $this->username,
                   $this->basepath);
        $data = $this->api('account/verify_credentials', 'json');
        $this->assertEqual($this->username, $data['screen_name']);
        $this->assertEqual($this->fullname, $data['name']);
        $this->assertEqual($this->homepage, $data['url']);
        $this->assertEqual($this->bio, $data['description']);
    }

    /**
     * Post a given message from this account
     * @param string $message
     * @return string URL/URI of notice
     * @todo reply, location options
     */
    function post($message)
    {
        $this->log("Posting notice as %s on %s: %s",
                   $this->username,
                   $this->basepath,
                   $message);
        $data = $this->api('statuses/update', 'json',
            array('status' => $message));

        $url = $this->basepath . '/notice/' . $data['id'];
        return $url;
    }

    /**
     * Check that this account has received the notice.
     * @param string $notice_uri URI for the notice to check for
     */
    function assertReceived($notice_uri)
    {
        $timeout = 5;
        $tries = 6;
        while ($tries) {
            $ok = $this->checkReceived($notice_uri);
            if ($ok) {
                return true;
            }
            $tries--;
            if ($tries) {
                $this->log("Didn't see it yet, waiting $timeout seconds");
                sleep($timeout);
            }
        }
        throw new Exception("Message $notice_uri not received by $this->username");
    }

    /**
     * Pull the user's home timeline to check if a notice with the given
     * source URL has been received recently.
     * If we don't see it, we'll try a couple more times up to 10 seconds.
     *
     * @param string $notice_uri
     */
    function checkReceived($notice_uri)
    {
        $this->log("Checking if %s on %s received notice %s",
                   $this->username,
                   $this->basepath,
                   $notice_uri);
        $params = array();
        $dom = $this->api('statuses/home_timeline', 'atom', $params);

        $xml = simplexml_import_dom($dom);
        if (!$xml->entry) {
            return false;
        }
        if (is_array($xml->entry)) {
            $entries = $xml->entry;
        } else {
            $entries = array($xml->entry);
        }
        foreach ($entries as $entry) {
            if ($entry->id == $notice_uri) {
                $this->log("found it $notice_uri");
                return true;
            }
            //$this->log("nope... " . $entry->id);
        }
        return false;
    }

    /**
     * @param string $profile user page link or webfinger
     */
    function subscribe($profile)
    {
        // This uses the command interface, since there's not currently
        // a friendly Twit-API way to do a fresh remote subscription and
        // the web form's a pain to use.
        $this->post('follow ' . $profile);
    }

    /**
     * @param string $profile user page link or webfinger
     */
    function unsubscribe($profile)
    {
        // This uses the command interface, since there's not currently
        // a friendly Twit-API way to do a fresh remote subscription and
        // the web form's a pain to use.
        $this->post('leave ' . $profile);
    }

    /**
     * Check that this account is subscribed to the given profile.
     * @param string $profile_uri URI for the profile to check for
     * @return boolean
     */
    function hasSubscription($profile_uri)
    {
        $this->log("Checking if $this->username has a subscription to $profile_uri");

        $me = $this->getProfileUri();
        return $this->checkSubscription($me, $profile_uri);
    }

    /**
     * Check that this account is subscribed to by the given profile.
     * @param string $profile_uri URI for the profile to check for
     * @return boolean
     */
    function hasSubscriber($profile_uri)
    {
        $this->log("Checking if $this->username is subscribed to by $profile_uri");

        $me = $this->getProfileUri();
        return $this->checkSubscription($profile_uri, $me);
    }
    
    protected function checkSubscription($subscriber, $subscribed)
    {
        // Using FOAF as the API methods for checking the social graph
        // currently are unfriendly to remote profiles
        $ns_foaf = 'http://xmlns.com/foaf/0.1/';
        $ns_sioc = 'http://rdfs.org/sioc/ns#';
        $ns_rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';

        $dom = $this->xml($this->username . '/foaf');
        $agents = $dom->getElementsByTagNameNS($ns_foaf, 'Agent');
        foreach ($agents as $agent) {
            $agent_uri = $agent->getAttributeNS($ns_rdf, 'about');
            if ($agent_uri == $subscriber) {
                $follows = $agent->getElementsByTagNameNS($ns_sioc, 'follows');
                foreach ($follows as $follow) {
                    $target = $follow->getAttributeNS($ns_rdf, 'resource');
                    if ($target == ($subscribed . '#acct')) {
                        $this->log("Confirmed $subscriber subscribed to $subscribed");
                        return true;
                    }
                }
                $this->log("We found $subscriber but they don't follow $subscribed");
                return false;
            }
        }
        $this->log("Can't find $subscriber in {$this->username}'s social graph.");
        return false;
    }

}

$args = array_slice($_SERVER['argv'], 1);
if (count($args) < 2) {
    print <<<END_HELP
remote-tests.php <url1> <url2>
  url1: base URL of a StatusNet instance
  url2: base URL of another StatusNet instance

This will register user accounts on the two given StatusNet instances
and run some tests to confirm that OStatus subscription and posting
between the two sites works correctly.

END_HELP;
exit(1);
}

$a = $args[0];
$b = $args[1];

$tester = new OStatusTester($a, $b);
$tester->run();