1
0

YourlsProxyTest.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. use PHPUnit\Framework\TestCase;
  3. use PrivateBin\Configuration;
  4. use PrivateBin\YourlsProxy;
  5. class YourlsProxyTest extends TestCase
  6. {
  7. private $_conf;
  8. private $_path;
  9. private $_mock_yourls_service;
  10. public function setUp(): void
  11. {
  12. /* Setup Routine */
  13. $this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
  14. if (!is_dir($this->_path)) {
  15. mkdir($this->_path);
  16. }
  17. $this->_mock_yourls_service = $this->_path . DIRECTORY_SEPARATOR . 'yourls.json';
  18. $options = parse_ini_file(CONF_SAMPLE, true);
  19. $options['main']['basepath'] = 'https://example.com/';
  20. $options['main']['urlshortener'] = 'https://example.com/shortenviayourls?link=';
  21. $options['yourls']['apiurl'] = $this->_mock_yourls_service;
  22. Helper::confBackup();
  23. Helper::createIniFile(CONF, $options);
  24. $this->_conf = new Configuration;
  25. }
  26. public function tearDown(): void
  27. {
  28. /* Tear Down Routine */
  29. unlink(CONF);
  30. Helper::confRestore();
  31. Helper::rmDir($this->_path);
  32. }
  33. public function testYourlsProxy()
  34. {
  35. // the real service answer is more complex, but we only look for the shorturl & statusCode
  36. file_put_contents($this->_mock_yourls_service, '{"shorturl":"https:\/\/example.com\/1","statusCode":200}');
  37. $yourls = new YourlsProxy($this->_conf, 'https://example.com/?foo#bar');
  38. $this->assertFalse($yourls->isError());
  39. $this->assertEquals($yourls->getUrl(), 'https://example.com/1');
  40. }
  41. public function testForeignUrl()
  42. {
  43. $yourls = new YourlsProxy($this->_conf, 'https://other.example.com/?foo#bar');
  44. $this->assertTrue($yourls->isError());
  45. $this->assertEquals($yourls->getError(), 'Trying to shorten a URL that isn\'t pointing at our instance.');
  46. }
  47. public function testYourlsError()
  48. {
  49. // when statusCode is not 200, shorturl may not have been set
  50. file_put_contents($this->_mock_yourls_service, '{"statusCode":403}');
  51. $yourls = new YourlsProxy($this->_conf, 'https://example.com/?foo#bar');
  52. $this->assertTrue($yourls->isError());
  53. $this->assertEquals($yourls->getError(), 'Error parsing YOURLS response.');
  54. }
  55. public function testServerError()
  56. {
  57. // simulate some other server error that results in a non-JSON reply
  58. file_put_contents($this->_mock_yourls_service, '500 Internal Server Error');
  59. $yourls = new YourlsProxy($this->_conf, 'https://example.com/?foo#bar');
  60. $this->assertTrue($yourls->isError());
  61. $this->assertEquals($yourls->getError(), 'Error calling YOURLS. Probably a configuration issue, like wrong or missing "apiurl" or "signature".');
  62. }
  63. }