first commit

This commit is contained in:
2026-01-25 18:18:09 +08:00
commit 509312e604
8136 changed files with 2349298 additions and 0 deletions

View File

@ -0,0 +1,296 @@
<?php
// Hack to override the time returned from the S3SignatureV4
// @codingStandardsIgnoreStart
namespace Qiniu {
function time()
{
return isset($_SERVER['override_qiniu_auth_time'])
? 1234567890
: \time();
}
}
namespace Qiniu\Tests {
use PHPUnit\Framework\TestCase;
use Qiniu\Auth;
use Qiniu\Http\Header;
// @codingStandardsIgnoreEnd
class AuthTest extends TestCase
{
public function testSign()
{
global $dummyAuth;
$token = $dummyAuth->sign('test');
$this->assertEquals('abcdefghklmnopq:mSNBTR7uS2crJsyFr2Amwv1LaYg=', $token);
}
public function testSignWithData()
{
global $dummyAuth;
$token = $dummyAuth->signWithData('test');
$this->assertEquals('abcdefghklmnopq:-jP8eEV9v48MkYiBGs81aDxl60E=:dGVzdA==', $token);
}
public function testSignRequest()
{
global $dummyAuth;
$token = $dummyAuth->signRequest('http://www.qiniu.com?go=1', 'test', '');
$this->assertEquals('abcdefghklmnopq:cFyRVoWrE3IugPIMP5YJFTO-O-Y=', $token);
$ctype = 'application/x-www-form-urlencoded';
$token = $dummyAuth->signRequest('http://www.qiniu.com?go=1', 'test', $ctype);
$this->assertEquals($token, 'abcdefghklmnopq:svWRNcacOE-YMsc70nuIYdaa1e4=');
}
public function testPrivateDownloadUrl()
{
global $dummyAuth;
$_SERVER['override_qiniu_auth_time'] = true;
$url = $dummyAuth->privateDownloadUrl('http://www.qiniu.com?go=1');
$expect = 'http://www.qiniu.com?go=1&e=1234571490&token=abcdefghklmnopq:8vzBeLZ9W3E4kbBLFLW0Xe0u7v4=';
$this->assertEquals($expect, $url);
unset($_SERVER['override_qiniu_auth_time']);
}
public function testUploadToken()
{
global $dummyAuth;
$_SERVER['override_qiniu_auth_time'] = true;
$token = $dummyAuth->uploadToken('1', '2', 3600, array('endUser' => 'y'));
// @codingStandardsIgnoreStart
$exp = 'abcdefghklmnopq:yyeexeUkPOROoTGvwBjJ0F0VLEo=:eyJlbmRVc2VyIjoieSIsInNjb3BlIjoiMToyIiwiZGVhZGxpbmUiOjEyMzQ1NzE0OTB9';
// @codingStandardsIgnoreEnd
$this->assertEquals($exp, $token);
unset($_SERVER['override_qiniu_auth_time']);
}
public function testSignQiniuAuthorization()
{
$auth = new Auth("ak", "sk");
$testCases = array(
array(
"url" => "",
"method" => "",
"headers" => array(
"X-Qiniu-" => array("a"),
"X-Qiniu" => array("b"),
"Content-Type" => array("application/x-www-form-urlencoded")
),
"body" => "{\"name\": \"test\"}",
"expectedToken" => "ak:0i1vKClRDWFyNkcTFzwcE7PzX74="
),
array(
"url" => "",
"method" => "",
"headers" => array(
"Content-Type" => array("application/json")
),
"body" => "{\"name\": \"test\"}",
"expectedToken" => "ak:K1DI0goT05yhGizDFE5FiPJxAj4="
),
array(
"url" => "",
"method" => "GET",
"headers" => array(
"X-Qiniu-" => array("a"),
"X-Qiniu" => array("b"),
"Content-Type" => array("application/x-www-form-urlencoded"),
),
"body" => "{\"name\": \"test\"}",
"expectedToken" => "ak:0i1vKClRDWFyNkcTFzwcE7PzX74="
),
array(
"url" => "",
"method" => "POST",
"headers" => array(
"Content-Type" => array("application/json"),
"X-Qiniu" => array("b"),
),
"body" => "{\"name\": \"test\"}",
"expectedToken" => "ak:0ujEjW_vLRZxebsveBgqa3JyQ-w="
),
array(
"url" => "http://upload.qiniup.com",
"method" => "",
"headers" => array(
"X-Qiniu-" => array("a"),
"X-Qiniu" => array("b"),
"Content-Type" => array("application/x-www-form-urlencoded"),
),
"body" => "{\"name\": \"test\"}",
"expectedToken" => "ak:GShw5NitGmd5TLoo38nDkGUofRw="
),
array(
"url" => "http://upload.qiniup.com",
"method" => "",
"headers" => array(
"Content-Type" => array("application/json"),
"X-Qiniu-Bbb" => array("BBB", "AAA"),
"X-Qiniu-Aaa" => array("DDD", "CCC"),
"X-Qiniu-" => array("a"),
"X-Qiniu" => array("b"),
),
"body" => "{\"name\": \"test\"}",
"expectedToken" => "ak:DhNA1UCaBqSHCsQjMOLRfVn63GQ="
),
array(
"url" => "http://upload.qiniup.com",
"method" => "",
"headers" => array(
"Content-Type" => array("application/x-www-form-urlencoded"),
"X-Qiniu-Bbb" => array("BBB", "AAA"),
"X-Qiniu-Aaa" => array("DDD", "CCC"),
"X-Qiniu-" => array("a"),
"X-Qiniu" => array("b"),
),
"body" => "name=test&language=go",
"expectedToken" => "ak:KUAhrYh32P9bv0COD8ugZjDCmII="
),
array(
"url" => "http://upload.qiniup.com",
"method" => "",
"headers" => array(
"Content-Type" => array("application/x-www"),
"Content-Type" => array("application/x-www-form-urlencoded"),
"X-Qiniu-Bbb" => array("BBB", "AAA"),
"X-Qiniu-Aaa" => array("DDD", "CCC"),
),
"body" => "name=test&language=go",
"expectedToken" => "ak:KUAhrYh32P9bv0COD8ugZjDCmII="
),
array(
"url" => "http://upload.qiniup.com/mkfile/sdf.jpg",
"method" => "",
"headers" => array(
"Content-Type" => array("application/x-www-form-urlencoded"),
"X-Qiniu-Bbb" => array("BBB", "AAA"),
"X-Qiniu-Aaa" => array("DDD", "CCC"),
"X-Qiniu-" => array("a"),
"X-Qiniu" => array("b"),
),
"body" => "name=test&language=go",
"expectedToken" => "ak:fkRck5_LeyfwdkyyLk-hyNwGKac="
),
array(
"url" => "http://upload.qiniup.com/mkfile/sdf.jpg?s=er3&df",
"method" => "",
"headers" => array(
"Content-Type" => array("application/x-www-form-urlencoded"),
"X-Qiniu-Bbb" => array("BBB", "AAA"),
"X-Qiniu-Aaa" => array("DDD", "CCC"),
"X-Qiniu-" => array("a"),
"X-Qiniu" => array("b"),
),
"body" => "name=test&language=go",
"expectedToken" => "ak:PUFPWsEUIpk_dzUvvxTTmwhp3p4="
)
);
foreach ($testCases as $testCase) {
list($sign, $err) = $auth->signQiniuAuthorization(
$testCase["url"],
$testCase["method"],
$testCase["body"],
new Header($testCase["headers"])
);
$this->assertNull($err);
$this->assertEquals($testCase["expectedToken"], $sign);
}
}
public function testDisableQiniuTimestampSignatureDefault()
{
$auth = new Auth("ak", "sk");
$authedHeaders = $auth->authorizationV2("https://example.com", "GET");
$this->assertArrayHasKey("X-Qiniu-Date", $authedHeaders);
}
public function testDisableQiniuTimestampSignature()
{
$auth = new Auth("ak", "sk", array(
"disableQiniuTimestampSignature" => true
));
$authedHeaders = $auth->authorizationV2("https://example.com", "GET");
$this->assertArrayNotHasKey("X-Qiniu-Date", $authedHeaders);
}
public function testDisableQiniuTimestampSignatureEnv()
{
putenv("DISABLE_QINIU_TIMESTAMP_SIGNATURE=true");
$auth = new Auth("ak", "sk");
$authedHeaders = $auth->authorizationV2("https://example.com", "GET");
$this->assertArrayNotHasKey("X-Qiniu-Date", $authedHeaders);
putenv('DISABLE_QINIU_TIMESTAMP_SIGNATURE');
}
public function testDisableQiniuTimestampSignatureEnvBeIgnored()
{
putenv("DISABLE_QINIU_TIMESTAMP_SIGNATURE=true");
$auth = new Auth("ak", "sk", array(
"disableQiniuTimestampSignature" => false
));
$authedHeaders = $auth->authorizationV2("https://example.com", "GET");
$this->assertArrayHasKey("X-Qiniu-Date", $authedHeaders);
putenv('DISABLE_QINIU_TIMESTAMP_SIGNATURE');
}
public function testQboxVerifyCallbackShouldOkWithRequiredOptions()
{
$auth = new Auth('abcdefghklmnopq', '1234567890');
$ok = $auth->verifyCallback(
'application/x-www-form-urlencoded',
'QBox abcdefghklmnopq:T7F-SjxX7X2zI4Fc1vANiNt1AUE=',
'https://test.qiniu.com/callback',
'name=sunflower.jpg&hash=Fn6qeQi4VDLQ347NiRm-RlQx_4O2&location=Shanghai&price=1500.00&uid=123'
);
$this->assertTrue($ok);
}
public function testQboxVerifyCallbackShouldOkWithOmitOptions()
{
$auth = new Auth('abcdefghklmnopq', '1234567890');
$ok = $auth->verifyCallback(
'application/x-www-form-urlencoded',
'QBox abcdefghklmnopq:T7F-SjxX7X2zI4Fc1vANiNt1AUE=',
'https://test.qiniu.com/callback',
'name=sunflower.jpg&hash=Fn6qeQi4VDLQ347NiRm-RlQx_4O2&location=Shanghai&price=1500.00&uid=123',
'POST', // this should be omit
array(
'X-Qiniu-Bbb' => 'BBB'
) // this should be omit
);
$this->assertTrue($ok);
}
public function testQiniuVerifyCallbackShouldOk()
{
$auth = new Auth('abcdefghklmnopq', '1234567890');
$ok = $auth->verifyCallback(
'application/x-www-form-urlencoded',
'Qiniu abcdefghklmnopq:ZqS7EZuAKrhZaEIxqNGxDJi41IQ=',
'https://test.qiniu.com/callback',
'name=sunflower.jpg&hash=Fn6qeQi4VDLQ347NiRm-RlQx_4O2&location=Shanghai&price=1500.00&uid=123',
'GET',
array(
'X-Qiniu-Bbb' => 'BBB'
)
);
$this->assertTrue($ok);
}
public function testQiniuVerifyCallbackShouldFailed()
{
$auth = new Auth('abcdefghklmnopq', '1234567890');
$ok = $auth->verifyCallback(
'application/x-www-form-urlencoded',
'Qiniu abcdefghklmnopq:ZqS7EZuAKrhZaEIxqNGxDJi41IQ=',
'https://test.qiniu.com/callback',
'name=sunflower.jpg&hash=Fn6qeQi4VDLQ347NiRm-RlQx_4O2&location=Shanghai&price=1500.00&uid=123',
'POST',
array(
'X-Qiniu-Bbb' => 'BBB'
)
);
$this->assertFalse($ok);
}
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu;
class Base64Test extends TestCase
{
public function testUrlSafe()
{
$a = '你好';
$b = \Qiniu\base64_urlSafeEncode($a);
$this->assertEquals($a, \Qiniu\base64_urlSafeDecode($b));
}
}

View File

@ -0,0 +1,733 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
class BucketTest extends TestCase
{
/**
* @var BucketManager
*/
private static $bucketManager;
private static $dummyBucketManager;
private static $bucketName;
private static $key;
private static $key2;
private static $customCallbackURL;
private static $bucketToCreate;
private static $bucketLifeRuleName;
private static $bucketLifeRulePrefix;
private static $bucketEventName;
private static $bucketEventPrefix;
private static $keysToCleanup;
/**
* @beforeClass
*/
public static function prepareEnvironment()
{
global $bucketName;
global $key;
global $key2;
self::$bucketName = $bucketName;
self::$key = $key;
self::$key2 = $key2;
global $customCallbackURL;
self::$customCallbackURL = $customCallbackURL;
global $testAuth;
$config = new Config();
self::$bucketManager = new BucketManager($testAuth, $config);
global $dummyAuth;
self::$dummyBucketManager = new BucketManager($dummyAuth);
self::$bucketToCreate = 'phpsdk-ci-test' . rand(1, 1000);
self::$bucketLifeRuleName = 'bucket_life_rule' . rand(1, 1000);
self::$bucketLifeRulePrefix = 'prefix-test' . rand(1, 1000);
self::$bucketEventName = 'bucketevent' . rand(1, 1000);
self::$bucketEventPrefix = 'event-test' . rand(1, 1000);
self::$keysToCleanup = array();
}
/**
* @afterClass
*/
public static function cleanupTestData()
{
$ops = BucketManager::buildBatchDelete(self::$bucketName, self::$keysToCleanup);
// ignore result for cleanup
self::$bucketManager->batch($ops);
}
private static function getObjectKey($key)
{
$result = $key . rand();
self::$bucketManager->copy(
self::$bucketName,
$key,
self::$bucketName,
$result
);
self::$keysToCleanup[] = $result;
return $result;
}
public function testBuckets()
{
list($list, $error) = self::$bucketManager->buckets();
$this->assertNull($error);
$this->assertTrue(in_array(self::$bucketName, $list));
list($list2, $error) = self::$dummyBucketManager->buckets();
$this->assertEquals(401, $error->code());
$this->assertNotNull($error->message());
$this->assertNotNull($error->getResponse());
$this->assertNull($list2);
}
public function testListBuckets()
{
list($ret, $error) = self::$bucketManager->listbuckets('z0');
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testCreateBucket()
{
list($ret, $error) = self::$bucketManager->createBucket(self::$bucketToCreate);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testDeleteBucket()
{
list($ret, $error) = self::$bucketManager->deleteBucket(self::$bucketToCreate);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testDomains()
{
list($ret, $error) = self::$bucketManager->domains(self::$bucketName);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testBucketInfo()
{
list($ret, $error) = self::$bucketManager->bucketInfo(self::$bucketName);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testBucketInfos()
{
list($ret, $error) = self::$bucketManager->bucketInfos('z0');
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testList()
{
list($ret, $error) = self::$bucketManager->listFiles(self::$bucketName, null, null, 10);
$this->assertNull($error);
$this->assertNotNull($ret['items'][0]);
$this->assertNotNull($ret['marker']);
}
public function testListFilesv2()
{
list($ret, $error) = self::$bucketManager->listFilesv2(self::$bucketName, null, null, 10);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testBucketLifecycleRule()
{
// delete
self::$bucketManager->deleteBucketLifecycleRule(self::$bucketName, self::$bucketLifeRuleName);
// add
list($ret, $error) = self::$bucketManager->bucketLifecycleRule(
self::$bucketName,
self::$bucketLifeRuleName,
self::$bucketLifeRulePrefix,
80,
70,
72,
74,
71
);
$this->assertNull($error);
$this->assertNotNull($ret);
// get
list($ret, $error) = self::$bucketManager->getBucketLifecycleRules(self::$bucketName);
$this->assertNull($error);
$this->assertNotNull($ret);
$rule = null;
foreach ($ret as $r) {
if ($r["name"] === self::$bucketLifeRuleName) {
$rule = $r;
break;
}
}
$this->assertNotNull($rule);
$this->assertEquals(self::$bucketLifeRulePrefix, $rule["prefix"]);
$this->assertEquals(80, $rule["delete_after_days"]);
$this->assertEquals(70, $rule["to_line_after_days"]);
$this->assertEquals(71, $rule["to_archive_ir_after_days"]);
$this->assertEquals(72, $rule["to_archive_after_days"]);
$this->assertEquals(74, $rule["to_deep_archive_after_days"]);
// update
list($ret, $error) = self::$bucketManager->updateBucketLifecycleRule(
self::$bucketName,
self::$bucketLifeRuleName,
'update-' . self::$bucketLifeRulePrefix,
90,
75,
80,
85,
78
);
$this->assertNull($error);
$this->assertNotNull($ret);
// get
list($ret, $error) = self::$bucketManager->getBucketLifecycleRules(self::$bucketName);
$this->assertNull($error);
$this->assertNotNull($ret);
$rule = null;
foreach ($ret as $r) {
if ($r["name"] === self::$bucketLifeRuleName) {
$rule = $r;
break;
}
}
$this->assertNotNull($rule);
$this->assertEquals('update-' . self::$bucketLifeRulePrefix, $rule["prefix"]);
$this->assertEquals(90, $rule["delete_after_days"]);
$this->assertEquals(75, $rule["to_line_after_days"]);
$this->assertEquals(78, $rule["to_archive_ir_after_days"]);
$this->assertEquals(80, $rule["to_archive_after_days"]);
$this->assertEquals(85, $rule["to_deep_archive_after_days"]);
// delete
list($ret, $error) = self::$bucketManager->deleteBucketLifecycleRule(
self::$bucketName,
self::$bucketLifeRuleName
);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testPutBucketEvent()
{
list($ret, $error) = self::$bucketManager->putBucketEvent(
self::$bucketName,
self::$bucketEventName,
self::$bucketEventPrefix,
'img',
array('copy'),
self::$customCallbackURL
);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testUpdateBucketEvent()
{
list($ret, $error) = self::$bucketManager->updateBucketEvent(
self::$bucketName,
self::$bucketEventName,
self::$bucketEventPrefix,
'video',
array('copy'),
self::$customCallbackURL
);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testGetBucketEvents()
{
list($ret, $error) = self::$bucketManager->getBucketEvents(self::$bucketName);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testDeleteBucketEvent()
{
list($ret, $error) = self::$bucketManager->deleteBucketEvent(self::$bucketName, self::$bucketEventName);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testStat()
{
list($stat, $error) = self::$bucketManager->stat(self::$bucketName, self::$key);
$this->assertNull($error);
$this->assertNotNull($stat);
$this->assertNotNull($stat['hash']);
list($stat, $error) = self::$bucketManager->stat(self::$bucketName, 'nofile');
$this->assertEquals(612, $error->code());
$this->assertNotNull($error->message());
$this->assertNull($stat);
list($stat, $error) = self::$bucketManager->stat('nobucket', 'nofile');
$this->assertEquals(631, $error->code());
$this->assertNotNull($error->message());
$this->assertNull($stat);
}
public function testDelete()
{
$fileToDel = self::getObjectKey(self::$key);
list(, $error) = self::$bucketManager->delete(self::$bucketName, $fileToDel);
$this->assertNull($error);
}
public function testRename()
{
$fileToRename = self::getObjectKey(self::$key);
$fileRenamed = $fileToRename . 'new';
list(, $error) = self::$bucketManager->rename(self::$bucketName, $fileToRename, $fileRenamed);
$this->assertNull($error);
self::$keysToCleanup[] = $fileRenamed;
}
public function testCopy()
{
$fileToCopy = self::getObjectKey(self::$key2);
$fileCopied = $fileToCopy . 'copied';
//test force copy
list(, $error) = self::$bucketManager->copy(
self::$bucketName,
$fileToCopy,
self::$bucketName,
$fileCopied,
true
);
$this->assertNull($error);
list($fileToCopyStat,) = self::$bucketManager->stat(self::$bucketName, $fileToCopy);
list($fileCopiedStat,) = self::$bucketManager->stat(self::$bucketName, $fileCopied);
$this->assertEquals($fileToCopyStat['hash'], $fileCopiedStat['hash']);
self::$keysToCleanup[] = $fileCopied;
}
public function testChangeMime()
{
$fileToChange = self::getObjectKey('php-sdk.html');
list(, $error) = self::$bucketManager->changeMime(
self::$bucketName,
$fileToChange,
'text/plain'
);
$this->assertNull($error);
list($ret, $error) = self::$bucketManager->stat(
self::$bucketName,
$fileToChange
);
$this->assertNull($error);
$this->assertEquals('text/plain', $ret['mimeType']);
}
public function testPrefetch()
{
list($ret, $error) = self::$bucketManager->prefetch(
self::$bucketName,
'php-sdk.html'
);
$this->assertNull($error);
$this->assertNotNull($ret);
}
public function testPrefetchFailed()
{
list($ret, $error) = self::$bucketManager->prefetch(
'fakebucket',
'php-sdk.html'
);
$this->assertNotNull($error);
$this->assertNull($ret);
}
public function testFetch()
{
list($ret, $error) = self::$bucketManager->fetch(
'http://developer.qiniu.com/docs/v6/sdk/php-sdk.html',
self::$bucketName,
'fetch.html'
);
$this->assertNull($error);
$this->assertArrayHasKey('hash', $ret);
list($ret, $error) = self::$bucketManager->fetch(
'http://developer.qiniu.com/docs/v6/sdk/php-sdk.html',
self::$bucketName,
''
);
$this->assertNull($error);
$this->assertArrayHasKey('key', $ret);
list($ret, $error) = self::$bucketManager->fetch(
'http://developer.qiniu.com/docs/v6/sdk/php-sdk.html',
self::$bucketName
);
$this->assertNull($error);
$this->assertArrayHasKey('key', $ret);
}
public function testFetchFailed()
{
list($ret, $error) = self::$bucketManager->fetch(
'http://developer.qiniu.com/docs/v6/sdk/php-sdk.html',
'fakebucket'
);
$this->assertNotNull($error);
$this->assertNull($ret);
}
public function testAsynchFetch()
{
list($ret, $error) = self::$bucketManager->asynchFetch(
'http://devtools.qiniu.com/qiniu.png',
self::$bucketName,
null,
'qiniu.png'
);
$this->assertNull($error);
$this->assertArrayHasKey('id', $ret);
list($ret, $error) = self::$bucketManager->asynchFetch(
'http://devtools.qiniu.com/qiniu.png',
self::$bucketName,
null,
''
);
$this->assertNull($error);
$this->assertArrayHasKey('id', $ret);
list($ret, $error) = self::$bucketManager->asynchFetch(
'http://devtools.qiniu.com/qiniu.png',
self::$bucketName
);
$this->assertNull($error);
$this->assertArrayHasKey('id', $ret);
}
public function testAsynchFetchFailed()
{
list($ret, $error) = self::$bucketManager->asynchFetch(
'http://devtools.qiniu.com/qiniu.png',
'fakebucket'
);
$this->assertNotNull($error);
$this->assertNull($ret);
}
public function testBatchCopy()
{
$key = 'copyto' . rand();
$ops = BucketManager::buildBatchCopy(
self::$bucketName,
array(self::$key => $key),
self::$bucketName,
true
);
list($ret, $error) = self::$bucketManager->batch($ops);
$this->assertNull($error);
$this->assertEquals(200, $ret[0]['code']);
self::$keysToCleanup[] = $key;
}
public function testBatchMove()
{
$fileToMove = self::getObjectKey(self::$key);
$fileMoved = $fileToMove . 'to';
$ops = BucketManager::buildBatchMove(
self::$bucketName,
array($fileToMove => $fileMoved),
self::$bucketName,
true
);
list($ret, $error) = self::$bucketManager->batch($ops);
$this->assertNull($error);
$this->assertEquals(200, $ret[0]['code']);
self::$keysToCleanup[] = $fileMoved;
}
public function testBatchRename()
{
$fileToRename = self::getObjectKey(self::$key);
$fileRenamed = $fileToRename . 'to';
$ops = BucketManager::buildBatchRename(
self::$bucketName,
array($fileToRename => $fileRenamed),
true
);
list($ret, $error) = self::$bucketManager->batch($ops);
$this->assertNull($error);
$this->assertEquals(200, $ret[0]['code']);
self::$keysToCleanup[] = $fileRenamed;
}
public function testBatchStat()
{
$ops = BucketManager::buildBatchStat(self::$bucketName, array('php-sdk.html'));
list($ret, $error) = self::$bucketManager->batch($ops);
$this->assertNull($error);
$this->assertEquals(200, $ret[0]['code']);
}
public function testBatchChangeTypeAndBatchRestoreAr()
{
$key = self::getObjectKey(self::$key);
$ops = BucketManager::buildBatchChangeType(self::$bucketName, array($key => 2)); // 2 Archive
list($ret, $error) = self::$bucketManager->batch($ops);
$this->assertNull($error);
$this->assertEquals(200, $ret[0]['code']);
$ops = BucketManager::buildBatchRestoreAr(self::$bucketName, array($key => 1)); // 1 day
list($ret, $error) = self::$bucketManager->batch($ops);
$this->assertNull($error);
$this->assertEquals(200, $ret[0]['code']);
}
public function testDeleteAfterDays()
{
$key = "noexist" . rand();
list($ret, $error) = self::$bucketManager->deleteAfterDays(self::$bucketName, $key, 1);
$this->assertNotNull($error);
$this->assertNull($ret);
$key = self::getObjectKey(self::$key);
list(, $error) = self::$bucketManager->deleteAfterDays(self::$bucketName, $key, 1);
$this->assertNull($error);
list($ret, $error) = self::$bucketManager->stat(self::$bucketName, $key);
$this->assertNull($error);
$this->assertGreaterThan(23 * 3600, $ret['expiration'] - time());
$this->assertLessThan(48 * 3600, $ret['expiration'] - time());
}
public function testSetObjectLifecycle()
{
$key = self::getObjectKey(self::$key);
list(, $err) = self::$bucketManager->setObjectLifecycle(
self::$bucketName,
$key,
10,
20,
30,
40,
15
);
$this->assertNull($err);
list($ret, $error) = self::$bucketManager->stat(self::$bucketName, $key);
$this->assertNull($error);
$this->assertNotNull($ret['transitionToIA']);
$this->assertNotNull($ret['transitionToArchiveIR']);
$this->assertNotNull($ret['transitionToARCHIVE']);
$this->assertNotNull($ret['transitionToDeepArchive']);
$this->assertNotNull($ret['expiration']);
}
public function testSetObjectLifecycleWithCond()
{
$key = self::getObjectKey(self::$key);
list($ret, $err) = self::$bucketManager->stat(self::$bucketName, $key);
$this->assertNull($err);
$key_hash = $ret['hash'];
$key_fsize = $ret['fsize'];
list(, $err) = self::$bucketManager->setObjectLifecycleWithCond(
self::$bucketName,
$key,
array(
'hash' => $key_hash,
'fsize' => $key_fsize
),
10,
20,
30,
40,
15
);
$this->assertNull($err);
list($ret, $error) = self::$bucketManager->stat(self::$bucketName, $key);
$this->assertNull($error);
$this->assertNotNull($ret['transitionToIA']);
$this->assertNotNull($ret['transitionToArchiveIR']);
$this->assertNotNull($ret['transitionToARCHIVE']);
$this->assertNotNull($ret['transitionToDeepArchive']);
$this->assertNotNull($ret['expiration']);
}
public function testBatchSetObjectLifecycle()
{
$key = self::getObjectKey(self::$key);
$ops = BucketManager::buildBatchSetObjectLifecycle(
self::$bucketName,
array($key),
10,
20,
30,
40,
15
);
list($ret, $err) = self::$bucketManager->batch($ops);
$this->assertNull($err);
$this->assertEquals(200, $ret[0]['code']);
}
public function testGetCorsRules()
{
list(, $err) = self::$bucketManager->getCorsRules(self::$bucketName);
$this->assertNull($err);
}
public function testPutBucketAccessStyleMode()
{
list(, $err) = self::$bucketManager->putBucketAccessStyleMode(self::$bucketName, 0);
$this->assertNull($err);
}
public function testPutBucketAccessMode()
{
list(, $err) = self::$bucketManager->putBucketAccessMode(self::$bucketName, 0);
$this->assertNull($err);
}
public function testPutReferAntiLeech()
{
list(, $err) = self::$bucketManager->putReferAntiLeech(self::$bucketName, 0, "1", "*");
$this->assertNull($err);
}
public function testPutBucketMaxAge()
{
list(, $err) = self::$bucketManager->putBucketMaxAge(self::$bucketName, 31536000);
$this->assertNull($err);
}
public function testPutBucketQuota()
{
list(, $err) = self::$bucketManager->putBucketQuota(self::$bucketName, -1, -1);
$this->assertNull($err);
}
public function testGetBucketQuota()
{
list(, $err) = self::$bucketManager->getBucketQuota(self::$bucketName);
$this->assertNull($err);
}
public function testChangeType()
{
$fileToChange = self::getObjectKey(self::$key);
list(, $err) = self::$bucketManager->changeType(self::$bucketName, $fileToChange, 0);
$this->assertNull($err);
list(, $err) = self::$bucketManager->changeType(self::$bucketName, $fileToChange, 1);
$this->assertNull($err);
}
public function testArchiveRestoreAr()
{
$key = self::getObjectKey(self::$key);
self::$bucketManager->changeType(self::$bucketName, $key, 2);
list(, $err) = self::$bucketManager->restoreAr(self::$bucketName, $key, 2);
$this->assertNull($err);
list($ret, $err) = self::$bucketManager->stat(self::$bucketName, $key);
$this->assertNull($err);
$this->assertEquals(2, $ret["type"]);
// restoreStatus
// null means frozen;
// 1 means be unfreezing;
// 2 means be unfrozen;
$this->assertNotNull($ret["restoreStatus"]);
$this->assertContains($ret["restoreStatus"], array(1, 2));
}
public function testDeepArchiveRestoreAr()
{
$key = self::getObjectKey(self::$key);
self::$bucketManager->changeType(self::$bucketName, $key, 3);
list(, $err) = self::$bucketManager->restoreAr(self::$bucketName, $key, 1);
$this->assertNull($err);
list($ret, $err) = self::$bucketManager->stat(self::$bucketName, $key);
$this->assertNull($err);
$this->assertEquals(3, $ret["type"]);
// restoreStatus
// null means frozen;
// 1 means be unfreezing;
// 2 means be unfrozen;
$this->assertNotNull($ret["restoreStatus"]);
$this->assertContains($ret["restoreStatus"], array(1, 2));
}
public function testChangeStatus()
{
$key = self::getObjectKey(self::$key);
list(, $err) = self::$bucketManager->changeStatus(self::$bucketName, $key, 1);
$this->assertNull($err);
list($ret, $err) = self::$bucketManager->stat(self::$bucketName, $key);
$this->assertNull($err);
$this->assertEquals(1, $ret['status']);
list(, $err) = self::$bucketManager->changeStatus(self::$bucketName, $key, 0);
$this->assertNull($err);
list($ret, $err) = self::$bucketManager->stat(self::$bucketName, $key);
$this->assertNull($err);
$this->assertArrayNotHasKey('status', $ret);
}
}

View File

@ -0,0 +1,151 @@
<?php
/**
* Created by IntelliJ IDEA.
* User: wf
* Date: 2017/6/21
* Time: AM8:46
*/
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Cdn\CdnManager;
use Qiniu\Http\Client;
class CdnManagerTest extends TestCase
{
protected $cdnManager;
protected $encryptKey;
protected $testStartDate;
protected $testEndDate;
protected $testGranularity;
protected $testLogDate;
protected $refreshUrl;
protected $refreshDirs;
protected $customDomain;
protected $customDomain2;
/**
* @before
*/
protected function setUpCdnManager()
{
global $testAuth;
$this->cdnManager = new CdnManager($testAuth);
global $timestampAntiLeechEncryptKey;
$this->encryptKey = $timestampAntiLeechEncryptKey;
global $testStartDate;
$this->testStartDate = $testStartDate;
global $testEndDate;
$this->testEndDate = $testEndDate;
global $testGranularity;
$this->testGranularity = $testGranularity;
global $testLogDate;
$this->testLogDate = $testLogDate;
global $customDomain;
$this->refreshUrl = $customDomain . '/sdktest.png';
$this->refreshDirs = $customDomain;
$this->customDomain = $customDomain;
global $customDomain2;
$this->customDomain2 = $customDomain2;
}
public function testRefreshUrls()
{
list($ret, $err) = $this->cdnManager->refreshUrls(array($this->refreshUrl));
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testRefreshDirs()
{
list($ret, $err) = $this->cdnManager->refreshDirs(array($this->refreshDirs));
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testRefreshUrlsAndDirs()
{
list($ret, $err) = $this->cdnManager->refreshUrlsAndDirs(array($this->refreshUrl), array($this->refreshDirs));
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testGetCdnRefreshList()
{
list($ret, $err) = $this->cdnManager->getCdnRefreshList(null, null, null, 'success');
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testPrefetchUrls()
{
list($ret, $err) = $this->cdnManager->prefetchUrls(array($this->refreshUrl));
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testGetCdnPrefetchList()
{
list($ret, $err) = $this->cdnManager->getCdnPrefetchList(null, null, 'success');
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testGetBandwidthData()
{
list($ret, $err) = $this->cdnManager->getBandwidthData(
array($this->customDomain2),
$this->testStartDate,
$this->testEndDate,
$this->testGranularity
);
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testGetFluxData()
{
list($ret, $err) = $this->cdnManager->getFluxData(
array($this->customDomain2),
$this->testStartDate,
$this->testEndDate,
$this->testGranularity
);
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testGetCdnLogList()
{
$domain = getenv('QINIU_TEST_DOMAIN');
list($ret, $err) = $this->cdnManager->getCdnLogList(array($domain), $this->testLogDate);
$this->assertNull($err);
$this->assertNotNull($ret);
}
public function testCreateTimestampAntiLeechUrl()
{
$signUrl = $this->cdnManager->createTimestampAntiLeechUrl($this->refreshUrl, $this->encryptKey, 3600);
$response = Client::get($signUrl);
$this->assertNull($response->error);
$this->assertEquals($response->statusCode, 200);
$signUrl = $this->cdnManager->createTimestampAntiLeechUrl(
$this->refreshUrl . '?qiniu',
$this->encryptKey,
3600
);
$response = Client::get($signUrl);
$this->assertNull($response->error);
$this->assertEquals($response->statusCode, 200);
}
}

View File

@ -0,0 +1,118 @@
<?php
namespace Qiniu\Tests {
use PHPUnit\Framework\TestCase;
use Qiniu\Config;
class ConfigTest extends TestCase
{
protected $accessKey;
protected $bucketName;
/**
* @before
*/
protected function setUpAkAndBucket()
{
global $accessKey;
$this->accessKey = $accessKey;
global $bucketName;
$this->bucketName = $bucketName;
}
public function testGetApiHost()
{
$conf = new Config();
$hasException = false;
$apiHost = '';
try {
$apiHost = $conf->getApiHost($this->accessKey, $this->bucketName);
} catch (\Exception $e) {
$hasException = true;
}
$this->assertFalse($hasException);
}
public function testGetApiHostErrored()
{
$conf = new Config();
$hasException = false;
try {
$conf->getApiHost($this->accessKey, "fakebucket");
} catch (\Exception $e) {
$hasException = true;
}
$this->assertTrue($hasException);
}
public function testGetApiHostV2()
{
$conf = new Config();
list($apiHost, $err) = $conf->getApiHostV2($this->accessKey, $this->bucketName);
$this->assertNull($err);
}
public function testGetApiHostV2Errored()
{
$conf = new Config();
list($apiHost, $err) = $conf->getApiHostV2($this->accessKey, "fakebucket");
$this->assertNotNull($err->code());
$this->assertEquals(631, $err->code());
$this->assertNull($apiHost);
}
public function testSetUcHost()
{
$conf = new Config();
$this->assertEquals('http://' . Config::UC_HOST, $conf->getUcHost());
$conf->setUcHost("uc.example.com");
$this->assertEquals("http://uc.example.com", $conf->getUcHost());
$conf = new Config();
$conf->useHTTPS = true;
$this->assertEquals('https://' . Config::UC_HOST, $conf->getUcHost());
$conf->setUcHost("uc.example.com");
$this->assertEquals("https://uc.example.com", $conf->getUcHost());
}
public function testGetRegionWithCustomDomain()
{
$conf = new Config();
$conf->setQueryRegionHost(
"uc.qbox.me"
);
list(, $err) = $conf->getRsHostV2($this->accessKey, $this->bucketName);
$this->assertNull($err);
}
public function testGetRegionWithBackupDomains()
{
$conf = new Config();
$conf->setQueryRegionHost(
"fake-uc.phpsdk.qiniu.com",
array(
"unavailable-uc.phpsdk.qiniu.com",
Config::UC_HOST // real uc
)
);
list(, $err) = $conf->getRsHostV2($this->accessKey, $this->bucketName);
$this->assertNull($err);
}
public function testGetRegionWithUcAndBackupDomains()
{
$conf = new Config();
$conf->setUcHost("fake-uc.phpsdk.qiniu.com");
$conf->setBackupQueryRegionHosts(
array(
"unavailable-uc.phpsdk.qiniu.com",
Config::UC_HOST // real uc
)
);
list(, $err) = $conf->getRsHostV2($this->accessKey, $this->bucketName);
$this->assertNull($err);
}
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu;
class Crc32Test extends TestCase
{
public function testData()
{
$a = '你好';
$b = \Qiniu\crc32_data($a);
$this->assertEquals('1352841281', $b);
}
public function testFile()
{
$b = \Qiniu\crc32_file(__file__);
$c = \Qiniu\crc32_file(__file__);
$this->assertEquals($c, $b);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Http\Client;
class DownloadTest extends TestCase
{
public function test()
{
global $testAuth;
$base_url = 'http://sdk.peterpy.cn/gogopher.jpg';
$private_url = $testAuth->privateDownloadUrl($base_url);
$response = Client::get($private_url);
$this->assertEquals(200, $response->statusCode);
}
public function testFop()
{
global $testAuth;
$base_url = 'http://sdk.peterpy.cn/gogopher.jpg?exif';
$private_url = $testAuth->privateDownloadUrl($base_url);
$response = Client::get($private_url);
$this->assertEquals(200, $response->statusCode);
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu;
class EntryTest extends TestCase
{
public function testNormal()
{
$bucket = 'qiniuphotos';
$key = 'gogopher.jpg';
$encodeEntryURI = Qiniu\entry($bucket, $key);
$this->assertEquals('cWluaXVwaG90b3M6Z29nb3BoZXIuanBn', $encodeEntryURI);
}
public function testKeyEmpty()
{
$bucket = 'qiniuphotos';
$key = '';
$encodeEntryURI = Qiniu\entry($bucket, $key);
$this->assertEquals('cWluaXVwaG90b3M6', $encodeEntryURI);
}
public function testKeyNull()
{
$bucket = 'qiniuphotos';
$key = null;
$encodeEntryURI = Qiniu\entry($bucket, $key);
$this->assertEquals('cWluaXVwaG90b3M=', $encodeEntryURI);
}
public function testKeyNeedReplacePlusSymbol()
{
$bucket = 'qiniuphotos';
$key = '012ts>a';
$encodeEntryURI = Qiniu\entry($bucket, $key);
$this->assertEquals('cWluaXVwaG90b3M6MDEydHM-YQ==', $encodeEntryURI);
}
public function testKeyNeedReplaceSlashSymbol()
{
$bucket = 'qiniuphotos';
$key = '012ts?a';
$encodeEntryURI = Qiniu\entry($bucket, $key);
$this->assertEquals('cWluaXVwaG90b3M6MDEydHM_YQ==', $encodeEntryURI);
}
public function testDecodeEntry()
{
$entry = 'cWluaXVwaG90b3M6Z29nb3BoZXIuanBn';
list($bucket, $key) = Qiniu\decodeEntry($entry);
$this->assertEquals('qiniuphotos', $bucket);
$this->assertEquals('gogopher.jpg', $key);
}
public function testDecodeEntryWithEmptyKey()
{
$entry = 'cWluaXVwaG90b3M6';
list($bucket, $key) = Qiniu\decodeEntry($entry);
$this->assertEquals('qiniuphotos', $bucket);
$this->assertEquals('', $key);
}
public function testDecodeEntryWithNullKey()
{
$entry = 'cWluaXVwaG90b3M=';
list($bucket, $key) = Qiniu\decodeEntry($entry);
$this->assertEquals('qiniuphotos', $bucket);
$this->assertNull($key);
}
public function testDecodeEntryWithPlusSymbol()
{
$entry = 'cWluaXVwaG90b3M6MDEydHM-YQ==';
list($bucket, $key) = Qiniu\decodeEntry($entry);
$this->assertEquals('qiniuphotos', $bucket);
$this->assertEquals('012ts>a', $key);
}
public function testDecodeEntryWithSlashSymbol()
{
$entry = 'cWluaXVwaG90b3M6MDEydHM_YQ==';
list($bucket, $key) = Qiniu\decodeEntry($entry);
$this->assertEquals('qiniuphotos', $bucket);
$this->assertEquals('012ts?a', $key);
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Etag;
class EtagTest extends TestCase
{
public function test0M()
{
$file = qiniuTempFile(0, false);
list($r, $error) = Etag::sum($file);
unlink($file);
$this->assertEquals('Fto5o-5ea0sNMlW_75VgGJCv2AcJ', $r);
$this->assertNull($error);
}
public function testLess4M()
{
$file = qiniuTempFile(3 * 1024 * 1024, false);
list($r, $error) = Etag::sum($file);
unlink($file);
$this->assertEquals('Fs5BpnAjRykYTg6o5E09cjuXrDkG', $r);
$this->assertNull($error);
}
public function test4M()
{
$file = qiniuTempFile(4 * 1024 * 1024, false);
list($r, $error) = Etag::sum($file);
unlink($file);
$this->assertEquals('FiuKULnybewpEnrfTmxjsxc-3dWp', $r);
$this->assertNull($error);
}
public function testMore4M()
{
$file = qiniuTempFile(5 * 1024 * 1024, false);
list($r, $error) = Etag::sum($file);
unlink($file);
$this->assertEquals('lhvyfIWMYFTq4s4alzlhXoAkqfVL', $r);
$this->assertNull($error);
}
public function test8M()
{
$file = qiniuTempFile(8 * 1024 * 1024, false);
list($r, $error) = Etag::sum($file);
unlink($file);
$this->assertEquals('lmRm9ZfGZ86bnMys4wRTWtJj9ClG', $r);
$this->assertNull($error);
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Processing\Operation;
use Qiniu\Processing\PersistentFop;
class FopTest extends TestCase
{
public function testExifPub()
{
$fop = new Operation('sdk.peterpy.cn');
list($exif, $error) = $fop->execute('gogopher.jpg', 'exif');
$this->assertNull($error);
$this->assertNotNull($exif);
}
public function testExifPrivate()
{
global $testAuth;
$fop = new Operation('private-res.qiniudn.com', $testAuth);
list($exif, $error) = $fop->execute('noexif.jpg', 'exif');
$this->assertNotNull($error);
$this->assertNull($exif);
}
public function testbuildUrl()
{
$fops = 'imageView2/2/h/200';
$fop = new Operation('testres.qiniudn.com');
$url = $fop->buildUrl('gogopher.jpg', $fops);
$this->assertEquals($url, 'http://testres.qiniudn.com/gogopher.jpg?imageView2/2/h/200');
$fops = array('imageView2/2/h/200', 'imageInfo');
$url = $fop->buildUrl('gogopher.jpg', $fops);
$this->assertEquals($url, 'http://testres.qiniudn.com/gogopher.jpg?imageView2/2/h/200|imageInfo');
}
}

View File

@ -0,0 +1,205 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Http\RequestOptions;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\FormUploader;
use Qiniu\Storage\UploadManager;
use Qiniu\Config;
class FormUpTest extends TestCase
{
private static $bucketName;
private static $auth;
private static $cfg;
private static $keysToCleanup;
/**
* @beforeClass
*/
public static function setUpConfigAndBucket()
{
global $bucketName;
self::$bucketName = $bucketName;
global $testAuth;
self::$auth = $testAuth;
self::$cfg = new Config();
self::$keysToCleanup = array();
}
/**
* @afterClass
*/
public static function cleanupTestData()
{
$bucketManager = new BucketManager(self::$auth);
$ops = BucketManager::buildBatchDelete(self::$bucketName, self::$keysToCleanup);
// ignore result for cleanup
$bucketManager->batch($ops);
}
private static function getObjectKey($key)
{
$result = $key . rand();
self::$keysToCleanup[] = $result;
return $result;
}
public function testData()
{
$key = self::getObjectKey('formput');
$token = self::$auth->uploadToken(self::$bucketName);
list($ret, $error) = FormUploader::put($token, $key, 'hello world', self::$cfg, null, 'text/plain', null);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
}
public function testDataWithProxy()
{
$key = self::getObjectKey('formput');
$token = self::$auth->uploadToken(self::$bucketName);
list($ret, $error) = FormUploader::put(
$token,
$key,
'hello world',
self::$cfg,
null,
'text/plain',
null,
$this->makeReqOpt()
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
}
public function testData2()
{
$key = self::getObjectKey('formput');
$upManager = new UploadManager();
$token = self::$auth->uploadToken(self::$bucketName);
list($ret, $error) = $upManager->put($token, $key, 'hello world', null, 'text/plain', null);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
}
public function testData2WithProxy()
{
$key = self::getObjectKey('formput');
$upManager = new UploadManager();
$token = self::$auth->uploadToken(self::$bucketName);
list($ret, $error) = $upManager->put(
$token,
$key,
'hello world',
null,
'text/plain',
null,
$this->makeReqOpt()
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
}
public function testDataFailed()
{
$key = self::getObjectKey('formput');
$token = self::$auth->uploadToken('fakebucket');
list($ret, $error) = FormUploader::put(
$token,
$key,
'hello world',
self::$cfg,
null,
'text/plain',
null
);
$this->assertNull($ret);
$this->assertNotNull($error);
}
public function testFile()
{
$key = self::getObjectKey('formPutFile');
$token = self::$auth->uploadToken(self::$bucketName, $key);
list($ret, $error) = FormUploader::putFile(
$token,
$key,
__file__,
self::$cfg,
null,
'text/plain',
null
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
}
public function testFileWithProxy()
{
$key = self::getObjectKey('formPutFile');
$token = self::$auth->uploadToken(self::$bucketName, $key);
list($ret, $error) = FormUploader::putFile(
$token,
$key,
__file__,
self::$cfg,
null,
'text/plain',
$this->makeReqOpt()
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
}
public function testFile2()
{
$key = self::getObjectKey('formPutFile');
$token = self::$auth->uploadToken(self::$bucketName, $key);
$upManager = new UploadManager();
list($ret, $error) = $upManager->putFile($token, $key, __file__, null, 'text/plain', null);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
}
public function testFile2WithProxy()
{
$key = self::getObjectKey('formPutFile');
$token = self::$auth->uploadToken(self::$bucketName, $key);
$upManager = new UploadManager();
list($ret, $error) = $upManager->putFile(
$token,
$key,
__file__,
null,
'text/plain',
false,
null,
'v1',
Config::BLOCK_SIZE,
$this->makeReqOpt()
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
}
public function testFileFailed()
{
$key = self::getObjectKey('fakekey');
$token = self::$auth->uploadToken('fakebucket', $key);
list($ret, $error) = FormUploader::putFile($token, $key, __file__, self::$cfg, null, 'text/plain', null);
$this->assertNull($ret);
$this->assertNotNull($error);
}
private function makeReqOpt()
{
$reqOpt = new RequestOptions();
$reqOpt->proxy = 'socks5://127.0.0.1:8080';
$reqOpt->proxy_user_password = 'user:pass';
return $reqOpt;
}
}

View File

@ -0,0 +1,184 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Http\Header;
class HeaderTest extends TestCase
{
protected $heads = array(
':status' => array('200'),
':x-test-1' => array('hello1'),
':x-Test-2' => array('hello2'),
'content-type' => array('application/json'),
'CONTENT-LENGTH' => array(1234),
'oRiGin' => array('https://www.qiniu.com'),
'ReFer' => array('www.qiniu.com'),
'Last-Modified' => array('Mon, 06 Sep 2021 06:44:52 GMT'),
'acCePt-ChArsEt' => array('utf-8'),
'x-test-3' => array('hello3'),
'cache-control' => array('no-cache', 'no-store'),
);
public function testNormalizeKey()
{
$except = array(
':status',
':x-test-1',
':x-Test-2',
'Content-Type',
'Content-Length',
'Origin',
'Refer',
'Last-Modified',
'Accept-Charset',
'X-Test-3',
'Cache-Control'
);
$actual = array_map(function ($str) {
return Header::normalizeKey($str);
}, array_keys($this->heads));
$this->assertEquals($actual, $except);
}
public function testInvalidKeyName()
{
$except = array(
'a:x-test-1',
);
$actual = array_map(function ($str) {
return Header::normalizeKey($str);
}, $except);
$this->assertEquals($except, $actual);
}
public function testGetRawData()
{
$header = new Header($this->heads);
foreach ($this->heads as $k => $v) {
$rawHeader = $header->getRawData();
$this->assertEquals($v, $rawHeader[Header::normalizeKey($k)]);
}
}
public function testOffsetExists()
{
$header = new Header($this->heads);
foreach (array_keys($this->heads) as $k) {
$this->assertNotNull($header[$k]);
}
$except = array(
':status',
':x-test-1',
':x-Test-2',
'Content-Type',
'Content-Length',
'Origin',
'Refer',
'Last-Modified',
'Accept-Charset',
'X-Test-3',
'Cache-Control'
);
foreach ($except as $k) {
$this->assertNotNull($header[$k], $k." is null");
}
}
public function testOffsetGet()
{
$header = new Header($this->heads);
foreach ($this->heads as $k => $v) {
$this->assertEquals($v[0], $header[$k]);
}
$this->assertNull($header['no-exist']);
}
public function testOffsetSet()
{
$header = new Header($this->heads);
$header["X-Test-3"] = "hello";
$this->assertEquals("hello", $header["X-Test-3"]);
$header["x-test-3"] = "hello test3";
$this->assertEquals("hello test3", $header["x-test-3"]);
$header[":x-Test-2"] = "hello";
$this->assertEquals("hello", $header[":x-Test-2"]);
$header[":x-test-2"] = "hello test2";
$this->assertEquals("hello", $header[":x-Test-2"]);
}
public function testOffsetUnset()
{
$header = new Header($this->heads);
unset($header["X-Test-3"]);
$this->assertFalse(isset($header["X-Test-3"]));
$header = new Header($this->heads);
unset($header["x-test-3"]);
$this->assertFalse(isset($header["x-test-3"]));
$header = new Header($this->heads);
unset($header[":x-test-2"]);
$this->assertTrue(isset($header[":x-Test-2"]));
$header = new Header($this->heads);
unset($header[":x-Test-2"]);
$this->assertFalse(isset($header[":x-Test-2"]));
}
public function testGetIterator()
{
$header = new Header($this->heads);
$hasException = false;
try {
foreach ($header as $k => $v) {
$hasException = !isset($header[$k]);
}
} catch (\Exception $e) {
$hasException = true;
}
$this->assertFalse($hasException);
}
public function testEmptyHeaderIterator()
{
$emptyHeader = new Header();
$hasException = false;
try {
foreach ($emptyHeader as $k => $v) {
$hasException = !isset($header[$k]);
}
} catch (\Exception $e) {
$hasException = true;
}
$this->assertFalse($hasException);
}
public function testCount()
{
$header = new Header($this->heads);
$this->assertEquals(count($this->heads), count($header));
}
public function testFromRaw()
{
$lines = array();
foreach ($this->heads as $k => $vs) {
foreach ($vs as $v) {
array_push($lines, $k . ": " . $v);
}
}
$raw = implode("\r\n", $lines);
$headerFromRaw = Header::fromRawText($raw);
$this->assertEquals(new Header($this->heads), $headerFromRaw);
}
}

View File

@ -0,0 +1,163 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Http\Client;
use Qiniu\Http\RequestOptions;
use Qiniu\Http\Response;
class HttpTest extends TestCase
{
public function testGet()
{
$response = Client::get('qiniu.com');
$this->assertEquals(200, $response->statusCode);
$this->assertNotNull($response->body);
$this->assertNull($response->error);
}
public function testGetQiniu()
{
$response = Client::get('upload.qiniu.com');
$this->assertEquals(405, $response->statusCode);
$this->assertNotNull($response->body);
$this->assertNotNull($response->xReqId());
$this->assertNotNull($response->xLog());
$this->assertNotNull($response->error);
}
public function testGetTimeout()
{
$reqOpt = new RequestOptions();
$reqOpt->timeout = 1;
$response = Client::get('localhost:9000/timeout.php', array(), $reqOpt);
$this->assertEquals(-1, $response->statusCode);
}
public function testGetRedirect()
{
$response = Client::get('localhost:9000/redirect.php');
$this->assertEquals(200, $response->statusCode);
$this->assertEquals('application/json;charset=UTF-8', $response->normalizedHeaders['Content-Type']);
$respData = $response->json();
$this->assertEquals('ok', $respData['msg']);
}
public function testDelete()
{
$response = Client::delete('uc.qbox.me/bucketTagging', array());
$this->assertEquals(401, $response->statusCode);
$this->assertNotNull($response->body);
$this->assertNotNull($response->error);
}
public function testDeleteQiniu()
{
$response = Client::delete('uc.qbox.me/bucketTagging', array());
$this->assertEquals(401, $response->statusCode);
$this->assertNotNull($response->body);
$this->assertNotNull($response->xReqId());
$this->assertNotNull($response->xLog());
$this->assertNotNull($response->error);
}
public function testDeleteTimeout()
{
$reqOpt = new RequestOptions();
$reqOpt->timeout = 1;
$response = Client::delete('localhost:9000/timeout.php', array(), $reqOpt);
$this->assertEquals(-1, $response->statusCode);
}
public function testPost()
{
$response = Client::post('qiniu.com', null);
$this->assertEquals(200, $response->statusCode);
$this->assertNotNull($response->body);
$this->assertNull($response->error);
}
public function testPostQiniu()
{
$response = Client::post('upload.qiniu.com', null);
$this->assertEquals(400, $response->statusCode);
$this->assertNotNull($response->body);
$this->assertNotNull($response->xReqId());
$this->assertNotNull($response->xLog());
$this->assertNotNull($response->error);
}
public function testPostTimeout()
{
$reqOpt = new RequestOptions();
$reqOpt->timeout = 1;
$response = Client::post('localhost:9000/timeout.php', null, array(), $reqOpt);
$this->assertEquals(-1, $response->statusCode);
}
public function testSocks5Proxy()
{
$reqOpt = new RequestOptions();
$reqOpt->proxy = 'socks5://localhost:8080';
$response = Client::post('qiniu.com', null, array(), $reqOpt);
$this->assertEquals(-1, $response->statusCode);
$reqOpt->proxy_user_password = 'user:pass';
$response = Client::post('qiniu.com', null, array(), $reqOpt);
$this->assertEquals(200, $response->statusCode);
}
public function testPut()
{
$response = Client::PUT('uc.qbox.me/bucketTagging', null);
$this->assertEquals(401, $response->statusCode);
$this->assertNotNull($response->body);
$this->assertNotNull($response->error);
}
public function testPutQiniu()
{
$response = Client::put('uc.qbox.me/bucketTagging', null);
$this->assertEquals(401, $response->statusCode);
$this->assertNotNull($response->body);
$this->assertNotNull($response->xReqId());
$this->assertNotNull($response->xLog());
$this->assertNotNull($response->error);
}
public function testPutTimeout()
{
$reqOpt = new RequestOptions();
$reqOpt->timeout = 1;
$response = Client::put('localhost:9000/timeout.php', null, array(), $reqOpt);
$this->assertEquals(-1, $response->statusCode);
}
public function testNeedRetry()
{
$testCases = array_merge(
array(array(-1, true)),
array_map(function ($i) {
return array($i, false);
}, range(100, 499)),
array_map(function ($i) {
if (in_array($i, array(
501, 509, 573, 579, 608, 612, 614, 616, 618, 630, 631, 632, 640, 701
))) {
return array($i, false);
}
return array($i, true);
}, range(500, 799))
);
$resp = new Response(-1, 222, array(), '{"msg": "mock"}', null);
foreach ($testCases as $testCase) {
list($code, $expectNeedRetry) = $testCase;
$resp->statusCode = $code;
$msg = $resp->statusCode . ' need' . ($expectNeedRetry ? '' : ' NOT') . ' retry';
$this->assertEquals($expectNeedRetry, $resp->needRetry(), $msg);
}
}
}

View File

@ -0,0 +1,263 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
/**
* imageprocess test
*
* @package Qiniu
* @subpackage test
* @author Sherlock Ren <sherlock_ren@icloud.com>
*/
class ImageUrlBuilderTest extends TestCase
{
/**
* 缩略图测试
*
* @test
* @return void
* @author Sherlock Ren <sherlock_ren@icloud.com>
*/
public function testThumbutl()
{
$imageUrlBuilder = new \Qiniu\Processing\ImageUrlBuilder();
$url = 'http://78re52.com1.z0.glb.clouddn.com/resource/gogopher.jpg';
$url2 = $url . '?watermark/1/gravity/SouthEast/dx/0/dy/0/image/'
. 'aHR0cDovL2Fkcy1jZG4uY2h1Y2h1amllLmNvbS9Ga1R6bnpIY2RLdmRBUFc5cHZZZ3pTc21UY0tB';
// 异常测试
$this->assertEquals($url, $imageUrlBuilder->thumbnail($url, 1, 0, 0));
$this->assertEquals($url, \Qiniu\thumbnail($url, 1, 0, 0));
// 简单缩略测试
$this->assertEquals(
$url . '?imageView2/1/w/200/h/200/ignore-error/1/',
$imageUrlBuilder->thumbnail($url, 1, 200, 200)
);
$this->assertEquals(
$url . '?imageView2/1/w/200/h/200/ignore-error/1/',
\Qiniu\thumbnail($url, 1, 200, 200)
);
// 输出格式测试
$this->assertEquals(
$url . '?imageView2/1/w/200/h/200/format/png/ignore-error/1/',
$imageUrlBuilder->thumbnail($url, 1, 200, 200, 'png')
);
$this->assertEquals(
$url . '?imageView2/1/w/200/h/200/format/png/ignore-error/1/',
\Qiniu\thumbnail($url, 1, 200, 200, 'png')
);
// 渐进显示测试
$this->assertEquals(
$url . '?imageView2/1/w/200/h/200/format/png/interlace/1/ignore-error/1/',
$imageUrlBuilder->thumbnail($url, 1, 200, 200, 'png', 1)
);
$this->assertEquals(
$url . '?imageView2/1/w/200/h/200/format/png/ignore-error/1/',
\Qiniu\thumbnail($url, 1, 200, 200, 'png', 2)
);
// 图片质量测试
$this->assertEquals(
$url . '?imageView2/1/w/200/h/200/format/png/interlace/1/q/80/ignore-error/1/',
$imageUrlBuilder->thumbnail($url, 1, 200, 200, 'png', 1, 80)
);
$this->assertEquals(
$url . '?imageView2/1/w/200/h/200/format/png/interlace/1/ignore-error/1/',
\Qiniu\thumbnail($url, 1, 200, 200, 'png', 1, 101)
);
// 多参数测试
$this->assertEquals(
$url2 . '|imageView2/1/w/200/h/200/ignore-error/1/',
$imageUrlBuilder->thumbnail($url2, 1, 200, 200)
);
$this->assertEquals(
$url2 . '|imageView2/1/w/200/h/200/ignore-error/1/',
\Qiniu\thumbnail($url2, 1, 200, 200)
);
}
/**
* 图片水印测试
*
* @test
* @param void
* @return void
* @author Sherlock Ren <sherlock_ren@icloud.com>
*/
public function waterImgTest()
{
$imageUrlBuilder = new \Qiniu\Processing\ImageUrlBuilder();
$url = 'http://78re52.com1.z0.glb.clouddn.com/resource/gogopher.jpg';
$url2 = $url . '?imageView2/1/w/200/h/200/format/png/ignore-error/1/';
$image = 'http://developer.qiniu.com/resource/logo-2.jpg';
// 水印简单测试
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/',
$imageUrlBuilder->waterImg($url, $image)
);
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/gravity/SouthEast/',
$imageUrlBuilder->waterImg($url, $image, 101)
);
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw==/',
$imageUrlBuilder->waterImg($url, $image, 101, 'sdfsd')
);
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/',
\Qiniu\waterImg($url, $image)
);
// 横轴边距测试
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/dx/10/',
$imageUrlBuilder->waterImg($url, $image, 100, 'SouthEast', 10)
);
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/',
\Qiniu\waterImg($url, $image, 100, 'SouthEast', 'sad')
);
// 纵轴边距测试
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/dx/10/dy/10/',
$imageUrlBuilder->waterImg($url, $image, 100, 'SouthEast', 10, 10)
);
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/',
\Qiniu\waterImg($url, $image, 100, 'SouthEast', 'sad', 'asdf')
);
// 自适应原图的短边比例测试
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/dx/10/dy/10/ws/0.5/',
$imageUrlBuilder->waterImg($url, $image, 100, 'SouthEast', 10, 10, 0.5)
);
$this->assertEquals(
$url . '?watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/',
\Qiniu\waterImg($url, $image, 100, 'SouthEast', 'sad', 'asdf', 2)
);
// 多参数测试
$this->assertEquals(
$url2 . '|watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/',
$imageUrlBuilder->waterImg($url2, $image)
);
$this->assertEquals(
$url2 . '|watermark/1/image/aHR0cDovL2RldmVsb3Blci5xaW5pdS5jb20vcmVzb3VyY2UvbG9nby0yLmpwZw=='
. '/dissolve/100/gravity/SouthEast/',
\Qiniu\waterImg($url2, $image)
);
}
/**
* 文字水印测试
*
* @test
* @param void
* @return void
* @author Sherlock Ren <sherlock_ren@icloud.com>
*/
public function waterTextTest()
{
$imageUrlBuilder = new \Qiniu\Processing\ImageUrlBuilder();
$url = 'http://78re52.com1.z0.glb.clouddn.com/resource/gogopher.jpg';
$url2 = $url . '?imageView2/1/w/200/h/200/format/png/ignore-error/1/';
$text = '测试一下';
$font = '微软雅黑';
$fontColor = '#FF0000';
// 水印简单测试
$this->assertEquals($url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/'
. 'fontsize/500/dissolve/100/gravity/SouthEast/', $imageUrlBuilder->waterText($url, $text, $font, 500));
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/'
. 'dissolve/100/gravity/SouthEast/',
\Qiniu\waterText($url, $text, $font, 'sdf')
);
// 字体颜色测试
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/'
. 'I0ZGMDAwMA==/dissolve/100/gravity/SouthEast/',
$imageUrlBuilder->waterText($url, $text, $font, 500, $fontColor)
);
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fill/I0ZGMDAwMA=='
. '/dissolve/100/gravity/SouthEast/',
\Qiniu\waterText($url, $text, $font, 'sdf', $fontColor)
);
// 透明度测试
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0ZGMDAwMA=='
. '/dissolve/80/gravity/SouthEast/',
$imageUrlBuilder->waterText($url, $text, $font, 500, $fontColor, 80)
);
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fill/I0ZGMDAwMA=='
. '/gravity/SouthEast/',
\Qiniu\waterText($url, $text, $font, 'sdf', $fontColor, 101)
);
// 水印位置测试
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0ZGMDAwMA=='
. '/dissolve/80/gravity/East/',
$imageUrlBuilder->waterText($url, $text, $font, 500, $fontColor, 80, 'East')
);
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fill/I0ZGMDAwMA==/',
\Qiniu\waterText($url, $text, $font, 'sdf', $fontColor, 101, 'sdfsdf')
);
// 横轴距离测试
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0ZGMDAwMA=='
. '/dissolve/80/gravity/East/dx/10/',
$imageUrlBuilder->waterText($url, $text, $font, 500, $fontColor, 80, 'East', 10)
);
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fill/I0ZGMDAwMA==/',
\Qiniu\waterText($url, $text, $font, 'sdf', $fontColor, 101, 'sdfsdf', 'sdfs')
);
// 纵轴距离测试
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0ZGMDAwMA=='
. '/dissolve/80/gravity/East/dx/10/dy/10/',
$imageUrlBuilder->waterText($url, $text, $font, 500, $fontColor, 80, 'East', 10, 10)
);
$this->assertEquals(
$url . '?watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/fill/I0ZGMDAwMA==/',
\Qiniu\waterText($url, $text, $font, 'sdf', $fontColor, 101, 'sdfsdf', 'sdfs', 'ssdf')
);
// 多参数测试
$this->assertEquals(
$url2 . '|watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/'
. 'fontsize/500/dissolve/100/gravity/SouthEast/',
$imageUrlBuilder->waterText($url2, $text, $font, 500)
);
$this->assertEquals(
$url2 . '|watermark/2/text/5rWL6K-V5LiA5LiL/font/5b6u6L2v6ZuF6buR/'
. 'fontsize/500/dissolve/100/gravity/SouthEast/',
\Qiniu\waterText($url2, $text, $font, 500)
);
}
}

View File

@ -0,0 +1,160 @@
<?php
// @codingStandardsIgnoreStart
// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Http\Client;
use Qiniu\Http\Request;
use Qiniu\Http\Middleware;
use Qiniu\Http\RequestOptions;
class RecorderMiddleware implements Middleware\Middleware
{
/**
* @var array<string>
*/
private $orderRecorder;
/**
* @var string
*/
private $label;
public function __construct(&$orderRecorder, $label)
{
$this->orderRecorder =& $orderRecorder;
$this->label = $label;
}
public function send($request, $next)
{
$this->orderRecorder[] = "bef_" . $this->label . count($this->orderRecorder);
$response = $next($request);
$this->orderRecorder[] = "aft_" . $this->label . count($this->orderRecorder);
return $response;
}
}
class MiddlewareTest extends TestCase
{
public function testSendWithMiddleware()
{
$orderRecorder = array();
$reqOpt = new RequestOptions();
$reqOpt->middlewares = array(
new RecorderMiddleware($orderRecorder, "A"),
new RecorderMiddleware($orderRecorder, "B")
);
$request = new Request(
"GET",
"http://localhost:9000/ok.php",
array(),
null,
$reqOpt
);
$response = Client::sendRequestWithMiddleware($request);
$expectRecords = array(
"bef_A0",
"bef_B1",
"aft_B2",
"aft_A3"
);
$this->assertEquals($expectRecords, $orderRecorder);
$this->assertEquals(200, $response->statusCode);
}
public function testSendWithRetryDomains()
{
$orderRecorder = array();
$reqOpt = new RequestOptions();
$reqOpt->middlewares = array(
new Middleware\RetryDomainsMiddleware(
array(
"unavailable.phpsdk.qiniu.com",
"localhost:9000",
),
3
),
new RecorderMiddleware($orderRecorder, "rec")
);
$request = new Request(
"GET",
"http://fake.phpsdk.qiniu.com/ok.php",
array(),
null,
$reqOpt
);
$response = Client::sendRequestWithMiddleware($request);
$expectRecords = array(
// 'fake.phpsdk.qiniu.com' with retried 3 times
'bef_rec0',
'aft_rec1',
'bef_rec2',
'aft_rec3',
'bef_rec4',
'aft_rec5',
// 'unavailable.pysdk.qiniu.com' with retried 3 times
'bef_rec6',
'aft_rec7',
'bef_rec8',
'aft_rec9',
'bef_rec10',
'aft_rec11',
// 'qiniu.com' and it's success
'bef_rec12',
'aft_rec13'
);
$this->assertEquals($expectRecords, $orderRecorder);
$this->assertEquals(200, $response->statusCode);
}
public function testSendFailFastWithRetryDomains()
{
$orderRecorder = array();
$reqOpt = new RequestOptions();
$reqOpt->middlewares = array(
new Middleware\RetryDomainsMiddleware(
array(
"unavailable.phpsdk.qiniu.com",
"localhost:9000",
),
3,
function () {
return false;
}
),
new RecorderMiddleware($orderRecorder, "rec")
);
$request = new Request(
"GET",
"http://fake.phpsdk.qiniu.com/ok.php",
array(),
null,
$reqOpt
);
$response = Client::sendRequestWithMiddleware($request);
$expectRecords = array(
// 'fake.phpsdk.qiniu.com' will fail fast
'bef_rec0',
'aft_rec1'
);
$this->assertEquals($expectRecords, $orderRecorder);
$this->assertEquals(-1, $response->statusCode);
}
}

View File

@ -0,0 +1,304 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Auth;
use Qiniu\Processing\PersistentFop;
use Qiniu\Storage\UploadManager;
//use Qiniu\Region;
//use Qiniu\Config;
class PfopTest extends TestCase
{
/**
* @var Auth
*/
private static $testAuth;
private static $bucketName;
/**
* @beforeClass
*/
public static function prepareEnvironment()
{
global $bucketName;
global $testAuth;
self::$bucketName = $bucketName;
self::$testAuth = $testAuth;
}
private static function getConfig()
{
// use this func to test in test env
// `null` means to use production env
return null;
}
public function testPfopExecuteAndStatusWithSingleFop()
{
global $testAuth;
$bucket = 'testres';
$key = 'sintel_trailer.mp4';
$pfop = new PersistentFop($testAuth, self::getConfig());
$fops = 'avthumb/m3u8/segtime/10/vcodec/libx264/s/320x240';
list($id, $error) = $pfop->execute($bucket, $key, $fops);
$this->assertNull($error);
list($status, $error) = $pfop->status($id);
$this->assertNotNull($status);
$this->assertNull($error);
}
public function testPfopExecuteAndStatusWithMultipleFops()
{
global $testAuth;
$bucket = 'testres';
$key = 'sintel_trailer.mp4';
$fops = array(
'avthumb/m3u8/segtime/10/vcodec/libx264/s/320x240',
'vframe/jpg/offset/7/w/480/h/360',
);
$pfop = new PersistentFop($testAuth, self::getConfig());
list($id, $error) = $pfop->execute($bucket, $key, $fops);
$this->assertNull($error);
list($status, $error) = $pfop->status($id);
$this->assertNotNull($status);
$this->assertNull($error);
}
private function pfopOptionsTestData()
{
return array(
array(
'type' => null
),
array(
'type' => -1
),
array(
'type' => 0
),
array(
'type' => 1
),
array(
'type' => 2
),
array(
'workflowTemplateID' => 'test-workflow'
)
);
}
public function testPfopExecuteWithOptions()
{
$bucket = self::$bucketName;
$key = 'qiniu.png';
$pfop = new PersistentFop(self::$testAuth, self::getConfig());
$testCases = $this->pfopOptionsTestData();
foreach ($testCases as $testCase) {
$workflowTemplateID = null;
$type = null;
if (array_key_exists('workflowTemplateID', $testCase)) {
$workflowTemplateID = $testCase['workflowTemplateID'];
}
if (array_key_exists('type', $testCase)) {
$type = $testCase['type'];
}
if ($workflowTemplateID) {
$fops = null;
} else {
$persistentEntry = \Qiniu\entry(
$bucket,
implode(
'_',
array(
'test-pfop/test-pfop-by-api',
'type',
$type
)
)
);
$fops = 'avinfo|saveas/' . $persistentEntry;
}
list($id, $error) = $pfop->execute(
$bucket,
$key,
$fops,
null,
null,
false,
$type,
$workflowTemplateID
);
if (in_array($type, array(null, 0, 1))) {
$this->assertNull($error);
list($status, $error) = $pfop->status($id);
$this->assertNotNull($status);
$this->assertNull($error);
if ($type == 1) {
$this->assertEquals(1, $status['type']);
}
if ($workflowTemplateID) {
// assertStringContainsString when PHPUnit >= 8.0
$this->assertTrue(
strpos(
$status['taskFrom'],
$workflowTemplateID
) !== false
);
}
$this->assertNotEmpty($status['creationDate']);
} else {
$this->assertNotNull($error);
}
}
}
public function testPfopWithInvalidArgument()
{
$bucket = self::$bucketName;
$key = 'qiniu.png';
$pfop = new PersistentFop(self::$testAuth, self::getConfig());
$err = null;
try {
$pfop->execute(
$bucket,
$key
);
} catch (\Exception $e) {
$err = $e;
}
$this->assertNotEmpty($err);
$this->assertTrue(
strpos(
$err->getMessage(),
'Must provide one of fops or template_id'
) !== false
);
}
public function testPfopWithUploadPolicy()
{
$bucket = self::$bucketName;
$testAuth = self::$testAuth;
$key = 'test-pfop/upload-file';
$testCases = $this->pfopOptionsTestData();
foreach ($testCases as $testCase) {
$workflowTemplateID = null;
$type = null;
if (array_key_exists('workflowTemplateID', $testCase)) {
$workflowTemplateID = $testCase['workflowTemplateID'];
}
if (array_key_exists('type', $testCase)) {
$type = $testCase['type'];
}
$putPolicy = array(
'persistentType' => $type
);
if ($workflowTemplateID) {
$putPolicy['persistentWorkflowTemplateID'] = $workflowTemplateID;
} else {
$persistentEntry = \Qiniu\entry(
$bucket,
implode(
'_',
array(
'test-pfop/test-pfop-by-upload',
'type',
$type
)
)
);
$putPolicy['persistentOps'] = 'avinfo|saveas/' . $persistentEntry;
}
if ($type == null) {
unset($putPolicy['persistentType']);
}
$token = $testAuth->uploadToken(
$bucket,
$key,
3600,
$putPolicy
);
$upManager = new UploadManager(self::getConfig());
list($ret, $error) = $upManager->putFile(
$token,
$key,
__file__,
null,
'text/plain',
true
);
if (in_array($type, array(null, 0, 1))) {
$this->assertNull($error);
$this->assertNotEmpty($ret['persistentId']);
$id = $ret['persistentId'];
} else {
$this->assertNotNull($error);
return;
}
$pfop = new PersistentFop($testAuth, self::getConfig());
list($status, $error) = $pfop->status($id);
$this->assertNotNull($status);
$this->assertNull($error);
if ($type == 1) {
$this->assertEquals(1, $status['type']);
}
if ($workflowTemplateID) {
// assertStringContainsString when PHPUnit >= 8.0
$this->assertTrue(
strpos(
$status['taskFrom'],
$workflowTemplateID
) !== false
);
}
$this->assertNotEmpty($status['creationDate']);
}
}
public function testMkzip()
{
$bucket = self::$bucketName;
$key = 'php-logo.png';
$pfop = new PersistentFop(self::$testAuth, null);
$url1 = 'http://phpsdk.qiniudn.com/php-logo.png';
$url2 = 'http://phpsdk.qiniudn.com/php-sdk.html';
$zipKey = 'test.zip';
$fops = 'mkzip/2/url/' . \Qiniu\base64_urlSafeEncode($url1);
$fops .= '/url/' . \Qiniu\base64_urlSafeEncode($url2);
$fops .= '|saveas/' . \Qiniu\base64_urlSafeEncode("$bucket:$zipKey");
list($id, $error) = $pfop->execute($bucket, $key, $fops);
$this->assertNull($error);
list($status, $error) = $pfop->status($id);
$this->assertNotNull($status);
$this->assertNull($error);
}
}

View File

@ -0,0 +1,354 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu\Http\RequestOptions;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Qiniu\Http\Client;
use Qiniu\Config;
class ResumeUpTest extends TestCase
{
private static $bucketName;
private static $auth;
private static $keysToCleanup = array();
/**
* @beforeClass
*/
public static function setUpAuthAndBucket()
{
global $bucketName;
self::$bucketName = $bucketName;
global $testAuth;
self::$auth = $testAuth;
}
/**
* @afterClass
*/
public static function cleanupTestData()
{
$ops = BucketManager::buildBatchDelete(self::$bucketName, self::$keysToCleanup);
$bucketManager = new BucketManager(self::$auth);
$bucketManager->batch($ops);
}
private static function getObjectKey($key)
{
$result = $key . rand();
self::$keysToCleanup[] = $result;
return $result;
}
public function test4ML()
{
$key = self::getObjectKey('resumePutFile4ML_');
$upManager = new UploadManager();
$token = self::$auth->uploadToken(self::$bucketName, $key);
$tempFile = qiniuTempFile(4 * 1024 * 1024 + 10);
$resumeFile = tempnam(sys_get_temp_dir(), 'resume_file');
$this->assertNotFalse($resumeFile);
list($ret, $error) = $upManager->putFile(
$token,
$key,
$tempFile,
null,
'application/octet-stream',
false,
$resumeFile
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
$domain = getenv('QINIU_TEST_DOMAIN');
$response = Client::get("http://$domain/$key");
$this->assertEquals(200, $response->statusCode);
$this->assertEquals(md5_file($tempFile, true), md5($response->body(), true));
unlink($tempFile);
}
public function test4ML2()
{
$key = self::getObjectKey('resumePutFile4ML_');
$cfg = new Config();
$upManager = new UploadManager($cfg);
$token = self::$auth->uploadToken(self::$bucketName, $key);
$tempFile = qiniuTempFile(4 * 1024 * 1024 + 10);
$resumeFile = tempnam(sys_get_temp_dir(), 'resume_file');
$this->assertNotFalse($resumeFile);
list($ret, $error) = $upManager->putFile(
$token,
$key,
$tempFile,
null,
'application/octet-stream',
false,
$resumeFile
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
$domain = getenv('QINIU_TEST_DOMAIN');
$response = Client::get("http://$domain/$key");
$this->assertEquals(200, $response->statusCode);
$this->assertEquals(md5_file($tempFile, true), md5($response->body(), true));
unlink($tempFile);
}
public function test4ML2WithProxy()
{
$key = self::getObjectKey('resumePutFile4ML_');
$cfg = new Config();
$upManager = new UploadManager($cfg);
$token = self::$auth->uploadToken(self::$bucketName, $key);
$tempFile = qiniuTempFile(4 * 1024 * 1024 + 10);
$resumeFile = tempnam(sys_get_temp_dir(), 'resume_file');
$this->assertNotFalse($resumeFile);
list($ret, $error) = $upManager->putFile(
$token,
$key,
$tempFile,
null,
'application/octet-stream',
false,
$resumeFile,
'v2',
Config::BLOCK_SIZE,
$this->makeReqOpt()
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
$domain = getenv('QINIU_TEST_DOMAIN');
$response = Client::get("http://$domain/$key");
$this->assertEquals(200, $response->statusCode);
$this->assertEquals(md5_file($tempFile, true), md5($response->body(), true));
unlink($tempFile);
}
// public function test8M()
// {
// $key = 'resumePutFile8M';
// $upManager = new UploadManager();
// $token = self::$auth->uploadToken(self::$bucketName, $key);
// $tempFile = qiniuTempFile(8*1024*1024+10);
// list($ret, $error) = $upManager->putFile($token, $key, $tempFile);
// $this->assertNull($error);
// $this->assertNotNull($ret['hash']);
// unlink($tempFile);
// }
public function testFileWithFileType()
{
$config = new Config();
$bucketManager = new BucketManager(self::$auth, $config);
$testCases = array(
array(
"fileType" => 1,
"name" => "IA"
),
array(
"fileType" => 2,
"name" => "Archive"
),
array(
"fileType" => 3,
"name" => "DeepArchive"
)
);
foreach ($testCases as $testCase) {
$key = self::getObjectKey('FileType' . $testCase["name"]);
$police = array(
"fileType" => $testCase["fileType"],
);
$token = self::$auth->uploadToken(self::$bucketName, $key, 3600, $police);
$upManager = new UploadManager();
list($ret, $error) = $upManager->putFile($token, $key, __file__, null, 'text/plain');
$this->assertNull($error);
$this->assertNotNull($ret);
list($ret, $err) = $bucketManager->stat(self::$bucketName, $key);
$this->assertNull($err);
$this->assertEquals($testCase["fileType"], $ret["type"]);
}
}
public function testResumeUploadWithParams()
{
$key = self::getObjectKey('resumePutFile4ML_');
$upManager = new UploadManager();
$policy = array('returnBody' => '{"hash":$(etag),"fname":$(fname),"var_1":$(x:var_1),"var_2":$(x:var_2)}');
$token = self::$auth->uploadToken(self::$bucketName, $key, 3600, $policy);
$tempFile = qiniuTempFile(4 * 1024 * 1024 + 10);
$resumeFile = tempnam(sys_get_temp_dir(), 'resume_file');
$this->assertNotFalse($resumeFile);
list($ret, $error) = $upManager->putFile(
$token,
$key,
$tempFile,
array("x:var_1" => "val_1", "x:var_2" => "val_2", "x-qn-meta-m1" => "val_1", "x-qn-meta-m2" => "val_2"),
'application/octet-stream',
false,
$resumeFile
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
$this->assertEquals("val_1", $ret['var_1']);
$this->assertEquals("val_2", $ret['var_2']);
$this->assertEquals(basename($tempFile), $ret['fname']);
$domain = getenv('QINIU_TEST_DOMAIN');
$response = Client::get("http://$domain/$key");
$this->assertEquals(200, $response->statusCode);
$this->assertEquals(md5_file($tempFile, true), md5($response->body(), true));
$headers = $response->headers();
$this->assertEquals("val_1", $headers["X-Qn-Meta-M1"]);
$this->assertEquals("val_2", $headers["X-Qn-Meta-M2"]);
unlink($tempFile);
}
public function testResumeUploadV2()
{
$cfg = new Config();
$upManager = new UploadManager($cfg);
$testFileSize = array(
config::BLOCK_SIZE / 2,
config::BLOCK_SIZE,
config::BLOCK_SIZE + 10,
config::BLOCK_SIZE * 2,
config::BLOCK_SIZE * 2.5
);
$partSize = 5 * 1024 * 1024;
foreach ($testFileSize as $item) {
$key = self::getObjectKey('resumePutFile4ML_');
$token = self::$auth->uploadToken(self::$bucketName, $key);
$tempFile = qiniuTempFile($item);
$resumeFile = tempnam(sys_get_temp_dir(), 'resume_file');
$this->assertNotFalse($resumeFile);
list($ret, $error) = $upManager->putFile(
$token,
$key,
$tempFile,
null,
'application/octet-stream',
false,
$resumeFile,
'v2',
$partSize
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
$domain = getenv('QINIU_TEST_DOMAIN');
$response = Client::get("http://$domain/$key");
$this->assertEquals(200, $response->statusCode);
$this->assertEquals(md5_file($tempFile, true), md5($response->body(), true));
unlink($tempFile);
}
}
public function testResumeUploadV2WithParams()
{
$key = self::getObjectKey('resumePutFile4ML_');
$upManager = new UploadManager();
$policy = array('returnBody' => '{"hash":$(etag),"fname":$(fname),"var_1":$(x:var_1),"var_2":$(x:var_2)}');
$token = self::$auth->uploadToken(self::$bucketName, $key, 3600, $policy);
$tempFile = qiniuTempFile(4 * 1024 * 1024 + 10);
$resumeFile = tempnam(sys_get_temp_dir(), 'resume_file');
$this->assertNotFalse($resumeFile);
list($ret, $error) = $upManager->putFile(
$token,
$key,
$tempFile,
array("x:var_1" => "val_1", "x:var_2" => "val_2", "x-qn-meta-m1" => "val_1", "x-qn-meta-m2" => "val_2"),
'application/octet-stream',
false,
$resumeFile,
'v2'
);
$this->assertNull($error);
$this->assertNotNull($ret['hash']);
$this->assertEquals("val_1", $ret['var_1']);
$this->assertEquals("val_2", $ret['var_2']);
$this->assertEquals(basename($tempFile), $ret['fname']);
$domain = getenv('QINIU_TEST_DOMAIN');
$response = Client::get("http://$domain/$key");
$this->assertEquals(200, $response->statusCode);
$this->assertEquals(md5_file($tempFile, true), md5($response->body(), true));
$headers = $response->headers();
$this->assertEquals("val_1", $headers["X-Qn-Meta-M1"]);
$this->assertEquals("val_2", $headers["X-Qn-Meta-M2"]);
unlink($tempFile);
}
// valid versions are tested above
// Use PHPUnit's Data Provider to test multiple Exception is better,
// but not match the test style of this project
public function testResumeUploadWithInvalidVersion()
{
$cfg = new Config();
$upManager = new UploadManager($cfg);
$testFileSize = config::BLOCK_SIZE * 2;
$partSize = 5 * 1024 * 1024;
$testInvalidVersions = array(
// High probability invalid versions
'v',
'1',
'2'
);
$expectExceptionCount = 0;
foreach ($testInvalidVersions as $invalidVersion) {
$key = self::getObjectKey('resumePutFile4ML_');
$token = self::$auth->uploadToken(self::$bucketName, $key);
$tempFile = qiniuTempFile($testFileSize);
$resumeFile = tempnam(sys_get_temp_dir(), 'resume_file');
$this->assertNotFalse($resumeFile);
try {
$upManager->putFile(
$token,
$key,
$tempFile,
null,
'application/octet-stream',
false,
$resumeFile,
$invalidVersion,
$partSize
);
} catch (\Exception $e) {
$isRightException = false;
$expectExceptionCount++;
while ($e) {
$isRightException = $e instanceof \UnexpectedValueException;
if ($isRightException) {
break;
}
$e = $e->getPrevious();
}
$this->assertTrue($isRightException);
}
unlink($tempFile);
}
$this->assertEquals(count($testInvalidVersions), $expectExceptionCount);
}
private function makeReqOpt()
{
$reqOpt = new RequestOptions();
$reqOpt->proxy = 'socks5://127.0.0.1:8080';
$reqOpt->proxy_user_password = 'user:pass';
return $reqOpt;
}
}

View File

@ -0,0 +1,136 @@
<?php
namespace Qiniu\Tests;
use PHPUnit\Framework\TestCase;
use Qiniu;
use Qiniu\Zone;
class ZoneTest extends TestCase
{
protected $zone;
protected $zoneHttps;
protected $ak;
protected $bucketName;
protected $bucketNameBC;
protected $bucketNameNA;
protected $bucketNameFS;
protected $bucketNameAS;
/**
* @before
*/
protected function setUpZoneAndBucket()
{
global $bucketName;
$this->bucketName = $bucketName;
global $bucketNameBC;
$this->bucketNameBC = $bucketNameBC;
global $bucketNameNA;
$this->bucketNameNA = $bucketNameNA;
global $bucketNameFS;
$this->bucketNameFS = $bucketNameFS;
global $bucketNameAS;
$this->bucketNameAS = $bucketNameAS;
global $accessKey;
$this->ak = $accessKey;
$this->zone = new Zone();
$this->zoneHttps = new Zone('https');
}
public function testUpHosts()
{
list($ret, $err) = Zone::queryZone($this->ak, 'fakebucket');
$this->assertNull($ret);
$this->assertNotNull($err);
$zone = Zone::queryZone($this->ak, $this->bucketName);
$this->assertContains('upload.qiniup.com', $zone->cdnUpHosts);
$zone = Zone::queryZone($this->ak, $this->bucketNameBC);
$this->assertContains('upload-z1.qiniup.com', $zone->cdnUpHosts);
$zone = Zone::queryZone($this->ak, $this->bucketNameFS);
$this->assertContains('upload-z2.qiniup.com', $zone->cdnUpHosts);
$zone = Zone::queryZone($this->ak, $this->bucketNameNA);
$this->assertContains('upload-na0.qiniup.com', $zone->cdnUpHosts);
$zone = Zone::queryZone($this->ak, $this->bucketNameAS);
$this->assertContains('upload-as0.qiniup.com', $zone->cdnUpHosts);
}
public function testIoHosts()
{
$zone = Zone::queryZone($this->ak, $this->bucketName);
$this->assertEquals($zone->iovipHost, 'iovip.qbox.me');
$zone = Zone::queryZone($this->ak, $this->bucketNameBC);
$this->assertEquals($zone->iovipHost, 'iovip-z1.qbox.me');
$zone = Zone::queryZone($this->ak, $this->bucketNameFS);
$this->assertEquals($zone->iovipHost, 'iovip-z2.qbox.me');
$zone = Zone::queryZone($this->ak, $this->bucketNameNA);
$this->assertEquals($zone->iovipHost, 'iovip-na0.qbox.me');
$zone = Zone::queryZone($this->ak, $this->bucketNameAS);
$this->assertEquals($zone->iovipHost, 'iovip-as0.qbox.me');
}
public function testZonez0()
{
$zone = Zone::zonez0();
$this->assertContains('upload.qiniup.com', $zone->cdnUpHosts);
}
public function testZonez1()
{
$zone = Zone::zonez1();
$this->assertContains('upload-z1.qiniup.com', $zone->cdnUpHosts);
}
public function testZonez2()
{
$zone = Zone::zonez2();
$this->assertContains('upload-z2.qiniup.com', $zone->cdnUpHosts);
}
public function testZoneCnEast2()
{
$zone = Zone::zoneCnEast2();
$this->assertContains('upload-cn-east-2.qiniup.com', $zone->cdnUpHosts);
}
public function testZoneNa0()
{
$zone = Zone::zoneNa0();
$this->assertContains('upload-na0.qiniup.com', $zone->cdnUpHosts);
}
public function testZoneAs0()
{
$zone = Zone::zoneAs0();
$this->assertContains('upload-as0.qiniup.com', $zone->cdnUpHosts);
}
public function testQvmZonez0()
{
$zone = Zone::qvmZonez0();
$this->assertContains('free-qvm-z0-xs.qiniup.com', $zone->srcUpHosts);
}
public function testQvmZonez1()
{
$zone = Zone::qvmZonez1();
$this->assertContains('free-qvm-z1-zz.qiniup.com', $zone->srcUpHosts);
}
}