Skip to content

Commit

Permalink
Adds fixes/tests for runSnippet (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer authored Apr 23, 2019
1 parent 5350e08 commit a1eb4e2
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 16 deletions.
16 changes: 10 additions & 6 deletions src/TestUtils/TestTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,21 @@ private static function runSnippet($sampleName, $params = [])
}

$testFunc = function () use ($sampleFile, $params) {
return shell_exec(sprintf(
'php %s %s',
$sampleFile,
implode(' ', array_map('escapeshellarg', $params))
));
$argv = array_merge([$sampleFile], $params);
$argc = count($argv);
try {
ob_start();
require $sampleFile;
return ob_get_clean();
} catch (\Exception $e) {
ob_get_clean();
throw $e;
}
};

if (isset(self::$backoff)) {
return self::$backoff->execute($testFunc);
}

return $testFunc();
}
}
43 changes: 33 additions & 10 deletions test/TestUtils/TestTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
namespace Google\Cloud\TestUtils\test;

use Google\Cloud\TestUtils\TestTrait;
use Google\Cloud\TestUtils\ExponentialBackoffTrait;

/**
* Class TestTraitTest
Expand All @@ -28,8 +29,7 @@
class TestTraitTest extends \PHPUnit_Framework_TestCase
{
use TestTrait;

private static $backoff;
use ExponentialBackoffTrait;

public static function checkProjectEnvVarBeforeClass()
{
Expand Down Expand Up @@ -108,18 +108,41 @@ public function testRunSnippet()
$output1 = shell_exec($snippet2Cmd . ' foo bar baz');
$output2 = $this->runSnippet($snippet2File, ['foo', 'bar', 'baz']);
$this->assertEquals($output1, $output2);
}

public function testRunSnippetWithBackoff()
{
$this->useBackoff($retries = 5, function () use (&$timesCalled) {
$timesCalled++;
return true;
});

self::setDelayFunction(function ($delay) {
// do nothing!
});

try {
$output = $this->runSnippet('snippet3');
$this->fail('Should have thrown exception');
} catch (\Exception $e) {
$this->assertEquals('This is expected', $e->getMessage());
}

self::$backoff = new FakeBackoff();
$this->assertEquals($retries + 1, $timesCalled);
}

$output = $this->runSnippet('foo');
$this->assertEquals('FakeBackoff', $output);
/**
* @expectedException Exception
* @expectedExceptionMessage This is expected
*/
public function testRunSnippetWithException()
{
$this->runSnippet('snippet3');
}
}

class FakeBackoff
{
public function execute($fn)
public function setUp()
{
return "FakeBackoff";
// Clear backoffs before running each test
self::$backoff = null;
}
}
3 changes: 3 additions & 0 deletions test/src/snippet3.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

throw new Exception('This is expected');

0 comments on commit a1eb4e2

Please sign in to comment.