test.js 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936
  1. var COS = require('./lib/cos-wx-sdk-v5');
  2. var wxfs = wx.getFileSystemManager();
  3. var config = require('./config');
  4. // 这里替换成自己的Uin (账号ID查询:https://console.cloud.tencent.com/developer)
  5. config.Uin = '10001';
  6. /**
  7. * 测试须知
  8. * 需要本地准备一个名为 5m.zip,大小为5mb的文件进行初始化上传
  9. **/
  10. var util = {
  11. createFile: function (options, filePath) {
  12. var buffer = new ArrayBuffer(options.size || 0);
  13. var arr = new Uint8Array(buffer);
  14. for (var i = 0; i < arr.length; i++) {
  15. arr[i] = 0;
  16. }
  17. var opt = {};
  18. options.type && (opt.type = options.type);
  19. if (filePath) {
  20. try {
  21. wxfs.statSync(filePath);
  22. } catch (e) {
  23. try {
  24. wxfs.writeFileSync(filePath, buffer);
  25. } catch (e) {
  26. }
  27. }
  28. }
  29. return buffer;
  30. },
  31. str2buf: function (str) {
  32. var size = str.length;
  33. var buffer = new ArrayBuffer(size || 0);
  34. var arr = new Uint8Array(buffer);
  35. for (var i = 0; i < arr.length; i++) {
  36. arr[i] = str[i];
  37. }
  38. return buffer;
  39. },
  40. };
  41. // var clearDir = function () {
  42. // var list = wxfs.readdirSync(wx.env.USER_DATA_PATH);
  43. // list.forEach(function (filename) {
  44. // try {
  45. // wxfs.unlinkSync(wx.env.USER_DATA_PATH + '/' + filename);
  46. // } catch (e) {}
  47. // });
  48. // };
  49. // clearDir();
  50. function camSafeUrlEncode(str) {
  51. return encodeURIComponent(str)
  52. .replace(/!/g, '%21')
  53. .replace(/'/g, '%27')
  54. .replace(/\(/g, '%28')
  55. .replace(/\)/g, '%29')
  56. .replace(/\*/g, '%2A');
  57. }
  58. var getAuthorization = function (options, callback) {
  59. wx.request({
  60. method: 'GET',
  61. url: config.stsUrl, // 服务端签名,参考 server 目录下的两个签名例子
  62. dataType: 'json',
  63. success: function(result) {
  64. var data = result.data;
  65. var credentials = data && data.credentials;
  66. if (!data || !credentials) return console.error('credentials invalid');
  67. callback({
  68. TmpSecretId: credentials.tmpSecretId,
  69. TmpSecretKey: credentials.tmpSecretKey,
  70. XCosSecurityToken: credentials.sessionToken,
  71. StartTime: data.startTime, // 时间戳,单位秒,如:1580000000,建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
  72. ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000900
  73. });
  74. }
  75. });
  76. };
  77. var dataURItoUploadBody = function (dataURI) {
  78. var byteString = atob(dataURI.split(',')[1]);
  79. var ab = new ArrayBuffer(byteString.length);
  80. var ia = new Uint8Array(ab);
  81. for (var i = 0; i < byteString.length; i++) {
  82. ia[i] = byteString.charCodeAt(i);
  83. }
  84. return ab;
  85. };
  86. var serial = function (list, fn, cb) {
  87. var next = function (i) {
  88. if (i >= list.length) return cb && cb();
  89. var loaded = false;
  90. fn(list[i], i, function () {
  91. if (loaded) {
  92. throw new Error('done() 被重复调用');
  93. return;
  94. }
  95. loaded = true;
  96. next(i + 1);
  97. });
  98. };
  99. next(0);
  100. };
  101. var test;
  102. var testFile = {};
  103. var group = (function (name, fn) {
  104. // 按顺序执行每个 group
  105. var groupQueue = [];
  106. var successCount = 0;
  107. var errorCount = 0;
  108. var errorList = [];
  109. var startTest = function () {
  110. serial(groupQueue, function (groupItem, groupIndex, nextGroup) {
  111. // 按顺序执行每个 group
  112. var testQueue = [];
  113. test = function (name, fn) {
  114. testQueue.push([name, fn]);
  115. };
  116. console.log((groupIndex + 1) + ' ' + groupItem[0])
  117. groupItem[1]();
  118. setTimeout(function () {
  119. serial(testQueue, function (testItem, testIndex, nextTest) {
  120. var assert = {
  121. ok: function (result, msg) {
  122. result ? successCount++ : errorCount++;
  123. var message = [' ' + (groupIndex + 1) + '.' + (testIndex + 1), result ? '[success]' : '[error]', msg || ''];
  124. console[result ? 'info' : 'error'](message.join(' '));
  125. },
  126. equal: function (a, b, msg) {
  127. assert.ok(a === b, msg);
  128. },
  129. };
  130. testItem[1](nextTest, assert);
  131. }, nextGroup);
  132. });
  133. }, function () {
  134. console.log('test complete! total ' + (successCount + errorCount) + ' cases, ' + errorCount + ' error.');
  135. if (errorList.length) {
  136. errorList.forEach(function (item) {
  137. console.error(item);
  138. })
  139. }
  140. });
  141. };
  142. wx.chooseMessageFile({
  143. count: 10,
  144. type: 'all',
  145. success: function(res) {
  146. res.tempFiles && res.tempFiles.forEach(v => {
  147. testFile[v.name] = v.path;
  148. });
  149. startTest();
  150. },
  151. });
  152. return function (name, fn) {
  153. groupQueue.push([name, fn]);
  154. }
  155. })();
  156. var request = function (opt, callback) {
  157. wx.request({
  158. method: opt.method,
  159. url: opt.url,
  160. header: opt.headers,
  161. dataType: 'text',
  162. data: opt.body,
  163. timeout: opt.timeout,
  164. success: function (response) {
  165. callback(null, response, response.data);
  166. },
  167. fail: function (response) {
  168. callback(response.errMsg, response, response.body);
  169. },
  170. });
  171. };
  172. var cos = new COS({
  173. // 必选参数
  174. getAuthorization: getAuthorization,
  175. // 可选参数
  176. FileParallelLimit: 3, // 控制文件上传并发数
  177. ChunkParallelLimit: 3, // 控制单个文件下分片上传并发数
  178. ChunkSize: 1024 * 1024, // 控制分片大小,单位 B
  179. ProgressInterval: 1, // 控制 onProgress 回调的间隔
  180. ChunkRetryTimes: 3, // 控制文件切片后单片上传失败后重试次数
  181. UploadCheckContentMd5: true, // 上传过程计算 Content-MD5
  182. });
  183. var AppId = config.AppId;
  184. var Bucket = config.Bucket;
  185. var BucketShortName = Bucket;
  186. var BucketLongName = Bucket + '-' + AppId;
  187. var TaskId;
  188. var match = config.Bucket.match(/^(.+)-(\d+)$/);
  189. if (match) {
  190. BucketLongName = config.Bucket;
  191. BucketShortName = match[1];
  192. AppId = match[2];
  193. }
  194. function comparePlainObject(a, b) {
  195. if (Object.keys(a).length !== Object.keys(b).length) {
  196. return false;
  197. }
  198. for (var key in a) {
  199. if (typeof a[key] === 'object' && typeof b[key] === 'object') {
  200. if (!comparePlainObject(a[key], b[key])) {
  201. return false;
  202. }
  203. } else if (a[key] != b[key]) {
  204. return false;
  205. }
  206. }
  207. return true;
  208. }
  209. function prepareBigObject(needHeaders, callback) {
  210. var filename = 'bigger.zip';
  211. var content = util.createFile({size: 1024 * 1024 * 10});
  212. // 调用方法
  213. var params = {
  214. Bucket: config.Bucket,
  215. Region: config.Region,
  216. Key: filename,
  217. Body: content,
  218. ContentLength: content.length,
  219. };
  220. if (needHeaders) {
  221. params.ContentType = 'text/html';
  222. params.CacheControl = 'max-age=7200';
  223. params.ContentDisposition = 'inline;filename=hello.jpg';
  224. params.ContentEncoding = 'gzip';
  225. params.Expires = (new Date()).toGMTString();
  226. params.Headers = {
  227. 'x-cos-meta-test': 'xxx'
  228. };
  229. }
  230. cos.putObject(params, function (err) {
  231. if (err) return console.error('prepareBigObject err', err);
  232. callback();
  233. });
  234. }
  235. function prepareBucket() {
  236. return new Promise(function (resolve, reject) {
  237. resolve();
  238. });
  239. }
  240. group('getAuth()', function () {
  241. test('getAuth()', function (done, assert) {
  242. var content = Date.now().toString();
  243. var key = '1.txt';
  244. cos.putObject({
  245. Bucket: config.Bucket,
  246. Region: config.Region,
  247. Key: key,
  248. Body: content,
  249. }, function (err, data) {
  250. cos.options.getAuthorization({
  251. Method: 'get',
  252. Key: key,
  253. Scope: [{
  254. action: 'GetObject',
  255. bucket: config.Bucket,
  256. region: config.Region,
  257. prefix: key,
  258. }],
  259. }, function (AuthData) {
  260. if (typeof AuthData === 'string') {
  261. AuthData = {Authorization: AuthData};
  262. }
  263. if (!AuthData.Authorization) {
  264. AuthData.Authorization = COS.getAuthorization({
  265. SecretId: AuthData.TmpSecretId,
  266. SecretKey: AuthData.TmpSecretKey,
  267. Method: 'get',
  268. Key: key,
  269. SystemClockOffset: cos.options.SystemClockOffset,
  270. });
  271. }
  272. var link = 'http://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com' + '/' +
  273. camSafeUrlEncode(key).replace(/%2F/g, '/') + '?' + AuthData.Authorization +
  274. (AuthData.XCosSecurityToken ? '&x-cos-security-token=' + AuthData.XCosSecurityToken : '');
  275. request({
  276. url: link,
  277. }, function (err, response, body) {
  278. assert.ok(response.statusCode === 200);
  279. assert.ok(body === content);
  280. done();
  281. });
  282. });
  283. });
  284. });
  285. });
  286. group('getObjectUrl()', function () {
  287. test('getObjectUrl()', function (done, assert) {
  288. var content = Date.now().toString();
  289. var key = '1.txt';
  290. cos.putObject({
  291. Bucket: config.Bucket,
  292. Region: config.Region,
  293. Key: key,
  294. Body: content,
  295. }, function (err, data) {
  296. cos.getObjectUrl({
  297. Bucket: config.Bucket,
  298. Region: config.Region,
  299. Key: key,
  300. }, function (err, data) {
  301. request({
  302. url: data.Url,
  303. }, function (err, response, body) {
  304. assert.ok(!err, '文件获取出错');
  305. assert.ok(response.statusCode === 200, '获取文件 200');
  306. assert.ok(body.toString() === content, '通过获取签名能正常获取文件');
  307. done();
  308. });
  309. });
  310. });
  311. });
  312. });
  313. group('auth check', function () {
  314. test('auth check', function (done, assert) {
  315. cos.getBucket({
  316. Bucket: config.Bucket,
  317. Region: config.Region,
  318. Prefix: 'aksjhdlash sajlhj!@#$%^&*()_+=-[]{}\';:"/.<>?.,??sadasd#/.,/~`',
  319. Headers: {
  320. 'x-cos-test': 'aksjhdlash sajlhj!@#$%^&*()_+=-[]{}\';:\"/.<>?.,??sadasd#/.,/~`',
  321. },
  322. }, function (err, data) {
  323. assert.ok(!err);
  324. done();
  325. });
  326. });
  327. });
  328. group('getBucket()', function () {
  329. test('正常获取 bucket 里的文件列表', function (done, assert) {
  330. prepareBucket().then(function () {
  331. cos.getBucket({
  332. Bucket: config.Bucket,
  333. Region: config.Region
  334. }, function (err, data) {
  335. assert.equal(true, data.Name === BucketLongName);
  336. assert.equal(data.Contents.constructor, Array);
  337. done();
  338. });
  339. }).catch(function () {
  340. assert.equal(false);
  341. done();
  342. });
  343. });
  344. });
  345. group('putObject(),cancelTask()', function () {
  346. test('putObject(),cancelTask()', function (done, assert) {
  347. var filename = '10m.zip';
  348. var alive = false;
  349. var canceled = false;
  350. cos.putObject({
  351. Bucket: config.Bucket,
  352. Region: config.Region,
  353. Key: filename,
  354. Body: util.createFile({size: 1024 * 1024 * 10}),
  355. onTaskReady: function (taskId) {
  356. TaskId = taskId;
  357. },
  358. onProgress: function (info) {
  359. alive = true;
  360. if (!canceled) {
  361. setTimeout(function () {
  362. cos.cancelTask(TaskId);
  363. alive = false;
  364. canceled = true;
  365. setTimeout(function () {
  366. assert.ok(!alive, '取消上传已经生效');
  367. done();
  368. }, 1200);
  369. }, 1200);
  370. }
  371. }
  372. }, function (err, data) {
  373. alive = true;
  374. });
  375. });
  376. });
  377. group('sliceUploadFile() 完整上传文件', function () {
  378. test('sliceUploadFile() 完整上传文件', function (done, assert) {
  379. var lastPercent;
  380. var filename = '5m.zip';
  381. var fileSize = 1024 * 1024 * 5;
  382. cos.abortUploadTask({
  383. Bucket: config.Bucket,
  384. Region: config.Region,
  385. Key: filename,
  386. Level: 'file',
  387. }, function () {
  388. cos.sliceUploadFile({
  389. Bucket: config.Bucket,
  390. Region: config.Region,
  391. Key: filename,
  392. FilePath: testFile[filename],
  393. onTaskReady: function (taskId) {
  394. TaskId = taskId;
  395. },
  396. onProgress: function (info) {
  397. lastPercent = info.percent;
  398. }
  399. }, function (err, data) {
  400. assert.ok(data.ETag.length > 0);
  401. cos.headObject({
  402. Bucket: config.Bucket,
  403. Region: config.Region,
  404. Key: filename,
  405. }, function (err, data) {
  406. assert.ok(data && data.headers && data.headers.etag && data.headers.etag.length > 0, '文件已上传成功');
  407. assert.ok(data && data.headers && parseInt(data.headers['content-length'] || 0) === fileSize, '文件大小一致');
  408. done();
  409. });
  410. });
  411. });
  412. });
  413. });
  414. group('sliceUploadFile(),pauseTask(),restartTask()', function () {
  415. test('sliceUploadFile(),pauseTask(),restartTask()', function (done, assert) {
  416. var filename = '5m.zip';
  417. var paused = false;
  418. var restarted = false;
  419. cos.abortUploadTask({
  420. Bucket: config.Bucket,
  421. Region: config.Region,
  422. Key: filename,
  423. Level: 'file',
  424. }, function (err, data) {
  425. cos.sliceUploadFile({
  426. Bucket: config.Bucket,
  427. Region: config.Region,
  428. Key: filename,
  429. FilePath: testFile[filename],
  430. onTaskReady: function (taskId) {
  431. TaskId = taskId;
  432. },
  433. onProgress: function (info) {
  434. if (!paused && info.percent > 0.6) {
  435. cos.pauseTask(TaskId);
  436. paused = true;
  437. setTimeout(function () {
  438. restarted = true;
  439. cos.restartTask(TaskId);
  440. }, 1000);
  441. }
  442. if (paused && restarted) {
  443. if (info.percent === 0) return;
  444. if (!info.percent > 0.3) {
  445. console.log(info.percent);
  446. }
  447. assert.ok(info.percent > 0.3, '暂停和重试成功');
  448. cos.cancelTask(TaskId);
  449. done();
  450. }
  451. }
  452. }, function (err, data) {
  453. paused = true;
  454. });
  455. });
  456. });
  457. });
  458. group('sliceUploadFile(),cancelTask()', function () {
  459. test('sliceUploadFile(),cancelTask()', function (done, assert) {
  460. var filename = '5m.zip';
  461. var blob = util.createFile({size: 1024 * 1024 * 5});
  462. var alive = false;
  463. var canceled = false;
  464. cos.sliceUploadFile({
  465. Bucket: config.Bucket,
  466. Region: config.Region,
  467. Key: filename,
  468. FilePath: testFile[filename],
  469. onTaskReady: function (taskId) {
  470. TaskId = taskId;
  471. },
  472. onProgress: function (info) {
  473. alive = true;
  474. if (!canceled) {
  475. cos.cancelTask(TaskId);
  476. alive = false;
  477. canceled = true;
  478. setTimeout(function () {
  479. assert.ok(!alive, '取消上传已经生效');
  480. done();
  481. }, 1200);
  482. }
  483. }
  484. }, function (err, data) {
  485. alive = true;
  486. });
  487. });
  488. });
  489. group('abortUploadTask()', function () {
  490. test('abortUploadTask(),Level=task', function (done, assert) {
  491. var filename = '1m.zip';
  492. cos.multipartInit({
  493. Bucket: config.Bucket,
  494. Region: config.Region,
  495. Key: filename,
  496. }, function (err, data) {
  497. cos.abortUploadTask({
  498. Bucket: config.Bucket,
  499. Region: config.Region,
  500. Key: filename,
  501. Level: 'task',
  502. UploadId: data.UploadId,
  503. }, function (err, data) {
  504. var nameExist = false;
  505. data.successList.forEach(function (item) {
  506. if (filename === item.Key) {
  507. nameExist = true;
  508. }
  509. });
  510. assert.ok(data.successList.length >= 1, '成功取消单个分片任务');
  511. assert.ok(nameExist, '成功取消单个分片任务');
  512. done();
  513. });
  514. });
  515. });
  516. test('abortUploadTask(),Level=file', function (done, assert) {
  517. var filename = '1m.zip';
  518. cos.multipartInit({
  519. Bucket: config.Bucket,
  520. Region: config.Region,
  521. Key: filename,
  522. }, function (err, data) {
  523. cos.abortUploadTask({
  524. Bucket: config.Bucket,
  525. Region: config.Region,
  526. Level: 'file',
  527. Key: filename,
  528. }, function (err, data) {
  529. assert.ok(data.successList.length >= 1, '成功舍弃单个文件下的所有分片任务');
  530. assert.ok(data.successList[0] && data.successList[0].Key === filename, '成功舍弃单个文件的所有分片任务');
  531. done();
  532. });
  533. });
  534. });
  535. test('abortUploadTask(),Level=bucket', function (done, assert) {
  536. var filename = '1m.zip';
  537. cos.multipartInit({
  538. Bucket: config.Bucket,
  539. Region: config.Region,
  540. Key: filename,
  541. }, function (err, data) {
  542. cos.abortUploadTask({
  543. Bucket: config.Bucket,
  544. Region: config.Region,
  545. Level: 'bucket',
  546. }, function (err, data) {
  547. var nameExist = false;
  548. data.successList.forEach(function (item) {
  549. if (filename === item.Key) {
  550. nameExist = true;
  551. }
  552. });
  553. assert.ok(data.successList.length >= 1, '成功舍弃Bucket下所有分片任务');
  554. assert.ok(nameExist, '成功舍弃Bucket下所有分片任务');
  555. done();
  556. });
  557. });
  558. });
  559. });
  560. group('headBucket()', function () {
  561. test('headBucket()', function (done, assert) {
  562. cos.headBucket({
  563. Bucket: config.Bucket,
  564. Region: config.Region
  565. }, function (err, data) {
  566. assert.ok(data, '正常获取 head bucket');
  567. done();
  568. });
  569. });
  570. test('headBucket() not exist', function (done, assert) {
  571. cos.headBucket({
  572. Bucket: config.Bucket + Date.now().toString(36),
  573. Region: config.Region
  574. }, function (err, data) {
  575. assert.ok(err, 'bucket 不存在');
  576. done();
  577. });
  578. });
  579. test('deleteBucket()', function (done, assert) {
  580. cos.deleteBucket({
  581. Bucket: config.Bucket + Date.now().toString(36),
  582. Region: config.Region
  583. }, function (err, data) {
  584. assert.ok(err, '正常获取 head bucket');
  585. done();
  586. });
  587. });
  588. test('getBucket()', function (done, assert) {
  589. cos.getBucket({
  590. Bucket: config.Bucket,
  591. Region: config.Region
  592. }, function (err, data) {
  593. assert.equal(true, data.Name === BucketLongName, '能列出 bucket');
  594. assert.equal(data.Contents.constructor, Array, '正常获取 bucket 里的文件列表');
  595. done();
  596. });
  597. });
  598. });
  599. group('putObject()', function () {
  600. test('putObject()', function (done, assert) {
  601. var filename = '1.txt';
  602. var getObjectETag = function (callback) {
  603. setTimeout(function () {
  604. cos.headObject({
  605. Bucket: config.Bucket,
  606. Region: config.Region,
  607. Key: filename,
  608. }, function (err, data) {
  609. callback(data && data.headers && data.headers.etag);
  610. });
  611. }, 2000);
  612. };
  613. var content = Date.now().toString();
  614. var lastPercent = 0;
  615. cos.putObject({
  616. Bucket: config.Bucket,
  617. Region: config.Region,
  618. Key: filename,
  619. Body: util.str2buf(content),
  620. onProgress: function (info) {
  621. lastPercent = info.percent;
  622. },
  623. }, function (err, data) {
  624. if (err) throw err;
  625. assert.ok(data && data.ETag, 'putObject 有返回 ETag');
  626. getObjectETag(function (ETag) {
  627. assert.ok(data.ETag === ETag, 'ArrayBuffer 创建 object');
  628. done();
  629. });
  630. });
  631. });
  632. test('putObject(),string', function (done, assert) {
  633. var filename = '1.txt';
  634. var content = '中文_' + Date.now().toString(36);
  635. var content = '中文';
  636. var lastPercent = 0;
  637. cos.putObject({
  638. Bucket: config.Bucket,
  639. Region: config.Region,
  640. Key: filename,
  641. Body: content,
  642. onProgress: function (info) {
  643. lastPercent = info.percent;
  644. },
  645. }, function (err, data) {
  646. if (err) throw err;
  647. var ETag = data && data.ETag;
  648. assert.ok(ETag, 'putObject 有返回 ETag');
  649. cos.getObject({
  650. Bucket: config.Bucket,
  651. Region: config.Region,
  652. Key: filename,
  653. }, function (err, data) {
  654. assert.ok(data.Body && data.Body === content && (data.headers && data.headers.etag) === ETag);
  655. done();
  656. });
  657. });
  658. });
  659. test('putObject(),string,empty', function (done, assert) {
  660. var content = '';
  661. var lastPercent = 0;
  662. var Key = '1.txt';
  663. cos.putObject({
  664. Bucket: config.Bucket,
  665. Region: config.Region,
  666. Key: Key,
  667. Body: content,
  668. onProgress: function (info) {
  669. lastPercent = info.percent;
  670. },
  671. }, function (err, data) {
  672. if (err) throw err;
  673. var ETag = data && data.ETag;
  674. assert.ok(ETag, 'putObject 有返回 ETag');
  675. cos.getObject({
  676. Bucket: config.Bucket,
  677. Region: config.Region,
  678. Key: Key,
  679. }, function (err, data) {
  680. assert.ok(data.Body === content && (data.headers && data.headers.etag) === ETag);
  681. done();
  682. });
  683. });
  684. });
  685. test('putObject(),特殊二进制字符 ArrayBuffer md5', function (done, assert) {
  686. var lastPercent = 0;
  687. var Key = '1.mp4';
  688. var buf = new ArrayBuffer(8);
  689. var arr = new Uint8Array(buf);
  690. [0xe8,0xaf,0xb4,0x2e,0x70,0x72,0x70,0x72].forEach((v, i) => arr[i] = v);
  691. cos.putObject({
  692. Bucket: config.Bucket,
  693. Region: config.Region,
  694. Key: Key,
  695. Body: buf,
  696. onProgress: function (info) {
  697. lastPercent = info.percent;
  698. },
  699. }, function (err, data) {
  700. if (err) throw err;
  701. var ETag = data && data.ETag;
  702. assert.ok(ETag, 'putObject 有返回 ETag');
  703. cos.getObject({
  704. Bucket: config.Bucket,
  705. Region: config.Region,
  706. Key: Key,
  707. }, function (err, data) {
  708. var isSame = unescape(encodeURIComponent(data.Body)).split(0).every((v, i) => v.charCodeAt(0) === arr[i]);
  709. assert.ok(isSame && (data.headers && data.headers.etag) === ETag);
  710. done();
  711. });
  712. });
  713. });
  714. test('putObject(),特殊二进制字符 中文 string md5', function (done, assert) {
  715. var Key = '1.txt';
  716. var content = '中文';
  717. cos.putObject({
  718. Bucket: config.Bucket,
  719. Region: config.Region,
  720. Key: Key,
  721. Body: content,
  722. }, function (err, data) {
  723. if (err) throw err;
  724. var ETag = data && data.ETag;
  725. assert.ok(ETag, 'putObject 有返回 ETag');
  726. cos.getObject({
  727. Bucket: config.Bucket,
  728. Region: config.Region,
  729. Key: Key,
  730. }, function (err, data) {
  731. var isSame = content === data.Body;
  732. assert.ok(isSame && (data.headers && data.headers.etag) === ETag);
  733. done();
  734. });
  735. });
  736. });
  737. test('putObject(),特殊二进制字符 unescape string md5', function (done, assert) {
  738. var Key = '1.txt';
  739. var content = unescape(encodeURIComponent('中文'));
  740. cos.putObject({
  741. Bucket: config.Bucket,
  742. Region: config.Region,
  743. Key: Key,
  744. Body: content,
  745. }, function (err, data) {
  746. if (err) throw err;
  747. var ETag = data && data.ETag;
  748. assert.ok(ETag, 'putObject 有返回 ETag');
  749. cos.getObject({
  750. Bucket: config.Bucket,
  751. Region: config.Region,
  752. Key: Key,
  753. }, function (err, data) {
  754. var isSame = content === data.Body;
  755. assert.ok(isSame && (data.headers && data.headers.etag) === ETag);
  756. done();
  757. });
  758. });
  759. });
  760. });
  761. group('getObject()', function () {
  762. test('getObject() body', function (done, assert) {
  763. var key = '1.txt';
  764. var content = Date.now().toString();
  765. cos.putObject({
  766. Bucket: config.Bucket,
  767. Region: config.Region,
  768. Key: key,
  769. Body: content,
  770. }, function (err, data) {
  771. cos.getObject({
  772. Bucket: config.Bucket,
  773. Region: config.Region,
  774. Key: key
  775. }, function (err, data) {
  776. if (err) throw err;
  777. var objectContent = data.Body.toString();
  778. assert.ok(data.headers['content-length'] === '' + content.length);
  779. assert.ok(objectContent === content);
  780. done();
  781. });
  782. });
  783. });
  784. });
  785. group('Key 特殊字符', function () {
  786. test('Key 特殊字符', function (done, assert) {
  787. cos.putObject({
  788. Bucket: config.Bucket,
  789. Region: config.Region,
  790. Key: '(!\'*) "#$%&+,-./0123456789:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
  791. Body: Date.now().toString()
  792. }, function (err, data) {
  793. if (err) throw err;
  794. assert.ok(data, 'putObject 特殊字符的 Key 能通过');
  795. done();
  796. });
  797. });
  798. });
  799. group('putObjectCopy() 1', function () {
  800. test('putObjectCopy() 1', function (done, assert) {
  801. var content = Date.now().toString(36);
  802. cos.putObject({
  803. Bucket: config.Bucket,
  804. Region: config.Region,
  805. Key: '1.txt',
  806. Body: content,
  807. }, function (err, data) {
  808. var ETag = data.ETag;
  809. cos.deleteObject({
  810. Bucket: config.Bucket,
  811. Region: config.Region,
  812. Key: '1.copy.txt',
  813. }, function (err, data) {
  814. cos.putObjectCopy({
  815. Bucket: config.Bucket,
  816. Region: config.Region,
  817. Key: '1.copy.txt',
  818. CopySource: BucketLongName + '.cos.' + config.Region + '.myqcloud.com/1.txt',
  819. }, function (err, data) {
  820. cos.headObject({
  821. Bucket: config.Bucket,
  822. Region: config.Region,
  823. Key: '1.copy.txt',
  824. }, function (err, data) {
  825. assert.ok(data.headers && data.headers.etag === ETag, '成功复制文件');
  826. done();
  827. });
  828. });
  829. });
  830. });
  831. });
  832. });
  833. group('putObjectCopy()', function () {
  834. var filename = '1.txt';
  835. test('正常复制 object', function (done, assert) {
  836. cos.putObjectCopy({
  837. Bucket: config.Bucket,
  838. Region: config.Region,
  839. Key: '1.copy.txt',
  840. CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + filename,
  841. }, function (err, data) {
  842. assert.ok(!err);
  843. assert.ok(data.ETag.length > 0);
  844. done();
  845. });
  846. });
  847. test('捕获 object 异常', function (done, assert) {
  848. var errFileName = '12345.txt';
  849. cos.putObjectCopy({
  850. Bucket: config.Bucket,
  851. Region: config.Region,
  852. Key: '1.copy.txt',
  853. CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + errFileName,
  854. }, function (err, data) {
  855. assert.equal(true, err.statusCode === 404);
  856. assert.equal(true, err.error.Code === 'NoSuchKey')
  857. done();
  858. });
  859. });
  860. });
  861. group('sliceCopyFile()', function () {
  862. var filename = 'bigger.zip';
  863. var Key = 'bigger.copy.zip';
  864. test('正常分片复制 object', function (done, assert) {
  865. prepareBigObject(true, function () {
  866. cos.headObject({
  867. Bucket: config.Bucket,
  868. Region: config.Region,
  869. Key: filename,
  870. }, function (err, data1) {
  871. if (err) throw err;
  872. cos.sliceCopyFile({
  873. Bucket: config.Bucket,
  874. Region: config.Region,
  875. Key: Key,
  876. CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/'+ filename,
  877. SliceSize: 5 * 1024 * 1024,
  878. },function (err, data) {
  879. if (err) throw err;
  880. assert.ok(data.ETag.length > 0);
  881. cos.headObject({
  882. Bucket: config.Bucket,
  883. Region: config.Region,
  884. Key: Key,
  885. }, function (err, data2) {
  886. if (err) throw err;
  887. delete data1.VersionId;
  888. delete data2.VersionId;
  889. delete data1.headers['x-cos-request-id'];
  890. delete data2.headers['x-cos-request-id'];
  891. delete data1.headers['x-cos-version-id'];
  892. delete data2.headers['x-cos-version-id'];
  893. delete data1.headers['last-modified'];
  894. delete data2.headers['last-modified'];
  895. delete data1.headers['date'];
  896. delete data2.headers['date'];
  897. delete data1.headers['etag'];
  898. delete data2.headers['etag'];
  899. delete data1.ETag;
  900. delete data2.ETag;
  901. assert.ok(comparePlainObject(data1, data2));
  902. done();
  903. });
  904. });
  905. });
  906. });
  907. });
  908. test('单片复制 object', function (done, assert) {
  909. setTimeout(function () {
  910. prepareBigObject(true, function () {
  911. cos.headObject({
  912. Bucket: config.Bucket,
  913. Region: config.Region,
  914. Key: filename,
  915. }, function (err, data1) {
  916. if (err) throw err;
  917. cos.sliceCopyFile({
  918. Bucket: config.Bucket,
  919. Region: config.Region,
  920. Key: Key,
  921. CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + filename,
  922. SliceSize: 10 * 1024 * 1024,
  923. }, function (err, data) {
  924. if (err) throw err;
  925. assert.ok(data.ETag.length > 0);
  926. setTimeout(function () {
  927. cos.headObject({
  928. Bucket: config.Bucket,
  929. Region: config.Region,
  930. Key: Key,
  931. }, function (err, data2) {
  932. if (err) throw err;
  933. delete data1.VersionId;
  934. delete data2.VersionId;
  935. delete data1.headers['x-cos-request-id'];
  936. delete data2.headers['x-cos-request-id'];
  937. delete data1.headers['x-cos-version-id'];
  938. delete data2.headers['x-cos-version-id'];
  939. delete data1.headers['last-modified'];
  940. delete data2.headers['last-modified'];
  941. delete data1.headers['date'];
  942. delete data2.headers['date'];
  943. assert.ok(comparePlainObject(data1, data2));
  944. done();
  945. });
  946. }, 2000);
  947. });
  948. });
  949. });
  950. }, 2000);
  951. });
  952. });
  953. group('deleteMultipleObject', function () {
  954. test('deleteMultipleObject()', function (done, assert) {
  955. var content = Date.now().toString(36);
  956. cos.putObject({
  957. Bucket: config.Bucket,
  958. Region: config.Region,
  959. Key: '1.txt',
  960. Body: content,
  961. }, function (err, data) {
  962. cos.putObject({
  963. Bucket: config.Bucket,
  964. Region: config.Region,
  965. Key: '2.txt',
  966. Body: content,
  967. }, function (err, data) {
  968. cos.deleteMultipleObject({
  969. Bucket: config.Bucket,
  970. Region: config.Region,
  971. Objects: [
  972. {Key: '1.txt'},
  973. {Key: '2.txt'},
  974. ],
  975. }, function (err, data) {
  976. assert.ok(data.Deleted.length === 2);
  977. cos.headObject({
  978. Bucket: config.Bucket,
  979. Region: config.Region,
  980. Key: '1.txt',
  981. }, function (err, data) {
  982. assert.ok(err.statusCode === 404, '1.txt 删除成功');
  983. cos.headObject({
  984. Bucket: config.Bucket,
  985. Region: config.Region,
  986. Key: '2.txt',
  987. }, function (err, data) {
  988. assert.ok(err.statusCode === 404, '2.txt 删除成功');
  989. done();
  990. });
  991. });
  992. });
  993. });
  994. });
  995. });
  996. });
  997. group('BucketAcl', function () {
  998. var AccessControlPolicy = {
  999. "Owner": {
  1000. "ID": 'qcs::cam::uin/10001:uin/10001' // 10001 是 QQ 号
  1001. },
  1002. "Grants": [{
  1003. "Grantee": {
  1004. "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
  1005. },
  1006. "Permission": "READ"
  1007. }]
  1008. };
  1009. var AccessControlPolicy2 = {
  1010. "Owner": {
  1011. "ID": 'qcs::cam::uin/10001:uin/10001' // 10001 是 QQ 号
  1012. },
  1013. "Grant": {
  1014. "Grantee": {
  1015. "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
  1016. },
  1017. "Permission": "READ"
  1018. }
  1019. };
  1020. test('putBucketAcl() header ACL:private', function (done, assert) {
  1021. cos.putBucketAcl({
  1022. Bucket: config.Bucket,
  1023. Region: config.Region,
  1024. ACL: 'private'
  1025. }, function (err, data) {
  1026. assert.ok(!err, 'putBucketAcl 成功');
  1027. cos.getBucketAcl({
  1028. Bucket: config.Bucket,
  1029. Region: config.Region
  1030. }, function (err, data) {
  1031. AccessControlPolicy.Owner.ID = data.Owner.ID;
  1032. AccessControlPolicy2.Owner.ID = data.Owner.ID;
  1033. assert.ok(data.ACL === 'private' || data.ACL === 'default');
  1034. done();
  1035. });
  1036. });
  1037. });
  1038. test('putBucketAcl() header ACL:public-read', function (done, assert) {
  1039. cos.putBucketAcl({
  1040. Bucket: config.Bucket,
  1041. Region: config.Region,
  1042. ACL: 'public-read',
  1043. }, function (err, data) {
  1044. assert.ok(!err, 'putBucketAcl 成功');
  1045. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region}, function (err, data) {
  1046. assert.ok(data.ACL === 'public-read');
  1047. done();
  1048. });
  1049. });
  1050. });
  1051. test('putBucketAcl() header ACL:public-read-write', function (done, assert) {
  1052. cos.putBucketAcl({
  1053. Bucket: config.Bucket,
  1054. Region: config.Region,
  1055. ACL: 'public-read-write',
  1056. }, function (err, data) {
  1057. assert.ok(!err, 'putBucketAcl 成功');
  1058. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region}, function (err, data) {
  1059. assert.ok(data.ACL === 'public-read-write');
  1060. done();
  1061. });
  1062. });
  1063. });
  1064. test('putBucketAcl() header GrantRead:1001,1002', function (done, assert) {
  1065. var GrantRead = 'id="qcs::cam::uin/1001:uin/1001", id="qcs::cam::uin/1002:uin/1002"';
  1066. cos.putBucketAcl({
  1067. Bucket: config.Bucket,
  1068. Region: config.Region,
  1069. GrantRead: GrantRead,
  1070. }, function (err, data) {
  1071. assert.ok(!err, 'putBucketAcl 成功');
  1072. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region}, function (err, data) {
  1073. assert.ok(data.GrantRead = GrantRead);
  1074. done();
  1075. });
  1076. });
  1077. });
  1078. test('putBucketAcl() header GrantWrite:1001,1002', function (done, assert) {
  1079. var GrantWrite = 'id="qcs::cam::uin/1001:uin/1001", id="qcs::cam::uin/1002:uin/1002"';
  1080. cos.putBucketAcl({
  1081. Bucket: config.Bucket,
  1082. Region: config.Region,
  1083. GrantWrite: GrantWrite,
  1084. }, function (err, data) {
  1085. assert.ok(!err, 'putBucketAcl 成功');
  1086. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region}, function (err, data) {
  1087. assert.ok(data.GrantWrite = GrantWrite);
  1088. done();
  1089. });
  1090. });
  1091. });
  1092. test('putBucketAcl() header GrantFullControl:1001,1002', function (done, assert) {
  1093. var GrantFullControl = 'id="qcs::cam::uin/1001:uin/1001", id="qcs::cam::uin/1002:uin/1002"';
  1094. cos.putBucketAcl({
  1095. Bucket: config.Bucket,
  1096. Region: config.Region,
  1097. GrantFullControl: GrantFullControl,
  1098. }, function (err, data) {
  1099. assert.ok(!err, 'putBucketAcl 成功');
  1100. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region}, function (err, data) {
  1101. assert.ok(data.GrantFullControl = GrantFullControl);
  1102. done();
  1103. });
  1104. });
  1105. });
  1106. test('putBucketAcl() header ACL:public-read, GrantFullControl:1001,1002', function (done, assert) {
  1107. var GrantFullControl = 'id="qcs::cam::uin/1001:uin/1001", id="qcs::cam::uin/1002:uin/1002"';
  1108. cos.putBucketAcl({
  1109. Bucket: config.Bucket,
  1110. Region: config.Region,
  1111. GrantFullControl: GrantFullControl,
  1112. ACL: 'public-read',
  1113. }, function (err, data) {
  1114. assert.ok(!err, 'putBucketAcl 成功');
  1115. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region}, function (err, data) {
  1116. assert.ok(data.GrantFullControl = GrantFullControl);
  1117. assert.ok(data.ACL === 'public-read');
  1118. done();
  1119. });
  1120. });
  1121. });
  1122. test('putBucketAcl() xml', function (done, assert) {
  1123. cos.putBucketAcl({
  1124. Bucket: config.Bucket,
  1125. Region: config.Region,
  1126. AccessControlPolicy: AccessControlPolicy
  1127. }, function (err, data) {
  1128. assert.ok(!err, 'putBucketAcl 成功');
  1129. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region}, function (err, data) {
  1130. assert.ok(data.Grants.length === 1);
  1131. assert.ok(data.Grants[0] && data.Grants[0].Grantee.ID === 'qcs::cam::uin/10002:uin/10002', '设置 AccessControlPolicy ID 正确');
  1132. assert.ok(data.Grants[0] && data.Grants[0].Permission === 'READ', '设置 AccessControlPolicy Permission 正确');
  1133. done();
  1134. });
  1135. });
  1136. });
  1137. test('putBucketAcl() xml2', function (done, assert) {
  1138. cos.putBucketAcl({
  1139. Bucket: config.Bucket,
  1140. Region: config.Region,
  1141. AccessControlPolicy: AccessControlPolicy2,
  1142. }, function (err, data) {
  1143. assert.ok(!err, 'putBucketAcl 成功');
  1144. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region}, function (err, data) {
  1145. assert.ok(data.Grants.length === 1);
  1146. assert.ok(data.Grants[0] && data.Grants[0].Grantee.ID === 'qcs::cam::uin/10002:uin/10002');
  1147. assert.ok(data.Grants[0] && data.Grants[0].Permission === 'READ');
  1148. done();
  1149. });
  1150. });
  1151. });
  1152. test('putBucketAcl() decodeAcl', function (done, assert) {
  1153. cos.getBucketAcl({
  1154. Bucket: config.Bucket,
  1155. Region: config.Region
  1156. }, function (err, data) {
  1157. cos.putBucketAcl({
  1158. Bucket: config.Bucket,
  1159. Region: config.Region,
  1160. GrantFullControl: data.GrantFullControl,
  1161. GrantWrite: data.GrantWrite,
  1162. GrantRead: data.GrantRead,
  1163. ACL: data.ACL,
  1164. }, function (err, data) {
  1165. assert.ok(data);
  1166. done();
  1167. });
  1168. });
  1169. });
  1170. });
  1171. group('ObjectAcl', function () {
  1172. var AccessControlPolicy = {
  1173. "Owner": {
  1174. "ID": 'qcs::cam::uin/10001:uin/10001' // 10001 是 QQ 号
  1175. },
  1176. "Grants": [{
  1177. "Grantee": {
  1178. "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
  1179. },
  1180. "Permission": "READ"
  1181. }]
  1182. };
  1183. var AccessControlPolicy2 = {
  1184. "Owner": {
  1185. "ID": 'qcs::cam::uin/10001:uin/10001' // 10001 是 QQ 号
  1186. },
  1187. "Grant": {
  1188. "Grantee": {
  1189. "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
  1190. },
  1191. "Permission": "READ"
  1192. }
  1193. };
  1194. test('putObjectAcl() header ACL:private', function (done, assert) {
  1195. cos.putObject({
  1196. Bucket: config.Bucket,
  1197. Region: config.Region,
  1198. Key: '1.txt',
  1199. Body: 'hello!',
  1200. }, function (err, data) {
  1201. assert.ok(!err);
  1202. cos.putObjectAcl({
  1203. Bucket: config.Bucket,
  1204. Region: config.Region,
  1205. ACL: 'private',
  1206. Key: '1.txt',
  1207. }, function (err, data) {
  1208. assert.ok(!err, 'putObjectAcl 成功');
  1209. cos.getObjectAcl({
  1210. Bucket: config.Bucket,
  1211. Region: config.Region,
  1212. Key: '1.txt'
  1213. }, function (err, data) {
  1214. assert.ok(data.ACL = 'private');
  1215. AccessControlPolicy.Owner.ID = data.Owner.ID;
  1216. AccessControlPolicy2.Owner.ID = data.Owner.ID;
  1217. assert.ok(data.Grants.length === 1);
  1218. done();
  1219. });
  1220. });
  1221. });
  1222. });
  1223. test('putObjectAcl() header ACL:default', function (done, assert) {
  1224. cos.putObjectAcl({
  1225. Bucket: config.Bucket,
  1226. Region: config.Region,
  1227. ACL: 'default',
  1228. Key: '1.txt',
  1229. }, function (err, data) {
  1230. assert.ok(!err, 'putObjectAcl 成功');
  1231. cos.getObjectAcl({
  1232. Bucket: config.Bucket,
  1233. Region: config.Region,
  1234. Key: '1.txt'
  1235. }, function (err, data) {
  1236. assert.ok(data.ACL = 'default');
  1237. done();
  1238. });
  1239. });
  1240. });
  1241. test('putObjectAcl() header ACL:public-read', function (done, assert) {
  1242. cos.putObjectAcl({
  1243. Bucket: config.Bucket,
  1244. Region: config.Region,
  1245. ACL: 'public-read',
  1246. Key: '1.txt',
  1247. }, function (err, data) {
  1248. assert.ok(!err, 'putObjectAcl 成功');
  1249. cos.getObjectAcl({Bucket: config.Bucket, Region: config.Region, Key: '1.txt'}, function (err, data) {
  1250. assert.ok(data.ACL = 'public-read');
  1251. done();
  1252. });
  1253. });
  1254. });
  1255. // Object 不再支持修改写权限
  1256. // test('putObjectAcl() header ACL:public-read-write', function (done, assert) {
  1257. // cos.putObjectAcl({
  1258. // Bucket: config.Bucket,
  1259. // Region: config.Region,
  1260. // ACL: 'public-read-write',
  1261. // Key: '1.txt',
  1262. // }, function (err, data) {
  1263. // assert.ok(!err, 'putObjectAcl 成功');
  1264. // cos.getObjectAcl({Bucket: config.Bucket, Region: config.Region, Key: '1.txt'}, function (err, data) {
  1265. // assert.ok(data.ACL = 'public-read-write');
  1266. // done();
  1267. // });
  1268. // });
  1269. // });
  1270. test('putObjectAcl() header GrantRead:1001,1002', function (done, assert) {
  1271. var GrantRead = 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"';
  1272. cos.putObjectAcl({
  1273. Bucket: config.Bucket,
  1274. Region: config.Region,
  1275. GrantRead: GrantRead,
  1276. Key: '1.txt',
  1277. }, function (err, data) {
  1278. assert.ok(!err, 'putObjectAcl 成功');
  1279. cos.getObjectAcl({Bucket: config.Bucket, Region: config.Region, Key: '1.txt'}, function (err, data) {
  1280. assert.ok(data.GrantRead = GrantRead);
  1281. done();
  1282. });
  1283. });
  1284. });
  1285. // Object 不再支持修改写权限
  1286. // test('putObjectAcl() header GrantWrite:1001,1002', function (done, assert) {
  1287. // var GrantWrite = 'id="qcs::cam::uin/1001:uin/1001", id="qcs::cam::uin/1002:uin/1002"';
  1288. // cos.putObjectAcl({
  1289. // Bucket: config.Bucket,
  1290. // Region: config.Region,
  1291. // GrantWrite: GrantWrite,
  1292. // Key: '1.txt',
  1293. // }, function (err, data) {
  1294. // assert.ok(!err, 'putObjectAcl 成功');
  1295. // cos.getObjectAcl({Bucket: config.Bucket, Region: config.Region, Key: '1.txt'}, function (err, data) {
  1296. // assert.ok(data.GrantWrite = GrantWrite);
  1297. // done();
  1298. // });
  1299. // });
  1300. // });
  1301. test('putObjectAcl() header GrantFullControl:1001,1002', function (done, assert) {
  1302. var GrantFullControl = 'id="qcs::cam::uin/1001:uin/1001", id="qcs::cam::uin/1002:uin/1002"';
  1303. cos.putObjectAcl({
  1304. Bucket: config.Bucket,
  1305. Region: config.Region,
  1306. GrantFullControl: GrantFullControl,
  1307. Key: '1.txt',
  1308. }, function (err, data) {
  1309. assert.ok(!err, 'putObjectAcl 成功');
  1310. cos.getObjectAcl({Bucket: config.Bucket, Region: config.Region, Key: '1.txt'}, function (err, data) {
  1311. assert.ok(data.GrantFullControl = GrantFullControl);
  1312. done();
  1313. });
  1314. });
  1315. });
  1316. test('putObjectAcl() header ACL:public-read, GrantRead:1001,1002', function (done, assert) {
  1317. var GrantFullControl = 'id="qcs::cam::uin/1001:uin/1001", id="qcs::cam::uin/1002:uin/1002"';
  1318. cos.putObjectAcl({
  1319. Bucket: config.Bucket,
  1320. Region: config.Region,
  1321. GrantFullControl: GrantFullControl,
  1322. ACL: 'public-read',
  1323. Key: '1.txt',
  1324. }, function (err, data) {
  1325. assert.ok(!err, 'putObjectAcl 成功');
  1326. cos.getObjectAcl({Bucket: config.Bucket, Region: config.Region, Key: '1.txt'}, function (err, data) {
  1327. assert.ok(data.GrantFullControl = GrantFullControl);
  1328. assert.ok(data.ACL = 'public-read');
  1329. done();
  1330. });
  1331. });
  1332. });
  1333. test('putObjectAcl() xml', function (done, assert) {
  1334. cos.putObjectAcl({
  1335. Bucket: config.Bucket,
  1336. Region: config.Region,
  1337. AccessControlPolicy: AccessControlPolicy,
  1338. Key: '1.txt',
  1339. }, function (err, data) {
  1340. assert.ok(!err, 'putObjectAcl 成功');
  1341. cos.getBucketAcl({Bucket: config.Bucket, Region: config.Region, Key: '1.txt'}, function (err, data) {
  1342. assert.ok(data.Grants.length === 1);
  1343. assert.ok(data.Grants[0] && data.Grants[0].Grantee.ID === 'qcs::cam::uin/10002:uin/10002', '设置 AccessControlPolicy ID 正确');
  1344. assert.ok(data.Grants[0] && data.Grants[0].Permission === 'READ', '设置 AccessControlPolicy Permission 正确');
  1345. done();
  1346. });
  1347. });
  1348. });
  1349. test('putObjectAcl() xml2', function (done, assert) {
  1350. cos.putObjectAcl({
  1351. Bucket: config.Bucket,
  1352. Region: config.Region,
  1353. AccessControlPolicy: AccessControlPolicy2,
  1354. Key: '1.txt',
  1355. }, function (err, data) {
  1356. assert.ok(!err, 'putObjectAcl 成功');
  1357. cos.getObjectAcl({
  1358. Bucket: config.Bucket,
  1359. Region: config.Region,
  1360. Key: '1.txt'
  1361. }, function (err, data) {
  1362. assert.ok(data.Grants.length === 1);
  1363. assert.ok(data.Grants[0] && data.Grants[0].Grantee.ID === 'qcs::cam::uin/10002:uin/10002', 'ID 正确');
  1364. assert.ok(data.Grants[0] && data.Grants[0].Permission === 'READ', 'Permission 正确');
  1365. done();
  1366. });
  1367. });
  1368. });
  1369. test('putObjectAcl() decodeAcl', function (done, assert) {
  1370. cos.getObjectAcl({
  1371. Bucket: config.Bucket,
  1372. Region: config.Region,
  1373. Key: '1.txt'
  1374. }, function (err, data) {
  1375. cos.putObjectAcl({
  1376. Bucket: config.Bucket,
  1377. Region: config.Region,
  1378. Key: '1.txt',
  1379. GrantFullControl: data.GrantFullControl,
  1380. GrantWrite: data.GrantWrite,
  1381. GrantRead: data.GrantRead,
  1382. ACL: data.ACL,
  1383. }, function (err, data) {
  1384. assert.ok(data);
  1385. done();
  1386. });
  1387. });
  1388. });
  1389. });
  1390. group('BucketCors', function () {
  1391. var CORSRules = [{
  1392. "AllowedOrigins": ["*"],
  1393. "AllowedMethods": ["GET", "POST", "PUT", "DELETE", "HEAD"],
  1394. "AllowedHeaders": ["*", 'test-' + Date.now().toString(36)],
  1395. "ExposeHeaders": [
  1396. 'etag',
  1397. 'date',
  1398. 'content-length',
  1399. 'expires',
  1400. 'cache-control',
  1401. 'content-disposition',
  1402. 'content-encoding',
  1403. 'x-cos-acl',
  1404. 'x-cos-version-id',
  1405. 'x-cos-request-id',
  1406. 'x-cos-delete-marker',
  1407. 'x-cos-server-side-encryption',
  1408. 'x-cos-storage-class',
  1409. 'x-cos-acl',
  1410. 'x-cos-meta-test',
  1411. 'x-cos-tagging-count',
  1412. ],
  1413. "MaxAgeSeconds": "5"
  1414. }];
  1415. var CORSRulesMulti = [{
  1416. "AllowedOrigins": ["*"],
  1417. "AllowedMethods": ["GET", "POST", "PUT", "DELETE", "HEAD"],
  1418. "AllowedHeaders": ["*"],
  1419. "ExposeHeaders": ["ETag", "Date", "Content-Length", "x-cos-acl", "x-cos-version-id", "x-cos-request-id", "x-cos-delete-marker", "x-cos-server-side-encryption"],
  1420. "MaxAgeSeconds": "5"
  1421. }, {
  1422. "AllowedOrigins": ["http://qq.com", "http://qcloud.com"],
  1423. "AllowedMethods": ["GET", "POST", "PUT", "DELETE", "HEAD"],
  1424. "AllowedHeaders": ["*"],
  1425. "ExposeHeaders": ["ETag", "Date", "Content-Length", "x-cos-acl", "x-cos-version-id", "x-cos-request-id", "x-cos-delete-marker", "x-cos-server-side-encryption"],
  1426. "MaxAgeSeconds": "5"
  1427. }];
  1428. test('putBucketCors() old CORSConfiguration', function (done, assert) {
  1429. CORSRules[0].AllowedHeaders[1] = 'test-' + Date.now().toString(36);
  1430. cos.putBucketCors({
  1431. Bucket: config.Bucket,
  1432. Region: config.Region,
  1433. CORSConfiguration: {
  1434. CORSRules: CORSRules
  1435. }
  1436. }, function (err, data) {
  1437. assert.ok(!err);
  1438. setTimeout(function () {
  1439. cos.getBucketCors({
  1440. Bucket: config.Bucket,
  1441. Region: config.Region
  1442. }, function (err, data) {
  1443. assert.ok(comparePlainObject(CORSRules, data.CORSRules));
  1444. done();
  1445. });
  1446. }, 2000);
  1447. });
  1448. });
  1449. test('putBucketCors() multi', function (done, assert) {
  1450. cos.putBucketCors({
  1451. Bucket: config.Bucket,
  1452. Region: config.Region,
  1453. CORSConfiguration: {
  1454. CORSRules: CORSRulesMulti
  1455. }
  1456. }, function (err, data) {
  1457. assert.ok(!err);
  1458. setTimeout(function () {
  1459. cos.getBucketCors({
  1460. Bucket: config.Bucket,
  1461. Region: config.Region
  1462. }, function (err, data) {
  1463. assert.ok(comparePlainObject(CORSRulesMulti, data.CORSRules));
  1464. done();
  1465. });
  1466. }, 2000);
  1467. });
  1468. });
  1469. test('putBucketCors() old CORSRules', function (done, assert) {
  1470. CORSRules[0].AllowedHeaders[1] = 'test-' + Date.now().toString(36);
  1471. cos.putBucketCors({
  1472. Bucket: config.Bucket,
  1473. Region: config.Region,
  1474. CORSRules: CORSRules
  1475. }, function (err, data) {
  1476. assert.ok(!err);
  1477. setTimeout(function () {
  1478. cos.getBucketCors({
  1479. Bucket: config.Bucket,
  1480. Region: config.Region
  1481. }, function (err, data) {
  1482. assert.ok(comparePlainObject(CORSRules, data.CORSRules));
  1483. done();
  1484. });
  1485. }, 2000);
  1486. });
  1487. });
  1488. test('putBucketCors(),getBucketCors()', function (done, assert) {
  1489. CORSRules[0].AllowedHeaders = ['*'];
  1490. cos.putBucketCors({
  1491. Bucket: config.Bucket,
  1492. Region: config.Region,
  1493. CORSConfiguration: {
  1494. CORSRules: CORSRules
  1495. }
  1496. }, function (err, data) {
  1497. assert.ok(!err);
  1498. setTimeout(function () {
  1499. cos.getBucketCors({
  1500. Bucket: config.Bucket,
  1501. Region: config.Region
  1502. }, function (err, data) {
  1503. assert.ok(comparePlainObject(CORSRules, data.CORSRules));
  1504. done();
  1505. });
  1506. }, 2000);
  1507. });
  1508. });
  1509. });
  1510. group('BucketTagging', function () {
  1511. var Tags = [
  1512. {Key: "k1", Value: "v1"}
  1513. ];
  1514. var TagsMulti = [
  1515. {Key: "k1", Value: "v1"},
  1516. {Key: "k2", Value: "v2"},
  1517. ];
  1518. test('putBucketTagging(),getBucketTagging()', function (done, assert) {
  1519. Tags[0].Value = Date.now().toString(36);
  1520. cos.putBucketTagging({
  1521. Bucket: config.Bucket,
  1522. Region: config.Region,
  1523. Tagging: {
  1524. Tags: Tags
  1525. }
  1526. }, function (err, data) {
  1527. assert.ok(!err);
  1528. setTimeout(function () {
  1529. cos.getBucketTagging({
  1530. Bucket: config.Bucket,
  1531. Region: config.Region
  1532. }, function (err, data) {
  1533. assert.ok(comparePlainObject(Tags, data.Tags));
  1534. done();
  1535. });
  1536. }, 1000);
  1537. });
  1538. });
  1539. test('deleteBucketTagging()', function (done, assert) {
  1540. cos.deleteBucketTagging({
  1541. Bucket: config.Bucket,
  1542. Region: config.Region
  1543. }, function (err, data) {
  1544. assert.ok(!err);
  1545. setTimeout(function () {
  1546. cos.getBucketTagging({
  1547. Bucket: config.Bucket,
  1548. Region: config.Region
  1549. }, function (err, data) {
  1550. assert.ok(comparePlainObject([], data.Tags));
  1551. done();
  1552. });
  1553. }, 1000);
  1554. });
  1555. });
  1556. test('putBucketTagging() multi', function (done, assert) {
  1557. Tags[0].Value = Date.now().toString(36);
  1558. cos.putBucketTagging({
  1559. Bucket: config.Bucket,
  1560. Region: config.Region,
  1561. Tagging: {
  1562. Tags: TagsMulti
  1563. }
  1564. }, function (err, data) {
  1565. assert.ok(!err);
  1566. setTimeout(function () {
  1567. cos.getBucketTagging({
  1568. Bucket: config.Bucket,
  1569. Region: config.Region
  1570. }, function (err, data) {
  1571. assert.ok(comparePlainObject(TagsMulti, data.Tags));
  1572. done();
  1573. });
  1574. }, 1000);
  1575. });
  1576. });
  1577. });
  1578. group('BucketPolicy', function () {
  1579. var Prefix = Date.now().toString(36);
  1580. var Policy = {
  1581. "version": "2.0",
  1582. "principal": {"qcs": ["qcs::cam::uin/10001:uin/10001"]}, // 这里的 10001 是 QQ 号
  1583. "statement": [{
  1584. "effect": "allow",
  1585. "action": [
  1586. "name/cos:GetBucket",
  1587. "name/cos:PutObject",
  1588. "name/cos:PostObject",
  1589. "name/cos:PutObjectCopy",
  1590. "name/cos:InitiateMultipartUpload",
  1591. "name/cos:UploadPart",
  1592. "name/cos:UploadPartCopy",
  1593. "name/cos:CompleteMultipartUpload",
  1594. "name/cos:AbortMultipartUpload",
  1595. "name/cos:AppendObject"
  1596. ],
  1597. "resource": ["qcs::cos:" + config.Region + ":uid/" + AppId + ":" + BucketLongName + ".cos." + config.Region + ".myqcloud.com//" + AppId + "/" + BucketShortName + "/" + Prefix + "/*"] // 1250000000 是 appid
  1598. }]
  1599. };
  1600. test('putBucketPolicy(),getBucketPolicy()', function (done, assert) {
  1601. cos.putBucketPolicy({
  1602. Bucket: config.Bucket,
  1603. Region: config.Region,
  1604. Policy: Policy
  1605. }, function (err, data) {
  1606. assert.ok(!err);
  1607. cos.getBucketPolicy({
  1608. Bucket: config.Bucket,
  1609. Region: config.Region
  1610. }, function (err, data) {
  1611. assert.ok(Policy, data.Policy);
  1612. done();
  1613. });
  1614. });
  1615. });
  1616. test('putBucketPolicy() s3', function (done, assert) {
  1617. cos.putBucketPolicy({
  1618. Bucket: config.Bucket,
  1619. Region: config.Region,
  1620. Policy: JSON.stringify(Policy)
  1621. }, function (err, data) {
  1622. assert.ok(!err);
  1623. cos.getBucketPolicy({
  1624. Bucket: config.Bucket,
  1625. Region: config.Region
  1626. }, function (err, data) {
  1627. assert.ok(Policy, data.Policy);
  1628. done();
  1629. });
  1630. });
  1631. });
  1632. });
  1633. group('BucketLocation', function () {
  1634. test('getBucketLocation()', function (done, assert) {
  1635. cos.getBucketLocation({
  1636. Bucket: config.Bucket,
  1637. Region: config.Region
  1638. }, function (err, data) {
  1639. var map1 = {
  1640. 'tianjin': 'ap-beijing-1',
  1641. 'cn-south-2': 'ap-guangzhou-2',
  1642. 'cn-south': 'ap-guangzhou',
  1643. 'cn-east': 'ap-shanghai',
  1644. 'cn-southwest': 'ap-chengdu',
  1645. };
  1646. var map2 = {
  1647. 'ap-beijing-1': 'tianjin',
  1648. 'ap-guangzhou-2': 'cn-south-2',
  1649. 'ap-guangzhou': 'cn-south',
  1650. 'ap-shanghai': 'cn-east',
  1651. 'ap-chengdu': 'cn-southwest',
  1652. };
  1653. assert.ok(data.LocationConstraint === config.Region || data.LocationConstraint === map1[config.Region] ||
  1654. data.LocationConstraint === map2[config.Region]);
  1655. done();
  1656. });
  1657. });
  1658. });
  1659. group('BucketLifecycle', function () {
  1660. var Rules = [{
  1661. 'ID': '1',
  1662. 'Filter': {
  1663. 'Prefix': 'test_' + Date.now().toString(36),
  1664. },
  1665. 'Status': 'Enabled',
  1666. 'Transition': {
  1667. 'Date': '2018-07-29T16:00:00.000Z',
  1668. 'StorageClass': 'STANDARD_IA'
  1669. }
  1670. }];
  1671. var RulesMulti = [{
  1672. 'ID': '1',
  1673. 'Filter': {
  1674. 'Prefix': 'test1_' + Date.now().toString(36),
  1675. },
  1676. 'Status': 'Enabled',
  1677. 'Transition': {
  1678. 'Date': '2018-07-29T16:00:00.000Z',
  1679. 'StorageClass': 'STANDARD_IA'
  1680. }
  1681. }, {
  1682. 'ID': '2',
  1683. 'Filter': {
  1684. 'Prefix': 'test2_' + Date.now().toString(36),
  1685. },
  1686. 'Status': 'Enabled',
  1687. 'Transition': {
  1688. 'Date': '2018-07-29T16:00:00.000Z',
  1689. 'StorageClass': 'STANDARD_IA'
  1690. }
  1691. }];
  1692. test('deleteBucketLifecycle()', function (done, assert) {
  1693. cos.deleteBucketLifecycle({
  1694. Bucket: config.Bucket,
  1695. Region: config.Region
  1696. }, function (err, data) {
  1697. assert.ok(!err);
  1698. setTimeout(function () {
  1699. cos.getBucketLifecycle({
  1700. Bucket: config.Bucket,
  1701. Region: config.Region
  1702. }, function (err, data) {
  1703. assert.ok(comparePlainObject([], data.Rules));
  1704. done();
  1705. });
  1706. }, 2000);
  1707. });
  1708. });
  1709. test('putBucketLifecycle(),getBucketLifecycle()', function (done, assert) {
  1710. Rules[0].Filter.Prefix = 'test_' + Date.now().toString(36);
  1711. cos.putBucketLifecycle({
  1712. Bucket: config.Bucket,
  1713. Region: config.Region,
  1714. LifecycleConfiguration: {
  1715. Rules: Rules
  1716. }
  1717. }, function (err, data) {
  1718. assert.ok(!err);
  1719. setTimeout(function () {
  1720. cos.getBucketLifecycle({
  1721. Bucket: config.Bucket,
  1722. Region: config.Region
  1723. }, function (err, data) {
  1724. assert.ok(comparePlainObject(Rules, data && data.Rules));
  1725. done();
  1726. });
  1727. }, 2000);
  1728. });
  1729. });
  1730. test('putBucketLifecycle() multi', function (done, assert) {
  1731. Rules[0].Filter.Prefix = 'test_' + Date.now().toString(36);
  1732. cos.putBucketLifecycle({
  1733. Bucket: config.Bucket,
  1734. Region: config.Region,
  1735. LifecycleConfiguration: {
  1736. Rules: RulesMulti
  1737. }
  1738. }, function (err, data) {
  1739. assert.ok(!err);
  1740. setTimeout(function () {
  1741. cos.getBucketLifecycle({
  1742. Bucket: config.Bucket,
  1743. Region: config.Region
  1744. }, function (err, data) {
  1745. assert.ok(comparePlainObject(RulesMulti, data.Rules));
  1746. done();
  1747. });
  1748. }, 2000);
  1749. });
  1750. });
  1751. });
  1752. group('BucketWebsite', function () {
  1753. var RoutingRules = [{
  1754. Condition: {
  1755. HttpErrorCodeReturnedEquals: "404"
  1756. },
  1757. Redirect: {
  1758. Protocol: "https",
  1759. ReplaceKeyWith: "404.html"
  1760. }
  1761. }, {
  1762. Condition: {
  1763. KeyPrefixEquals: "docs/"
  1764. },
  1765. Redirect: {
  1766. Protocol: "https",
  1767. ReplaceKeyPrefixWith: "documents/"
  1768. }
  1769. }, {
  1770. Condition: {
  1771. KeyPrefixEquals: "img/"
  1772. },
  1773. Redirect: {
  1774. Protocol: "https",
  1775. ReplaceKeyWith: "picture.jpg"
  1776. }
  1777. }];
  1778. var WebsiteConfiguration = {
  1779. IndexDocument: {
  1780. Suffix: "index.html"
  1781. },
  1782. RedirectAllRequestsTo: {
  1783. Protocol: "https"
  1784. },
  1785. ErrorDocument: {
  1786. Key: "error.html"
  1787. },
  1788. };
  1789. test('putBucketWebsite(),getBucketWebsite()', function (done, assert) {
  1790. cos.putBucketWebsite({
  1791. Bucket: config.Bucket,
  1792. Region: config.Region,
  1793. WebsiteConfiguration: WebsiteConfiguration
  1794. }, function (err, data) {
  1795. assert.ok(!err);
  1796. setTimeout(function () {
  1797. cos.getBucketWebsite({
  1798. Bucket: config.Bucket,
  1799. Region: config.Region
  1800. }, function (err, data) {
  1801. assert.ok(comparePlainObject(WebsiteConfiguration, data.WebsiteConfiguration));
  1802. done();
  1803. });
  1804. }, 2000);
  1805. });
  1806. });
  1807. test('putBucketWebsite() multi RoutingRules', function (done, assert) {
  1808. WebsiteConfiguration.RoutingRules = RoutingRules;
  1809. cos.putBucketWebsite({
  1810. Bucket: config.Bucket,
  1811. Region: config.Region,
  1812. WebsiteConfiguration: WebsiteConfiguration
  1813. }, function (err, data) {
  1814. assert.ok(!err);
  1815. setTimeout(function () {
  1816. cos.getBucketWebsite({
  1817. Bucket: config.Bucket,
  1818. Region: config.Region
  1819. }, function (err, data) {
  1820. assert.ok(comparePlainObject(WebsiteConfiguration, data.WebsiteConfiguration));
  1821. done();
  1822. });
  1823. }, 2000);
  1824. });
  1825. });
  1826. test('deleteBucketWebsite()', function (done, assert) {
  1827. cos.deleteBucketWebsite({
  1828. Bucket: config.Bucket,
  1829. Region: config.Region
  1830. }, function (err, data) {
  1831. assert.ok(!err);
  1832. setTimeout(function () {
  1833. cos.getBucketWebsite({
  1834. Bucket: config.Bucket,
  1835. Region: config.Region
  1836. }, function (err, data) {
  1837. assert.ok(comparePlainObject({}, data.WebsiteConfiguration));
  1838. done();
  1839. });
  1840. }, 2000);
  1841. });
  1842. });
  1843. });
  1844. group('BucketDomain', function () {
  1845. var DomainRule = [{
  1846. Status: "DISABLED",
  1847. Name: "www.testDomain1.com",
  1848. Type: "REST"
  1849. },
  1850. {
  1851. Status: "DISABLED",
  1852. Name: "www.testDomain2.com",
  1853. Type: "WEBSITE"
  1854. }];
  1855. test('putBucketDomain(),getBucketDomain()', function (done, assert) {
  1856. cos.putBucketDomain({
  1857. Bucket: config.Bucket,
  1858. Region: config.Region,
  1859. DomainRule: DomainRule
  1860. }, function (err, data) {
  1861. assert.ok(!err);
  1862. setTimeout(function () {
  1863. cos.getBucketDomain({
  1864. Bucket: config.Bucket,
  1865. Region: config.Region
  1866. }, function (err, data) {
  1867. assert.ok(comparePlainObject(DomainRule, data.DomainRule));
  1868. done();
  1869. });
  1870. }, 2000);
  1871. });
  1872. });
  1873. // test('putBucketDomain() multi', function (done, assert) {
  1874. // cos.putBucketDomain({
  1875. // Bucket: config.Bucket,
  1876. // Region: config.Region,
  1877. // DomainRule: DomainRuleMulti
  1878. // }, function (err, data) {
  1879. // assert.ok(!err);
  1880. // setTimeout(function () {
  1881. // cos.getBucketDomain({
  1882. // Bucket: config.Bucket,
  1883. // Region: config.Region
  1884. // }, function (err, data) {
  1885. // assert.ok(comparePlainObject(DomainRuleMulti, data.DomainRule));
  1886. // done();
  1887. // });
  1888. // }, 2000);
  1889. // });
  1890. // });
  1891. test('deleteBucketDomain()', function (done, assert) {
  1892. cos.deleteBucketDomain({
  1893. Bucket: config.Bucket,
  1894. Region: config.Region
  1895. }, function (err, data) {
  1896. assert.ok(!err);
  1897. setTimeout(function () {
  1898. cos.getBucketDomain({
  1899. Bucket: config.Bucket,
  1900. Region: config.Region
  1901. }, function (err, data) {
  1902. assert.ok(comparePlainObject([], data.DomainRule));
  1903. done();
  1904. });
  1905. }, 2000);
  1906. });
  1907. });
  1908. });
  1909. group('params check Region', function () {
  1910. test('params check', function (done, assert) {
  1911. cos.headBucket({
  1912. Bucket: config.Bucket,
  1913. Region: 'cos.ap-guangzhou'
  1914. }, function (err, data) {
  1915. assert.ok(err.error === 'param Region should not be start with "cos."');
  1916. done();
  1917. });
  1918. });
  1919. test('params check Region', function (done, assert) {
  1920. cos.headBucket({
  1921. Bucket: config.Bucket,
  1922. Region: 'gz'
  1923. }, function (err, data) {
  1924. assert.ok(err);
  1925. done();
  1926. });
  1927. });
  1928. });
  1929. group('Key 特殊字符处理', function () {
  1930. test('Key 特殊字符处理', function (done, assert) {
  1931. var Key = '中文→↓←→↖↗↙↘! $&\'()+,-.0123456789=@ABCDEFGHIJKLMNOPQRSTUV?WXYZ[]^_`abcdefghijklmnopqrstuvwxyz{}~.jpg';
  1932. cos.putObject({
  1933. Bucket: config.Bucket,
  1934. Region: config.Region,
  1935. Key: Key,
  1936. Body: 'hello',
  1937. }, function (err, data) {
  1938. assert.ok(!err);
  1939. cos.deleteObject({
  1940. Bucket: config.Bucket,
  1941. Region: config.Region,
  1942. Key: Key,
  1943. Body: 'hello',
  1944. }, function (err, data) {
  1945. assert.ok(!err);
  1946. cos.deleteMultipleObject({
  1947. Bucket: config.Bucket,
  1948. Region: config.Region,
  1949. Objects: {
  1950. Key: Key,
  1951. },
  1952. }, function (err, data) {
  1953. assert.ok(!err);
  1954. done();
  1955. });
  1956. });
  1957. });
  1958. });
  1959. });
  1960. group('Bucket 格式有误', function () {
  1961. test('Bucket 带有中文', function (done, assert) {
  1962. cos.headBucket({
  1963. Bucket: '中文-1250000000',
  1964. Region: config.Region,
  1965. }, function (err, data) {
  1966. assert.ok(err && err.error === 'Bucket should format as "test-1250000000".');
  1967. done();
  1968. });
  1969. });
  1970. test('Bucket 带有 /', function (done, assert) {
  1971. cos.headBucket({
  1972. Bucket: 'te/st-1250000000',
  1973. Region: config.Region,
  1974. }, function (err, data) {
  1975. assert.ok(err && err.error === 'Bucket should format as "test-1250000000".');
  1976. done();
  1977. });
  1978. });
  1979. test('Bucket 带有 .', function (done, assert) {
  1980. cos.headBucket({
  1981. Bucket: 'te.st-1250000000',
  1982. Region: config.Region,
  1983. }, function (err, data) {
  1984. assert.ok(err && err.error === 'Bucket should format as "test-1250000000".');
  1985. done();
  1986. });
  1987. });
  1988. test('Bucket 带有 :', function (done, assert) {
  1989. cos.headBucket({
  1990. Bucket: 'te:st-1250000000',
  1991. Region: config.Region,
  1992. }, function (err, data) {
  1993. assert.ok(err && err.error === 'Bucket should format as "test-1250000000".');
  1994. done();
  1995. });
  1996. });
  1997. });
  1998. group('Region 格式有误', function () {
  1999. test('Region 带有中文', function (done, assert) {
  2000. cos.headBucket({
  2001. Bucket: 'test-1250000000',
  2002. Region: '中文',
  2003. }, function (err, data) {
  2004. assert.ok(err && err.error === 'Region format error.');
  2005. done();
  2006. });
  2007. });
  2008. test('Region 带有 /', function (done, assert) {
  2009. cos.headBucket({
  2010. Bucket: 'test-1250000000',
  2011. Region: 'test/',
  2012. }, function (err, data) {
  2013. assert.ok(err && err.error === 'Region format error.');
  2014. done();
  2015. });
  2016. });
  2017. test('Region 带有 :', function (done, assert) {
  2018. cos.headBucket({
  2019. Bucket: 'test-1250000000',
  2020. Region: 'test:',
  2021. }, function (err, data) {
  2022. assert.ok(err && err.error === 'Region format error.');
  2023. done();
  2024. });
  2025. });
  2026. });
  2027. group('复制文件', function () {
  2028. test('sliceCopyFile() 正常分片复制', function (done, assert) {
  2029. var filename = '10m.zip';
  2030. var Key = '10m.copy.zip';
  2031. var blob = util.createFile({size: 1024 * 1024 * 10});
  2032. var lastPercent;
  2033. cos.putObject({
  2034. Bucket: config.Bucket,
  2035. Region: config.Region,
  2036. Key: filename,
  2037. Body: blob,
  2038. }, function (err, data) {
  2039. cos.sliceCopyFile({
  2040. Bucket: config.Bucket,
  2041. Region: config.Region,
  2042. Key: Key,
  2043. CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + filename,
  2044. SliceSize: 5 * 1024 * 1024,
  2045. onProgress: function (info) {
  2046. lastPercent = info.percent;
  2047. }
  2048. }, function (err, data) {
  2049. assert.ok(data && data.ETag, '成功进行分片复制');
  2050. done();
  2051. });
  2052. });
  2053. });
  2054. test('sliceCopyFile() 单片复制', function (done, assert) {
  2055. var filename = '10m.zip';
  2056. var Key = '10m.copy.zip';
  2057. cos.sliceCopyFile({
  2058. Bucket: config.Bucket,
  2059. Region: config.Region,
  2060. Key: Key,
  2061. CopySource: config.Bucket + '.cos.' + config.Region + '.myqcloud.com/' + filename,
  2062. SliceSize: 10 * 1024 * 1024,
  2063. }, function (err, data) {
  2064. if (err) throw err;
  2065. assert.ok(data && data.ETag, '成功进行单片复制');
  2066. done();
  2067. });
  2068. });
  2069. });
  2070. group('putObject 中文 Content-MD5', function () {
  2071. var fileBlob = dataURItoUploadBody('data:text/plain;base64,5Lit5paH');
  2072. // 这里两个用户正式测试的时候需要给 putObject 计算并加上 Content-MD5 字段
  2073. test('putObject 中文文件内容 带 Content-MD5', function (done, assert) {
  2074. var Key = '中文.txt';
  2075. cos.putObject({
  2076. Bucket: config.Bucket,
  2077. Region: config.Region,
  2078. Key: Key,
  2079. Body: fileBlob,
  2080. }, function (err, data) {
  2081. assert.ok(data && data.ETag, '成功进行上传');
  2082. done();
  2083. });
  2084. });
  2085. test('putObject 中文字符串 带 Content-MD5', function (done, assert) {
  2086. var Key = '中文.txt';
  2087. cos.putObject({
  2088. Bucket: config.Bucket,
  2089. Region: config.Region,
  2090. Key: Key,
  2091. Body: '中文',
  2092. }, function (err, data) {
  2093. assert.ok(data && data.ETag, '成功进行上传');
  2094. done();
  2095. });
  2096. });
  2097. });
  2098. group('deleteMultipleObject Key 带中文字符', function () {
  2099. test('deleteMultipleObject Key 带中文字符', function (done, assert) {
  2100. cos.deleteMultipleObject({
  2101. Bucket: config.Bucket,
  2102. Region: config.Region,
  2103. Objects: [
  2104. {Key: '中文/中文.txt'},
  2105. {Key: '中文/中文.zip', VersionId: 'MTg0NDY3NDI1MzM4NzM0ODA2MTI'},
  2106. {Key: unescape(encodeURIComponent('中文'))},
  2107. {Key: unescape('%e8%af%b4%2e%70%72%70%72')},
  2108. ]
  2109. }, function (err, data) {
  2110. assert.ok(!err, '成功进行批量删除');
  2111. done();
  2112. });
  2113. });
  2114. });
  2115. group('upload Content-Type', function () {
  2116. // putObject
  2117. test('putObject string Content-Type null -> text/plain', function (done, assert) {
  2118. cos.putObject({
  2119. Bucket: config.Bucket,
  2120. Region: config.Region,
  2121. Key: '1.zip',
  2122. Body: '12345',
  2123. }, function (err, data) {
  2124. cos.headObject({
  2125. Bucket: config.Bucket,
  2126. Region: config.Region,
  2127. Key: '1.zip',
  2128. }, function (err, data) {
  2129. assert.ok(data.headers['content-type'] === 'application/zip', 'Content-Type 正确');
  2130. done();
  2131. });
  2132. });
  2133. });
  2134. test('putObject string Content-Type text/xml -> text/xml', function (done, assert) {
  2135. cos.putObject({
  2136. Bucket: config.Bucket,
  2137. Region: config.Region,
  2138. Key: '1.zip',
  2139. ContentType: 'text/xml',
  2140. Body: util.createFile({size: 1}),
  2141. }, function (err, data) {
  2142. cos.headObject({
  2143. Bucket: config.Bucket,
  2144. Region: config.Region,
  2145. Key: '1.zip',
  2146. }, function (err, data) {
  2147. assert.ok(data.headers['content-type'] === 'text/xml', 'Content-Type 正确');
  2148. done();
  2149. });
  2150. });
  2151. });
  2152. test('putObject empty blob Content-Type null application/octet-stream', function (done, assert) {
  2153. cos.putObject({
  2154. Bucket: config.Bucket,
  2155. Region: config.Region,
  2156. Key: '1',
  2157. Body: '1234',
  2158. }, function (err, data) {
  2159. cos.headObject({
  2160. Bucket: config.Bucket,
  2161. Region: config.Region,
  2162. Key: '1',
  2163. }, function (err, data) {
  2164. assert.ok(data.headers['content-type'] === 'application/octet-stream', 'Content-Type 正确');
  2165. done();
  2166. });
  2167. });
  2168. });
  2169. // sliceUploadFile
  2170. test('sliceUploadFile string Content-Type text/xml -> text/xml', function (done, assert) {
  2171. cos.sliceUploadFile({
  2172. Bucket: config.Bucket,
  2173. Region: config.Region,
  2174. Key: '1.zip',
  2175. ContentType: 'text/xml',
  2176. Body: util.createFile({size: 1, type: 'text/html'}),
  2177. }, function (err, data) {
  2178. cos.headObject({
  2179. Bucket: config.Bucket,
  2180. Region: config.Region,
  2181. Key: '1.zip',
  2182. }, function (err, data) {
  2183. assert.ok(data.headers['content-type'] === 'text/xml', 'Content-Type 正确');
  2184. done();
  2185. });
  2186. });
  2187. });
  2188. test('sliceUploadFile ArrayBuffer Content-Type null application/octet-stream', function (done, assert) {
  2189. cos.sliceUploadFile({
  2190. Bucket: config.Bucket,
  2191. Region: config.Region,
  2192. Key: '1',
  2193. Body: '1234',
  2194. }, function (err, data) {
  2195. cos.headObject({
  2196. Bucket: config.Bucket,
  2197. Region: config.Region,
  2198. Key: '1',
  2199. }, function (err, data) {
  2200. assert.ok(data.headers['content-type'] === 'application/octet-stream', 'Content-Type 正确');
  2201. done();
  2202. });
  2203. });
  2204. });
  2205. });
  2206. group('Cache-Control', function () {
  2207. // putObject
  2208. test('putObject Cache-Control: null -> Cache-Control: null or max-age=259200', function (done, assert) {
  2209. cos.putObject({
  2210. Bucket: config.Bucket,
  2211. Region: config.Region,
  2212. Key: '1m.zip',
  2213. Body: '',
  2214. }, function (err, data) {
  2215. cos.headObject({
  2216. Bucket: config.Bucket,
  2217. Region: config.Region,
  2218. Key: '1m.zip',
  2219. }, function (err, data) {
  2220. assert.ok(data.headers['cache-control'] === undefined || data.headers['cache-control'] === 'max-age=259200', 'cache-control 正确');
  2221. done();
  2222. });
  2223. });
  2224. });
  2225. test('putObject Cache-Control: max-age=7200 -> Cache-Control: max-age=7200', function (done, assert) {
  2226. cos.putObject({
  2227. Bucket: config.Bucket,
  2228. Region: config.Region,
  2229. Key: '1m.zip',
  2230. Body: '',
  2231. CacheControl: 'max-age=7200',
  2232. }, function (err, data) {
  2233. cos.headObject({
  2234. Bucket: config.Bucket,
  2235. Region: config.Region,
  2236. Key: '1m.zip',
  2237. }, function (err, data) {
  2238. assert.ok(data.headers['cache-control'] === 'max-age=7200', 'cache-control 正确');
  2239. done();
  2240. });
  2241. });
  2242. });
  2243. test('putObject Cache-Control: no-cache -> Cache-Control: no-cache', function (done, assert) {
  2244. cos.putObject({
  2245. Bucket: config.Bucket,
  2246. Region: config.Region,
  2247. Key: '1m.zip',
  2248. Body: '',
  2249. CacheControl: 'no-cache',
  2250. }, function (err, data) {
  2251. cos.headObject({
  2252. Bucket: config.Bucket,
  2253. Region: config.Region,
  2254. Key: '1m.zip',
  2255. }, function (err, data) {
  2256. assert.ok(data.headers['cache-control'] === 'no-cache' || data.headers['cache-control'] === 'no-cache, max-age=259200', 'cache-control 正确');
  2257. done();
  2258. });
  2259. });
  2260. });
  2261. // sliceUploadFile
  2262. test('sliceUploadFile Cache-Control: null -> Cache-Control: null or max-age=259200', function (done, assert) {
  2263. var filename = '1.txt';
  2264. cos.sliceUploadFile({
  2265. Bucket: config.Bucket,
  2266. Region: config.Region,
  2267. Key: filename,
  2268. FilePath: testFile[filename],
  2269. }, function (err, data) {
  2270. cos.headObject({
  2271. Bucket: config.Bucket,
  2272. Region: config.Region,
  2273. Key: filename,
  2274. }, function (err, data) {
  2275. assert.ok(data.headers['cache-control'] === undefined || data.headers['cache-control'] === 'max-age=259200', 'cache-control 正确');
  2276. done();
  2277. });
  2278. });
  2279. });
  2280. test('sliceUploadFile Cache-Control: max-age=7200 -> Cache-Control: max-age=7200', function (done, assert) {
  2281. var filename = '1.txt';
  2282. cos.sliceUploadFile({
  2283. Bucket: config.Bucket,
  2284. Region: config.Region,
  2285. Key: filename,
  2286. FilePath: testFile[filename],
  2287. CacheControl: 'max-age=7200',
  2288. }, function (err, data) {
  2289. cos.headObject({
  2290. Bucket: config.Bucket,
  2291. Region: config.Region,
  2292. Key: filename,
  2293. }, function (err, data) {
  2294. assert.ok(data.headers['cache-control'] === 'max-age=7200', 'cache-control 正确');
  2295. done();
  2296. });
  2297. });
  2298. });
  2299. test('sliceUploadFile Cache-Control: no-cache -> Cache-Control: no-cache', function (done, assert) {
  2300. var filename = '1.txt';
  2301. var fileSize = 1024;
  2302. var filePath = wx.env.USER_DATA_PATH + '/' + filename;
  2303. util.createFile({size: fileSize}, filePath);
  2304. cos.sliceUploadFile({
  2305. Bucket: config.Bucket,
  2306. Region: config.Region,
  2307. Key: filename,
  2308. FilePath: testFile[filename],
  2309. CacheControl: 'no-cache',
  2310. }, function (err, data) {
  2311. cos.headObject({
  2312. Bucket: config.Bucket,
  2313. Region: config.Region,
  2314. Key: filename,
  2315. }, function (err, data) {
  2316. assert.ok(data.headers['cache-control'] === 'no-cache' || data.headers['cache-control'] === 'no-cache, max-age=259200', 'cache-control 正确');
  2317. done();
  2318. });
  2319. });
  2320. });
  2321. });
  2322. group('BucketLogging', function () {
  2323. var TargetBucket = config.Bucket;
  2324. var TargetPrefix = 'bucket-logging-prefix' + Date.now().toString(36) + '/';
  2325. var BucketLoggingStatus = {
  2326. LoggingEnabled: {
  2327. TargetBucket: TargetBucket,
  2328. TargetPrefix: TargetPrefix
  2329. }
  2330. };
  2331. test('putBucketLogging(), getBucketLogging()', function (done, assert) {
  2332. cos.putBucketLogging({
  2333. Bucket: config.Bucket,
  2334. Region: config.Region,
  2335. BucketLoggingStatus: BucketLoggingStatus
  2336. }, function (err, data) {
  2337. assert.ok(!err);
  2338. cos.getBucketLogging({
  2339. Bucket: config.Bucket,
  2340. Region: config.Region
  2341. }, function (err, data) {
  2342. delete data.BucketLoggingStatus._xmlns;
  2343. assert.ok(comparePlainObject(BucketLoggingStatus, data.BucketLoggingStatus));
  2344. done();
  2345. });
  2346. });
  2347. });
  2348. test('putBucketLogging() 删除 logging 配置', function (done, assert) {
  2349. cos.putBucketLogging({
  2350. Bucket: config.Bucket,
  2351. Region: config.Region,
  2352. BucketLoggingStatus: ''
  2353. }, function (err, data) {
  2354. assert.ok(!err);
  2355. cos.getBucketLogging({
  2356. Bucket: config.Bucket,
  2357. Region: config.Region
  2358. }, function (err, data) {
  2359. delete data.BucketLoggingStatus._xmlns;
  2360. assert.ok(comparePlainObject(data.BucketLoggingStatus, {}));
  2361. done();
  2362. });
  2363. });
  2364. });
  2365. });
  2366. group('BucketInventory', function () {
  2367. var TargetBucket = config.Bucket;
  2368. var InventoryConfiguration = {
  2369. Id: 'inventory_test',
  2370. IsEnabled: 'true',
  2371. Destination: {
  2372. COSBucketDestination: {
  2373. Format: 'CSV',
  2374. AccountId: config.Uin,
  2375. Bucket: 'qcs::cos:' + config.Region + '::' + TargetBucket,
  2376. Prefix: 'inventory_prefix_1',
  2377. Encryption: {
  2378. SSECOS: ''
  2379. }
  2380. }
  2381. },
  2382. Schedule: {
  2383. Frequency: 'Daily'
  2384. },
  2385. Filter: {
  2386. Prefix: 'myPrefix'
  2387. },
  2388. IncludedObjectVersions: 'All',
  2389. OptionalFields: [
  2390. 'Size'
  2391. ]
  2392. };
  2393. var InventoryConfigurationNoEncryption = {
  2394. Id: 'inventory_test',
  2395. IsEnabled: 'true',
  2396. Destination: {
  2397. COSBucketDestination: {
  2398. Format: 'CSV',
  2399. AccountId: config.Uin,
  2400. Bucket: 'qcs::cos:' + config.Region + '::' + TargetBucket,
  2401. Prefix: 'inventory_prefix_1'
  2402. }
  2403. },
  2404. Schedule: {
  2405. Frequency: 'Daily'
  2406. },
  2407. Filter: {
  2408. Prefix: 'myPrefix'
  2409. },
  2410. IncludedObjectVersions: 'All',
  2411. OptionalFields: [
  2412. 'Size'
  2413. ]
  2414. };
  2415. test('putBucketInventory(), getBucketInventory()', function (done, assert) {
  2416. cos.putBucketInventory({
  2417. Bucket: config.Bucket,
  2418. Region: config.Region,
  2419. Id: InventoryConfiguration.Id,
  2420. InventoryConfiguration: InventoryConfiguration
  2421. }, function (err, data) {
  2422. assert.ok(!err);
  2423. cos.getBucketInventory({
  2424. Bucket: config.Bucket,
  2425. Region: config.Region,
  2426. Id: InventoryConfiguration.Id
  2427. }, function (err, data) {
  2428. assert.ok(comparePlainObject(InventoryConfiguration, data.InventoryConfiguration));
  2429. done();
  2430. });
  2431. });
  2432. });
  2433. test('listBucketInventory()', function (done, assert) {
  2434. cos.listBucketInventory({
  2435. Bucket: config.Bucket,
  2436. Region: config.Region
  2437. }, function (err, data) {
  2438. var targetInventory;
  2439. data.InventoryConfigurations.forEach(function (item) {
  2440. if (item.Id === InventoryConfiguration.Id) {
  2441. targetInventory = item;
  2442. }
  2443. });
  2444. assert.ok(comparePlainObject(InventoryConfiguration, targetInventory));
  2445. assert.ok(data.IsTruncated === 'false' || data.IsTruncated === 'true');
  2446. done();
  2447. });
  2448. });
  2449. test('putBucketInventory() 不设置 SSECOS', function (done, assert) {
  2450. cos.putBucketInventory({
  2451. Bucket: config.Bucket,
  2452. Region: config.Region,
  2453. Id: InventoryConfigurationNoEncryption.Id,
  2454. InventoryConfiguration: InventoryConfigurationNoEncryption
  2455. }, function (err, data) {
  2456. assert.ok(!err);
  2457. cos.getBucketInventory({
  2458. Bucket: config.Bucket,
  2459. Region: config.Region,
  2460. Id: InventoryConfigurationNoEncryption.Id
  2461. }, function (err, data) {
  2462. assert.ok(comparePlainObject(InventoryConfigurationNoEncryption, data.InventoryConfiguration));
  2463. done();
  2464. });
  2465. });
  2466. });
  2467. test('deleteBucketInventory()', function (done, assert) {
  2468. cos.deleteBucketInventory({
  2469. Bucket: config.Bucket,
  2470. Region: config.Region,
  2471. Id: InventoryConfiguration.Id
  2472. }, function (err, data) {
  2473. assert.ok(!err);
  2474. cos.getBucketInventory({
  2475. Bucket: config.Bucket,
  2476. Region: config.Region,
  2477. Id: InventoryConfiguration.Id
  2478. }, function (err, data) {
  2479. assert.ok(err && err.statusCode === 404);
  2480. done();
  2481. });
  2482. });
  2483. });
  2484. });
  2485. var tagging2str = (obj) => {
  2486. var arr = [];
  2487. obj.forEach(v => arr.push(v.Key + '=' + encodeURIComponent(v.Value)))
  2488. return arr.join('&');
  2489. }
  2490. group('上传带 tagging', function () {
  2491. var Tags = [
  2492. {Key: "k1", Value: "v1"},
  2493. {Key: "k2", Value: "v2"},
  2494. ];
  2495. var key = '1.txt';
  2496. test('putObject 带 x-cos-tagging', function (done, assert) {
  2497. Tags[0].Value = Date.now().toString(36);
  2498. var tagStr = tagging2str(Tags);
  2499. // 调用方法
  2500. cos.putObject({
  2501. Bucket: config.Bucket, /* 必须 */ // Bucket 格式:test-1250000000
  2502. Region: config.Region,
  2503. Key: key,
  2504. Body: 'hello!',
  2505. Headers: {
  2506. 'x-cos-tagging': tagStr,
  2507. },
  2508. }, function (err1, data1) {
  2509. cos.headObject({
  2510. Bucket: config.Bucket, /* 必须 */ // Bucket 格式:test-1250000000
  2511. Region: config.Region,
  2512. Key: key,
  2513. }, function (err2, data2) {
  2514. var taggingCount = data2 && data2.headers['x-cos-tagging-count'];
  2515. assert.ok(taggingCount === '2', '返回 x-cos-tagging-count: ' + taggingCount);
  2516. cos.getObjectTagging({
  2517. Bucket: config.Bucket, /* 必须 */ // Bucket 格式:test-1250000000
  2518. Region: config.Region,
  2519. Key: key,
  2520. }, function (err3, data3) {
  2521. assert.ok(comparePlainObject(Tags, data3.Tags));
  2522. done();
  2523. });
  2524. });
  2525. });
  2526. });
  2527. // test('sliceUploadFile 带 x-cos-tagging', function (done, assert) {
  2528. // Tags[0].Value = Date.now().toString(36);
  2529. // var tagStr = tagging2str(Tags);
  2530. // // 调用方法
  2531. // cos.sliceUploadFile({
  2532. // Bucket: config.Bucket, /* 必须 */ // Bucket 格式:test-1250000000
  2533. // Region: config.Region,
  2534. // Key: key,
  2535. // Body: 'hello!',
  2536. // Headers: {
  2537. // 'x-cos-tagging': tagStr,
  2538. // },
  2539. // }, function (err1, data1) {
  2540. // cos.headObject({
  2541. // Bucket: config.Bucket, /* 必须 */ // Bucket 格式:test-1250000000
  2542. // Region: config.Region,
  2543. // Key: key,
  2544. // }, function (err2, data2) {
  2545. // var taggingCount = data2 && data2.headers['x-cos-tagging-count'];
  2546. // assert.ok(taggingCount === '1', '返回 x-cos-tagging-count: ' + taggingCount);
  2547. // cos.getObjectTagging({
  2548. // Bucket: config.Bucket, /* 必须 */ // Bucket 格式:test-1250000000
  2549. // Region: config.Region,
  2550. // Key: key,
  2551. // }, function (err3, data3) {
  2552. // assert.ok(data3 && data3.Tags && comparePlainObject(Tags, data3.Tags));
  2553. // done();
  2554. // });
  2555. // });
  2556. // });
  2557. // });
  2558. });
  2559. group('ObjectTagging', function () {
  2560. var key = '1.txt';
  2561. var Tags = [
  2562. {Key: "k1", Value: "v1"},
  2563. {Key: "k2", Value: "v2"},
  2564. ];
  2565. test('putObjectTagging(),getObjectTagging()', function (done, assert) {
  2566. Tags[0].Value = Date.now().toString(36);
  2567. cos.putObjectTagging({
  2568. Bucket: config.Bucket,
  2569. Region: config.Region,
  2570. Key: key,
  2571. Tagging: {
  2572. Tags: Tags
  2573. },
  2574. }, function (err, data) {
  2575. assert.ok(!err);
  2576. setTimeout(function () {
  2577. cos.getObjectTagging({
  2578. Bucket: config.Bucket,
  2579. Region: config.Region,
  2580. Key: key,
  2581. }, function (err, data) {
  2582. assert.ok(comparePlainObject(Tags, data.Tags));
  2583. done();
  2584. });
  2585. }, 1000);
  2586. });
  2587. });
  2588. test('deleteObjectTagging()', function (done, assert) {
  2589. cos.deleteObjectTagging({
  2590. Bucket: config.Bucket,
  2591. Region: config.Region,
  2592. Key: key,
  2593. }, function (err, data) {
  2594. assert.ok(!err);
  2595. setTimeout(function () {
  2596. cos.getObjectTagging({
  2597. Bucket: config.Bucket,
  2598. Region: config.Region,
  2599. Key: key,
  2600. }, function (err, data) {
  2601. assert.ok(comparePlainObject([], data.Tags));
  2602. done();
  2603. });
  2604. }, 1000);
  2605. });
  2606. });
  2607. });
  2608. group('getBucketAccelerate', function () {
  2609. test('putBucketAccelerate(),getBucketAccelerate() Enabled', function (done, assert) {
  2610. cos.putBucketAccelerate({
  2611. Bucket: config.Bucket,
  2612. Region: config.Region,
  2613. AccelerateConfiguration: {
  2614. Status: 'Enabled', // Suspended、Enabled
  2615. },
  2616. }, function (err, data) {
  2617. assert.ok(!err);
  2618. setTimeout(function () {
  2619. cos.getBucketAccelerate({
  2620. Bucket: config.Bucket,
  2621. Region: config.Region,
  2622. }, function (err2, data2) {
  2623. assert.ok(data2 && data2.AccelerateConfiguration && data2.AccelerateConfiguration.Status === 'Enabled');
  2624. done();
  2625. });
  2626. }, 2000);
  2627. });
  2628. });
  2629. test('putBucketAccelerate(),getBucketAccelerate() Suspended', function (done, assert) {
  2630. cos.putBucketAccelerate({
  2631. Bucket: config.Bucket,
  2632. Region: config.Region,
  2633. AccelerateConfiguration: {
  2634. Status: 'Suspended', // Suspended、Enabled
  2635. },
  2636. }, function (err, data) {
  2637. assert.ok(!err);
  2638. setTimeout(function () {
  2639. cos.getBucketAccelerate({
  2640. Bucket: config.Bucket,
  2641. Region: config.Region,
  2642. }, function (err2, data2) {
  2643. assert.ok(data2 && data2.AccelerateConfiguration && data2.AccelerateConfiguration.Status === 'Suspended');
  2644. done();
  2645. });
  2646. }, 1000);
  2647. });
  2648. });
  2649. });
  2650. // 小程序没有 Promise
  2651. // group('Promise', function () {
  2652. //
  2653. // test('Promise() getService', function (done, assert) {
  2654. // cos.getService().then(function (data) {
  2655. // assert.ok(data);
  2656. // done();
  2657. // }).catch(function (err) {
  2658. // assert.ok(false);
  2659. // done();
  2660. // });
  2661. // });
  2662. //
  2663. // test('Promise() getService region', function (done, assert) {
  2664. // cos.getService({
  2665. // Region: config.Region,
  2666. // }).then(function (data) {
  2667. // assert.ok(data);
  2668. // done();
  2669. // }).catch(function (err) {
  2670. // assert.ok(false);
  2671. // done();
  2672. // });
  2673. // });
  2674. //
  2675. // test('Promise() getObjectUrl', function (done, assert) {
  2676. // var res = cos.getObjectUrl({
  2677. // Bucket: config.Bucket,
  2678. // Region: config.Region,
  2679. // Key: '123.txt',
  2680. // });
  2681. // assert.ok(!res.then);
  2682. // done();
  2683. // });
  2684. //
  2685. // test('Promise() headBucket', function (done, assert) {
  2686. // cos.headBucket({
  2687. // Bucket: config.Bucket,
  2688. // Region: config.Region,
  2689. // }).then(function (data) {
  2690. // assert.ok(data);
  2691. // done();
  2692. // }).catch(function () {
  2693. // assert.ok(false);
  2694. // done();
  2695. // });
  2696. // });
  2697. //
  2698. // test('headBucket callback', function (done, assert) {
  2699. // var res = cos.headBucket({
  2700. // Bucket: config.Bucket,
  2701. // Region: config.Region,
  2702. // }, function (err, data) {
  2703. // assert.ok(!err && data);
  2704. // done();
  2705. // });
  2706. // assert.ok(!res);
  2707. // });
  2708. //
  2709. // test('Promise() headBucket error', function (done, assert) {
  2710. // cos.headBucket({
  2711. // Bucket: config.Bucket,
  2712. // Region: config.Region + '/',
  2713. // }).then(function (data) {
  2714. // assert.ok(!data);
  2715. // done();
  2716. // }).catch(function (err) {
  2717. // assert.ok(err && err.error === 'Region format error.');
  2718. // done();
  2719. // });
  2720. // });
  2721. // });
  2722. group('Query 的键值带有特殊字符', function () {
  2723. test('getAuth()', function (done, assert) {
  2724. var content = Date.now().toString();
  2725. var key = '1.txt';
  2726. cos.putObject({
  2727. Bucket: config.Bucket,
  2728. Region: config.Region,
  2729. Key: key,
  2730. Body: content,
  2731. }, function (err, data) {
  2732. var str = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM,./;\'[]\\-=0987654321`~!@#$%^&*()_+{}|":>?<';
  2733. var qs = {};
  2734. qs[str] = str;
  2735. cos.options.getAuthorization({
  2736. Method: 'get',
  2737. Key: key,
  2738. Scope: [{
  2739. action: 'GetObject',
  2740. bucket: config.Bucket,
  2741. region: config.Region,
  2742. prefix: key,
  2743. }],
  2744. }, function (AuthData) {
  2745. if (typeof AuthData === 'string') {
  2746. AuthData = {Authorization: AuthData};
  2747. }
  2748. if (!AuthData.Authorization) {
  2749. AuthData.Authorization = COS.getAuthorization({
  2750. SecretId: AuthData.TmpSecretId,
  2751. SecretKey: AuthData.TmpSecretKey,
  2752. Method: 'get',
  2753. Key: key,
  2754. SystemClockOffset: cos.options.SystemClockOffset,
  2755. });
  2756. }
  2757. var link = 'http://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com' + '/' +
  2758. camSafeUrlEncode(key).replace(/%2F/g, '/') +
  2759. '?sign=' + camSafeUrlEncode(AuthData.Authorization) +
  2760. (AuthData.XCosSecurityToken ? '&x-cos-security-token=' + AuthData.XCosSecurityToken : '') +
  2761. '&' + camSafeUrlEncode(str) + '=' + camSafeUrlEncode(str);
  2762. request({
  2763. method: 'GET',
  2764. url: link,
  2765. }, function (err, response, body) {
  2766. assert.ok(response.statusCode === 200);
  2767. assert.ok(body === content);
  2768. done();
  2769. });
  2770. });
  2771. });
  2772. });
  2773. });
  2774. group('appendObject', function () {
  2775. test('appendObject()', function (done, assert) {
  2776. cos.headObject({
  2777. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  2778. Region: config.Region,
  2779. Key: 'append.txt', /* 必须 */
  2780. }, function(err, data) {
  2781. assert.ok(!err);
  2782. if (err) return console.log(err);
  2783. // 首先取到要追加的文件当前长度,即需要上送的Position
  2784. var position = data.headers['content-length'];
  2785. cos.appendObject({
  2786. Bucket: config.Bucket, // Bucket 格式:test-1250000000
  2787. Region: config.Region,
  2788. Key: 'append.txt', /* 必须 */
  2789. Body: '66666',
  2790. Position: position,
  2791. },
  2792. function(err, data) {
  2793. assert.ok(!err);
  2794. done();
  2795. })
  2796. });
  2797. });
  2798. });
  2799. group('数据万象', function () {
  2800. test('describeMediaBuckets()', function (done, assert) {
  2801. var host = 'ci.' + config.Region + '.myqcloud.com';
  2802. var url = 'https://' + host + '/mediabucket';
  2803. cos.request({
  2804. Bucket: config.Bucket,
  2805. Region: config.Region,
  2806. Method: 'GET',
  2807. Key: 'mediabucket', /** 固定值,必须 */
  2808. Url: url,
  2809. Query: {
  2810. pageNumber: '1', /** 第几页,非必须 */
  2811. pageSize: '10', /** 每页个数,非必须 */
  2812. // regions: 'ap-chengdu', /** 地域信息,例如'ap-beijing',支持多个值用逗号分隔如'ap-shanghai,ap-beijing',非必须 */
  2813. // bucketNames: 'test-1250000000', /** 存储桶名称,精确搜索,例如'test-1250000000',支持多个值用逗号分隔如'test1-1250000000,test2-1250000000',非必须 */
  2814. // bucketName: 'test', /** 存储桶名称前缀,前缀搜索,例如'test',支持多个值用逗号分隔如'test1,test2',非必须 */
  2815. }
  2816. },
  2817. function(err, data){
  2818. assert.ok(!err);
  2819. done();
  2820. });
  2821. });
  2822. test('getMediaInfo()', function (done, assert) {
  2823. cos.request({
  2824. Bucket: config.Bucket,
  2825. Region: config.Region,
  2826. Method: 'GET',
  2827. Key: 'test.mp4',
  2828. Query: {
  2829. 'ci-process': 'videoinfo' /** 固定值,必须 */
  2830. }
  2831. },
  2832. function(err, data){
  2833. assert.ok(!err);
  2834. done();
  2835. });
  2836. });
  2837. test('getSnapshot()', function (done, assert) {
  2838. cos.request({
  2839. Bucket: config.Bucket,
  2840. Region: config.Region,
  2841. Method: 'GET',
  2842. Key: 'test.mp4',
  2843. Query: {
  2844. 'ci-process': 'snapshot', /** 固定值,必须 */
  2845. time: 1, /** 截图的时间点,单位为秒,必须 */
  2846. // width: 0, /** 截图的宽,非必须 */
  2847. // height: 0, /** 截图的高,非必须 */
  2848. // format: 'jpg', /** 截图的格式,支持 jpg 和 png,默认 jpg,非必须 */
  2849. // rotate: 'auto', /** 图片旋转方式,默认为'auto',非必须 */
  2850. // mode: 'exactframe', /** 截帧方式,默认为'exactframe',非必须 */
  2851. },
  2852. RawBody: true,
  2853. },
  2854. function(err, data){
  2855. assert.ok(!err);
  2856. done();
  2857. });
  2858. });
  2859. });