You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.6 KiB

2 years ago
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: x
  5. * Date: 2018/12/10
  6. * Time: 12:35 AM
  7. */
  8. namespace Tests\Feature;
  9. use GuzzleHttp\Handler\MockHandler;
  10. use GuzzleHttp\Psr7\Response;
  11. use QL\QueryList;
  12. use Tests\TestCaseBase;
  13. class HttpTest extends TestCaseBase
  14. {
  15. protected $urls;
  16. protected function setUp(): void
  17. {
  18. $this->urls = [
  19. 'http://httpbin.org/get?name=php',
  20. 'http://httpbin.org/get?name=golang',
  21. 'http://httpbin.org/get?name=c++',
  22. 'http://httpbin.org/get?name=java'
  23. ];
  24. }
  25. /**
  26. * @test
  27. */
  28. public function can_post_json_data()
  29. {
  30. $mock = new MockHandler([new Response()]);
  31. $data = [
  32. 'name' => 'foo'
  33. ];
  34. QueryList::postJson('http://foo.com',$data,[
  35. 'handler' => $mock
  36. ]);
  37. $this->assertEquals((string)$mock->getLastRequest()->getBody(),json_encode($data));
  38. }
  39. /**
  40. * @test
  41. */
  42. public function concurrent_requests_base_use()
  43. {
  44. $urls = $this->urls;
  45. QueryList::getInstance()
  46. ->multiGet($urls)
  47. ->success(function(QueryList $ql,Response $response, $index) use($urls){
  48. $body = json_decode((string)$response->getBody(),true);
  49. $this->assertEquals($urls[$index],$body['url']);
  50. })->send();
  51. }
  52. /**
  53. * @test
  54. */
  55. public function concurrent_requests_advanced_use()
  56. {
  57. $ua = 'QueryList/4.0';
  58. $errorUrl = 'http://web-site-not-exist.com';
  59. $urls = array_merge($this->urls,[$errorUrl]);
  60. QueryList::rules([])
  61. ->multiGet($urls)
  62. ->concurrency(2)
  63. ->withOptions([
  64. 'timeout' => 60
  65. ])
  66. ->withHeaders([
  67. 'User-Agent' => $ua
  68. ])
  69. ->success(function (QueryList $ql, Response $response, $index) use($ua){
  70. $body = json_decode((string)$response->getBody(),true);
  71. $this->assertEquals($ua,$body['headers']['User-Agent']);
  72. })
  73. ->error(function (QueryList $ql, $reason, $index) use($urls,$errorUrl){
  74. $this->assertEquals($urls[$index],$errorUrl);
  75. })
  76. ->send();
  77. }
  78. /**
  79. * @test
  80. */
  81. public function request_with_cache()
  82. {
  83. $url = $this->urls[0];
  84. $data = QueryList::get($url,null,[
  85. 'cache' => sys_get_temp_dir(),
  86. 'cache_ttl' => 600
  87. ])->getHtml();
  88. $data = json_decode($data,true);
  89. $this->assertEquals($url,$data['url']);
  90. }
  91. }