bucket_test.go 156 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184
  1. package oss
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "math/rand"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/baiyubin/aliyun-sts-go-sdk/sts"
  18. . "gopkg.in/check.v1"
  19. )
  20. type OssBucketSuite struct {
  21. client *Client
  22. bucket *Bucket
  23. archiveBucket *Bucket
  24. }
  25. var _ = Suite(&OssBucketSuite{})
  26. var (
  27. pastDate = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
  28. futureDate = time.Date(2049, time.January, 10, 23, 0, 0, 0, time.UTC)
  29. )
  30. // SetUpSuite runs once when the suite starts running.
  31. func (s *OssBucketSuite) SetUpSuite(c *C) {
  32. client, err := New(endpoint, accessID, accessKey)
  33. c.Assert(err, IsNil)
  34. s.client = client
  35. s.client.CreateBucket(bucketName)
  36. err = s.client.CreateBucket(archiveBucketName, StorageClass(StorageArchive))
  37. c.Assert(err, IsNil)
  38. bucket, err := s.client.Bucket(bucketName)
  39. c.Assert(err, IsNil)
  40. s.bucket = bucket
  41. archiveBucket, err := s.client.Bucket(archiveBucketName)
  42. c.Assert(err, IsNil)
  43. s.archiveBucket = archiveBucket
  44. testLogger.Println("test bucket started")
  45. }
  46. // TearDownSuite runs before each test or benchmark starts running.
  47. func (s *OssBucketSuite) TearDownSuite(c *C) {
  48. for _, bucket := range []*Bucket{s.bucket, s.archiveBucket} {
  49. // Delete multipart
  50. keyMarker := KeyMarker("")
  51. uploadIDMarker := UploadIDMarker("")
  52. for {
  53. lmu, err := bucket.ListMultipartUploads(keyMarker, uploadIDMarker)
  54. c.Assert(err, IsNil)
  55. for _, upload := range lmu.Uploads {
  56. imur := InitiateMultipartUploadResult{Bucket: bucketName, Key: upload.Key, UploadID: upload.UploadID}
  57. err = bucket.AbortMultipartUpload(imur)
  58. c.Assert(err, IsNil)
  59. }
  60. keyMarker = KeyMarker(lmu.NextKeyMarker)
  61. uploadIDMarker = UploadIDMarker(lmu.NextUploadIDMarker)
  62. if !lmu.IsTruncated {
  63. break
  64. }
  65. }
  66. // Delete objects
  67. marker := Marker("")
  68. for {
  69. lor, err := bucket.ListObjects(marker)
  70. c.Assert(err, IsNil)
  71. for _, object := range lor.Objects {
  72. err = bucket.DeleteObject(object.Key)
  73. c.Assert(err, IsNil)
  74. }
  75. marker = Marker(lor.NextMarker)
  76. if !lor.IsTruncated {
  77. break
  78. }
  79. }
  80. // Delete bucket
  81. err := s.client.DeleteBucket(bucket.BucketName)
  82. c.Assert(err, IsNil)
  83. }
  84. testLogger.Println("test bucket completed")
  85. }
  86. // SetUpTest runs after each test or benchmark runs.
  87. func (s *OssBucketSuite) SetUpTest(c *C) {
  88. err := removeTempFiles("../oss", ".jpg")
  89. c.Assert(err, IsNil)
  90. }
  91. // TearDownTest runs once after all tests or benchmarks have finished running.
  92. func (s *OssBucketSuite) TearDownTest(c *C) {
  93. err := removeTempFiles("../oss", ".jpg")
  94. c.Assert(err, IsNil)
  95. err = removeTempFiles("../oss", ".txt")
  96. c.Assert(err, IsNil)
  97. err = removeTempFiles("../oss", ".temp")
  98. c.Assert(err, IsNil)
  99. err = removeTempFiles("../oss", ".txt1")
  100. c.Assert(err, IsNil)
  101. err = removeTempFiles("../oss", ".txt2")
  102. c.Assert(err, IsNil)
  103. }
  104. // TestPutObject
  105. func (s *OssBucketSuite) TestPutObjectOnly(c *C) {
  106. objectName := objectNamePrefix + RandStr(8)
  107. objectValue := "大江东去,浪淘尽,千古风流人物。 故垒西边,人道是、三国周郎赤壁。 乱石穿空,惊涛拍岸,卷起千堆雪。 江山如画,一时多少豪杰。" +
  108. "遥想公谨当年,小乔初嫁了,雄姿英发。 羽扇纶巾,谈笑间、樯橹灰飞烟灭。故国神游,多情应笑我,早生华发,人生如梦,一尊还酹江月。"
  109. // Put string
  110. var respHeader http.Header
  111. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue), GetResponseHeader(&respHeader))
  112. c.Assert(err, IsNil)
  113. // Check
  114. body, err := s.bucket.GetObject(objectName)
  115. c.Assert(err, IsNil)
  116. str, err := readBody(body)
  117. c.Assert(err, IsNil)
  118. c.Assert(str, Equals, objectValue)
  119. acl, err := s.bucket.GetObjectACL(objectName)
  120. c.Assert(err, IsNil)
  121. testLogger.Println("aclRes:", acl)
  122. c.Assert(acl.ACL, Equals, "default")
  123. err = s.bucket.DeleteObject(objectName)
  124. c.Assert(err, IsNil)
  125. // Put bytes
  126. err = s.bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
  127. c.Assert(err, IsNil)
  128. // Check
  129. body, err = s.bucket.GetObject(objectName)
  130. c.Assert(err, IsNil)
  131. str, err = readBody(body)
  132. c.Assert(err, IsNil)
  133. c.Assert(str, Equals, objectValue)
  134. err = s.bucket.DeleteObject(objectName)
  135. c.Assert(err, IsNil)
  136. // Put file
  137. err = CreateFileAndWrite(objectName+".txt", []byte(objectValue))
  138. c.Assert(err, IsNil)
  139. fd, err := os.Open(objectName + ".txt")
  140. c.Assert(err, IsNil)
  141. err = s.bucket.PutObject(objectName, fd)
  142. c.Assert(err, IsNil)
  143. os.Remove(objectName + ".txt")
  144. // Check
  145. body, err = s.bucket.GetObject(objectName)
  146. c.Assert(err, IsNil)
  147. str, err = readBody(body)
  148. c.Assert(err, IsNil)
  149. c.Assert(str, Equals, objectValue)
  150. err = s.bucket.DeleteObject(objectName)
  151. c.Assert(err, IsNil)
  152. // Put with properties
  153. objectName = objectNamePrefix + RandStr(8)
  154. options := []Option{
  155. Expires(futureDate),
  156. ObjectACL(ACLPublicRead),
  157. Meta("myprop", "mypropval"),
  158. }
  159. err = s.bucket.PutObject(objectName, strings.NewReader(objectValue), options...)
  160. c.Assert(err, IsNil)
  161. // Check
  162. body, err = s.bucket.GetObject(objectName)
  163. c.Assert(err, IsNil)
  164. str, err = readBody(body)
  165. c.Assert(err, IsNil)
  166. c.Assert(str, Equals, objectValue)
  167. acl, err = s.bucket.GetObjectACL(objectName)
  168. c.Assert(err, IsNil)
  169. testLogger.Println("GetObjectACL:", acl)
  170. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  171. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  172. c.Assert(err, IsNil)
  173. testLogger.Println("GetObjectDetailedMeta:", meta)
  174. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  175. err = s.bucket.DeleteObject(objectName)
  176. c.Assert(err, IsNil)
  177. }
  178. func (s *OssBucketSuite) SignURLTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
  179. objectName := objectNamePrefix + RandStr(8)
  180. objectValue := RandStr(20)
  181. filePath := RandLowStr(10)
  182. content := "复写object"
  183. CreateFile(filePath, content, c)
  184. notExistfilePath := RandLowStr(10)
  185. os.Remove(notExistfilePath)
  186. oldType := s.bucket.Client.Config.AuthVersion
  187. oldHeaders := s.bucket.Client.Config.AdditionalHeaders
  188. s.bucket.Client.Config.AuthVersion = authVersion
  189. s.bucket.Client.Config.AdditionalHeaders = extraHeaders
  190. // Sign URL for put
  191. str, err := s.bucket.SignURL(objectName, HTTPPut, 60)
  192. c.Assert(err, IsNil)
  193. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  194. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  195. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  196. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  197. } else {
  198. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  199. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  200. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  201. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  202. }
  203. // Error put object with URL
  204. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue), ContentType("image/tiff"))
  205. c.Assert(err, NotNil)
  206. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  207. err = s.bucket.PutObjectFromFileWithURL(str, filePath, ContentType("image/tiff"))
  208. c.Assert(err, NotNil)
  209. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  210. // Put object with URL
  211. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  212. c.Assert(err, IsNil)
  213. acl, err := s.bucket.GetObjectACL(objectName)
  214. c.Assert(err, IsNil)
  215. c.Assert(acl.ACL, Equals, "default")
  216. // Get object meta
  217. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  218. c.Assert(err, IsNil)
  219. c.Assert(meta.Get(HTTPHeaderContentType), Equals, "application/octet-stream")
  220. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "")
  221. // Sign URL for function GetObjectWithURL
  222. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  223. c.Assert(err, IsNil)
  224. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  225. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  226. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  227. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  228. } else {
  229. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  230. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  231. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  232. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  233. }
  234. // Get object with URL
  235. body, err := s.bucket.GetObjectWithURL(str)
  236. c.Assert(err, IsNil)
  237. str, err = readBody(body)
  238. c.Assert(err, IsNil)
  239. c.Assert(str, Equals, objectValue)
  240. // Sign URL for function PutObjectWithURL
  241. options := []Option{
  242. ObjectACL(ACLPublicRead),
  243. Meta("myprop", "mypropval"),
  244. ContentType("image/tiff"),
  245. ResponseContentEncoding("deflate"),
  246. }
  247. str, err = s.bucket.SignURL(objectName, HTTPPut, 60, options...)
  248. c.Assert(err, IsNil)
  249. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  250. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  251. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  252. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  253. } else {
  254. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  255. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  256. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  257. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  258. }
  259. // Put object with URL from file
  260. // Without option, error
  261. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  262. c.Assert(err, NotNil)
  263. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  264. err = s.bucket.PutObjectFromFileWithURL(str, filePath)
  265. c.Assert(err, NotNil)
  266. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  267. // With option, error file
  268. err = s.bucket.PutObjectFromFileWithURL(str, notExistfilePath, options...)
  269. c.Assert(err, NotNil)
  270. // With option
  271. err = s.bucket.PutObjectFromFileWithURL(str, filePath, options...)
  272. c.Assert(err, IsNil)
  273. // Get object meta
  274. meta, err = s.bucket.GetObjectDetailedMeta(objectName)
  275. c.Assert(err, IsNil)
  276. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  277. c.Assert(meta.Get(HTTPHeaderContentType), Equals, "image/tiff")
  278. acl, err = s.bucket.GetObjectACL(objectName)
  279. c.Assert(err, IsNil)
  280. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  281. // Sign URL for function GetObjectToFileWithURL
  282. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  283. c.Assert(err, IsNil)
  284. // Get object to file with URL
  285. newFile := RandStr(10)
  286. err = s.bucket.GetObjectToFileWithURL(str, newFile)
  287. c.Assert(err, IsNil)
  288. eq, err := compareFiles(filePath, newFile)
  289. c.Assert(err, IsNil)
  290. c.Assert(eq, Equals, true)
  291. os.Remove(newFile)
  292. // Get object to file error
  293. err = s.bucket.GetObjectToFileWithURL(str, newFile, options...)
  294. c.Assert(err, NotNil)
  295. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  296. _, err = os.Stat(newFile)
  297. c.Assert(err, NotNil)
  298. // Get object error
  299. body, err = s.bucket.GetObjectWithURL(str, options...)
  300. c.Assert(err, NotNil)
  301. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  302. c.Assert(body, IsNil)
  303. // Sign URL for function GetObjectToFileWithURL
  304. options = []Option{
  305. Expires(futureDate),
  306. ObjectACL(ACLPublicRead),
  307. Meta("myprop", "mypropval"),
  308. ContentType("image/tiff"),
  309. ResponseContentEncoding("deflate"),
  310. }
  311. str, err = s.bucket.SignURL(objectName, HTTPGet, 60, options...)
  312. c.Assert(err, IsNil)
  313. // Get object to file with URL and options
  314. err = s.bucket.GetObjectToFileWithURL(str, newFile, options...)
  315. c.Assert(err, IsNil)
  316. eq, err = compareFiles(filePath, newFile)
  317. c.Assert(err, IsNil)
  318. c.Assert(eq, Equals, true)
  319. os.Remove(newFile)
  320. // Get object to file error
  321. err = s.bucket.GetObjectToFileWithURL(str, newFile)
  322. c.Assert(err, NotNil)
  323. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  324. _, err = os.Stat(newFile)
  325. c.Assert(err, NotNil)
  326. // Get object error
  327. body, err = s.bucket.GetObjectWithURL(str)
  328. c.Assert(err, NotNil)
  329. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  330. c.Assert(body, IsNil)
  331. err = s.bucket.PutObjectFromFile(objectName, "../sample/The Go Programming Language.html")
  332. c.Assert(err, IsNil)
  333. str, err = s.bucket.SignURL(objectName, HTTPGet, 3600, AcceptEncoding("gzip"))
  334. c.Assert(err, IsNil)
  335. s.bucket.GetObjectToFileWithURL(str, newFile)
  336. c.Assert(err, IsNil)
  337. os.Remove(filePath)
  338. os.Remove(newFile)
  339. // Sign URL error
  340. str, err = s.bucket.SignURL(objectName, HTTPGet, -1)
  341. c.Assert(err, NotNil)
  342. err = s.bucket.DeleteObject(objectName)
  343. c.Assert(err, IsNil)
  344. // Invalid URL parse
  345. str = RandStr(20)
  346. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  347. c.Assert(err, NotNil)
  348. err = s.bucket.GetObjectToFileWithURL(str, newFile)
  349. c.Assert(err, NotNil)
  350. s.bucket.Client.Config.AuthVersion = oldType
  351. s.bucket.Client.Config.AdditionalHeaders = oldHeaders
  352. }
  353. func (s *OssBucketSuite) TestSignURL(c *C) {
  354. s.SignURLTestFunc(c, AuthV1, []string{})
  355. s.SignURLTestFunc(c, AuthV2, []string{})
  356. s.SignURLTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
  357. }
  358. func (s *OssBucketSuite) SignURLWithEscapedKeyTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
  359. // Key with '/'
  360. objectName := "zyimg/86/e8/653b5dc97bb0022051a84c632bc4"
  361. objectValue := "弃我去者,昨日之日不可留;乱我心者,今日之日多烦忧。长风万里送秋雁,对此可以酣高楼。蓬莱文章建安骨,中间小谢又清发。" +
  362. "俱怀逸兴壮思飞,欲上青天揽明月。抽刀断水水更流,举杯销愁愁更愁。人生在世不称意,明朝散发弄扁舟。"
  363. oldType := s.bucket.Client.Config.AuthVersion
  364. oldHeaders := s.bucket.Client.Config.AdditionalHeaders
  365. s.bucket.Client.Config.AuthVersion = authVersion
  366. s.bucket.Client.Config.AdditionalHeaders = extraHeaders
  367. // Sign URL for function PutObjectWithURL
  368. str, err := s.bucket.SignURL(objectName, HTTPPut, 60)
  369. c.Assert(err, IsNil)
  370. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  371. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  372. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  373. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  374. } else {
  375. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  376. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  377. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  378. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  379. }
  380. // Put object with URL
  381. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  382. c.Assert(err, IsNil)
  383. // Sign URL for function GetObjectWithURL
  384. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  385. c.Assert(err, IsNil)
  386. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  387. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  388. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  389. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  390. } else {
  391. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  392. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  393. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  394. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  395. }
  396. // Get object with URL
  397. body, err := s.bucket.GetObjectWithURL(str)
  398. c.Assert(err, IsNil)
  399. str, err = readBody(body)
  400. c.Assert(err, IsNil)
  401. c.Assert(str, Equals, objectValue)
  402. // Key with escaped chars
  403. objectName = "<>[]()`?.,!@#$%^&'/*-_=+~:;"
  404. // Sign URL for funciton PutObjectWithURL
  405. str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
  406. c.Assert(err, IsNil)
  407. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  408. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  409. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  410. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  411. } else {
  412. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  413. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  414. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  415. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  416. }
  417. // Put object with URL
  418. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  419. c.Assert(err, IsNil)
  420. // Sign URL for function GetObjectWithURL
  421. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  422. c.Assert(err, IsNil)
  423. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  424. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  425. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  426. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  427. } else {
  428. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  429. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  430. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  431. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  432. }
  433. // Get object with URL
  434. body, err = s.bucket.GetObjectWithURL(str)
  435. c.Assert(err, IsNil)
  436. str, err = readBody(body)
  437. c.Assert(err, IsNil)
  438. c.Assert(str, Equals, objectValue)
  439. // Key with Chinese chars
  440. objectName = "风吹柳花满店香,吴姬压酒劝客尝。金陵子弟来相送,欲行不行各尽觞。请君试问东流水,别意与之谁短长。"
  441. // Sign URL for function PutObjectWithURL
  442. str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
  443. c.Assert(err, IsNil)
  444. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  445. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  446. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  447. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  448. } else {
  449. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  450. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  451. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  452. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  453. }
  454. // Put object with URL
  455. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  456. c.Assert(err, IsNil)
  457. // Sign URL for get function GetObjectWithURL
  458. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  459. c.Assert(err, IsNil)
  460. if s.bucket.Client.Config.AuthVersion == AuthV1 {
  461. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  462. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  463. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  464. } else {
  465. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  466. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  467. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  468. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  469. }
  470. // Get object with URL
  471. body, err = s.bucket.GetObjectWithURL(str)
  472. c.Assert(err, IsNil)
  473. str, err = readBody(body)
  474. c.Assert(err, IsNil)
  475. c.Assert(str, Equals, objectValue)
  476. // Key
  477. objectName = "test/此情无计可消除/才下眉头/却上 心头/。,;:‘’“”?()『』【】《》!@#¥%……&×/test+ =-_*&^%$#@!`~[]{}()<>|\\/?.,;.txt"
  478. // Sign URL for function PutObjectWithURL
  479. str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
  480. c.Assert(err, IsNil)
  481. // Put object with URL
  482. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  483. c.Assert(err, IsNil)
  484. // Sign URL for function GetObjectWithURL
  485. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  486. c.Assert(err, IsNil)
  487. // Get object with URL
  488. body, err = s.bucket.GetObjectWithURL(str)
  489. c.Assert(err, IsNil)
  490. str, err = readBody(body)
  491. c.Assert(err, IsNil)
  492. c.Assert(str, Equals, objectValue)
  493. // Put object
  494. err = s.bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
  495. c.Assert(err, IsNil)
  496. // Get object
  497. body, err = s.bucket.GetObject(objectName)
  498. c.Assert(err, IsNil)
  499. str, err = readBody(body)
  500. c.Assert(err, IsNil)
  501. c.Assert(str, Equals, objectValue)
  502. // Delete object
  503. err = s.bucket.DeleteObject(objectName)
  504. c.Assert(err, IsNil)
  505. s.bucket.Client.Config.AuthVersion = oldType
  506. s.bucket.Client.Config.AdditionalHeaders = oldHeaders
  507. }
  508. func (s *OssBucketSuite) TestSignURLWithEscapedKey(c *C) {
  509. s.SignURLWithEscapedKeyTestFunc(c, AuthV1, []string{})
  510. s.SignURLWithEscapedKeyTestFunc(c, AuthV2, []string{})
  511. s.SignURLWithEscapedKeyTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
  512. }
  513. func (s *OssBucketSuite) SignURLWithEscapedKeyAndPorxyTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
  514. // Key with '/'
  515. objectName := "zyimg/86/e8/653b5dc97bb0022051a84c632bc4"
  516. objectValue := "弃我去者,昨日之日不可留;乱我心者,今日之日多烦忧。长风万里送秋雁,对此可以酣高楼。蓬莱文章建安骨,中间小谢又清发。" +
  517. "俱怀逸兴壮思飞,欲上青天揽明月。抽刀断水水更流,举杯销愁愁更愁。人生在世不称意,明朝散发弄扁舟。"
  518. options := []ClientOption{
  519. AuthProxy(proxyHost, proxyUser, proxyPasswd),
  520. AuthVersion(authVersion),
  521. AdditionalHeaders(extraHeaders),
  522. }
  523. client, err := New(endpoint, accessID, accessKey, options...)
  524. bucket, err := client.Bucket(bucketName)
  525. // Sign URL for put
  526. str, err := bucket.SignURL(objectName, HTTPPut, 60)
  527. c.Assert(err, IsNil)
  528. if bucket.Client.Config.AuthVersion == AuthV1 {
  529. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  530. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  531. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  532. } else {
  533. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  534. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  535. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  536. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  537. }
  538. // Put object with URL
  539. err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  540. c.Assert(err, IsNil)
  541. // Sign URL for function GetObjectWithURL
  542. str, err = bucket.SignURL(objectName, HTTPGet, 60)
  543. c.Assert(err, IsNil)
  544. if bucket.Client.Config.AuthVersion == AuthV1 {
  545. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  546. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  547. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  548. } else {
  549. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  550. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  551. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  552. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  553. }
  554. // Get object with URL
  555. body, err := bucket.GetObjectWithURL(str)
  556. c.Assert(err, IsNil)
  557. str, err = readBody(body)
  558. c.Assert(err, IsNil)
  559. c.Assert(str, Equals, objectValue)
  560. // Key with Chinese chars
  561. objectName = "test/此情无计可消除/才下眉头/却上 心头/。,;:‘’“”?()『』【】《》!@#¥%……&×/test+ =-_*&^%$#@!`~[]{}()<>|\\/?.,;.txt"
  562. // Sign URL for function PutObjectWithURL
  563. str, err = bucket.SignURL(objectName, HTTPPut, 60)
  564. c.Assert(err, IsNil)
  565. // Put object with URL
  566. err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  567. c.Assert(err, IsNil)
  568. // Sign URL for function GetObjectWithURL
  569. str, err = bucket.SignURL(objectName, HTTPGet, 60)
  570. c.Assert(err, IsNil)
  571. // Get object with URL
  572. body, err = bucket.GetObjectWithURL(str)
  573. c.Assert(err, IsNil)
  574. str, err = readBody(body)
  575. c.Assert(err, IsNil)
  576. c.Assert(str, Equals, objectValue)
  577. // Put object
  578. err = bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
  579. c.Assert(err, IsNil)
  580. // Get object
  581. body, err = bucket.GetObject(objectName)
  582. c.Assert(err, IsNil)
  583. str, err = readBody(body)
  584. c.Assert(err, IsNil)
  585. c.Assert(str, Equals, objectValue)
  586. // Delete object
  587. err = bucket.DeleteObject(objectName)
  588. c.Assert(err, IsNil)
  589. }
  590. func (s *OssBucketSuite) TestSignURLWithEscapedKeyAndPorxy(c *C) {
  591. s.SignURLWithEscapedKeyAndPorxyTestFunc(c, AuthV1, []string{})
  592. s.SignURLWithEscapedKeyAndPorxyTestFunc(c, AuthV2, []string{})
  593. s.SignURLWithEscapedKeyAndPorxyTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
  594. }
  595. func (s *OssBucketSuite) TestQueryStringAuthV2(c *C) {
  596. client, err := New(endpoint, accessID, accessKey)
  597. c.Assert(err, IsNil)
  598. // set oss v2 signatrue
  599. client.Config.AuthVersion = AuthV2
  600. bucketName := bucketNamePrefix + RandLowStr(6)
  601. err = client.CreateBucket(bucketName)
  602. c.Assert(err, IsNil)
  603. bucket, err := client.Bucket(bucketName)
  604. // build QueryString
  605. QueryKey1 := "abc"
  606. QueryKey2 := "|abc"
  607. c.Assert(strings.Compare(QueryKey1, QueryKey2) < 0, Equals, true)
  608. c.Assert(strings.Compare(url.QueryEscape(QueryKey1), url.QueryEscape(QueryKey2)) > 0, Equals, true)
  609. options := []Option{}
  610. params := map[string]interface{}{}
  611. params[QueryKey1] = "queryValue1"
  612. params[QueryKey2] = "queryValue2"
  613. objectKey := objectNamePrefix + RandStr(8)
  614. resp, _ := bucket.do("HEAD", objectKey, params, options, nil, nil)
  615. // object not exist,no signature error
  616. c.Assert(resp.StatusCode, Equals, 404)
  617. ForceDeleteBucket(client, bucketName, c)
  618. }
  619. // TestPutObjectType
  620. func (s *OssBucketSuite) TestPutObjectType(c *C) {
  621. objectName := objectNamePrefix + RandStr(8)
  622. objectValue := "乱石穿空,惊涛拍岸,卷起千堆雪。 江山如画,一时多少豪杰。"
  623. // Put
  624. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  625. c.Assert(err, IsNil)
  626. // Check
  627. body, err := s.bucket.GetObject(objectName)
  628. c.Assert(err, IsNil)
  629. str, err := readBody(body)
  630. c.Assert(err, IsNil)
  631. c.Assert(str, Equals, objectValue)
  632. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  633. c.Assert(err, IsNil)
  634. c.Assert(meta.Get("Content-Type"), Equals, "application/octet-stream")
  635. err = s.bucket.DeleteObject(objectName)
  636. c.Assert(err, IsNil)
  637. // Put
  638. err = s.bucket.PutObject(objectName+".txt", strings.NewReader(objectValue))
  639. c.Assert(err, IsNil)
  640. meta, err = s.bucket.GetObjectDetailedMeta(objectName + ".txt")
  641. c.Assert(err, IsNil)
  642. c.Assert(strings.Contains(meta.Get("Content-Type"), "text/plain"), Equals, true)
  643. err = s.bucket.DeleteObject(objectName + ".txt")
  644. c.Assert(err, IsNil)
  645. // Put
  646. err = s.bucket.PutObject(objectName+".apk", strings.NewReader(objectValue))
  647. c.Assert(err, IsNil)
  648. meta, err = s.bucket.GetObjectDetailedMeta(objectName + ".apk")
  649. c.Assert(err, IsNil)
  650. c.Assert(meta.Get("Content-Type"), Equals, "application/vnd.android.package-archive")
  651. err = s.bucket.DeleteObject(objectName + ".txt")
  652. c.Assert(err, IsNil)
  653. }
  654. // TestPutObject
  655. func (s *OssBucketSuite) TestPutObjectKeyChars(c *C) {
  656. objectName := objectNamePrefix + RandStr(8)
  657. objectValue := "白日依山尽,黄河入海流。欲穷千里目,更上一层楼。"
  658. // Put
  659. objectKey := objectName + "十步杀一人,千里不留行。事了拂衣去,深藏身与名"
  660. err := s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
  661. c.Assert(err, IsNil)
  662. // Check
  663. body, err := s.bucket.GetObject(objectKey)
  664. c.Assert(err, IsNil)
  665. str, err := readBody(body)
  666. c.Assert(err, IsNil)
  667. c.Assert(str, Equals, objectValue)
  668. err = s.bucket.DeleteObject(objectKey)
  669. c.Assert(err, IsNil)
  670. // Put
  671. objectKey = objectName + "ごきげん如何ですかおれの顔をよく拝んでおけ"
  672. err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
  673. c.Assert(err, IsNil)
  674. // Check
  675. body, err = s.bucket.GetObject(objectKey)
  676. c.Assert(err, IsNil)
  677. str, err = readBody(body)
  678. c.Assert(err, IsNil)
  679. c.Assert(str, Equals, objectValue)
  680. err = s.bucket.DeleteObject(objectKey)
  681. c.Assert(err, IsNil)
  682. // Put
  683. objectKey = objectName + "~!@#$%^&*()_-+=|\\[]{}<>,./?"
  684. err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
  685. c.Assert(err, IsNil)
  686. // Check
  687. body, err = s.bucket.GetObject(objectKey)
  688. c.Assert(err, IsNil)
  689. str, err = readBody(body)
  690. c.Assert(err, IsNil)
  691. c.Assert(str, Equals, objectValue)
  692. err = s.bucket.DeleteObject(objectKey)
  693. c.Assert(err, IsNil)
  694. // Put
  695. objectKey = "go/中国 日本 +-#&=*"
  696. err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
  697. c.Assert(err, IsNil)
  698. // Check
  699. body, err = s.bucket.GetObject(objectKey)
  700. c.Assert(err, IsNil)
  701. str, err = readBody(body)
  702. c.Assert(err, IsNil)
  703. c.Assert(str, Equals, objectValue)
  704. err = s.bucket.DeleteObject(objectKey)
  705. c.Assert(err, IsNil)
  706. }
  707. // TestPutObjectNegative
  708. func (s *OssBucketSuite) TestPutObjectNegative(c *C) {
  709. objectName := objectNamePrefix + RandStr(8)
  710. objectValue := "大江东去,浪淘尽,千古风流人物。 "
  711. // Put
  712. objectName = objectNamePrefix + RandStr(8)
  713. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue),
  714. Meta("meta-my", "myprop"))
  715. c.Assert(err, IsNil)
  716. // Check meta
  717. body, err := s.bucket.GetObject(objectName)
  718. c.Assert(err, IsNil)
  719. str, err := readBody(body)
  720. c.Assert(err, IsNil)
  721. c.Assert(str, Equals, objectValue)
  722. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  723. c.Assert(err, IsNil)
  724. c.Assert(meta.Get("X-Oss-Meta-My"), Not(Equals), "myprop")
  725. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "")
  726. err = s.bucket.DeleteObject(objectName)
  727. c.Assert(err, IsNil)
  728. // Invalid option
  729. err = s.bucket.PutObject(objectName, strings.NewReader(objectValue),
  730. IfModifiedSince(pastDate))
  731. c.Assert(err, NotNil)
  732. err = s.bucket.PutObjectFromFile(objectName, "bucket.go", IfModifiedSince(pastDate))
  733. c.Assert(err, NotNil)
  734. err = s.bucket.PutObjectFromFile(objectName, "/tmp/xxx")
  735. c.Assert(err, NotNil)
  736. }
  737. // TestPutObjectFromFile
  738. func (s *OssBucketSuite) TestPutObjectFromFile(c *C) {
  739. objectName := objectNamePrefix + RandStr(8)
  740. localFile := "../sample/BingWallpaper-2015-11-07.jpg"
  741. newFile := "newpic11.jpg"
  742. // Put
  743. err := s.bucket.PutObjectFromFile(objectName, localFile)
  744. c.Assert(err, IsNil)
  745. // Check
  746. err = s.bucket.GetObjectToFile(objectName, newFile)
  747. c.Assert(err, IsNil)
  748. eq, err := compareFiles(localFile, newFile)
  749. c.Assert(err, IsNil)
  750. c.Assert(eq, Equals, true)
  751. acl, err := s.bucket.GetObjectACL(objectName)
  752. c.Assert(err, IsNil)
  753. testLogger.Println("aclRes:", acl)
  754. c.Assert(acl.ACL, Equals, "default")
  755. err = s.bucket.DeleteObject(objectName)
  756. c.Assert(err, IsNil)
  757. // Put with properties
  758. options := []Option{
  759. Expires(futureDate),
  760. ObjectACL(ACLPublicRead),
  761. Meta("myprop", "mypropval"),
  762. }
  763. os.Remove(newFile)
  764. err = s.bucket.PutObjectFromFile(objectName, localFile, options...)
  765. c.Assert(err, IsNil)
  766. // Check
  767. err = s.bucket.GetObjectToFile(objectName, newFile)
  768. c.Assert(err, IsNil)
  769. eq, err = compareFiles(localFile, newFile)
  770. c.Assert(err, IsNil)
  771. c.Assert(eq, Equals, true)
  772. acl, err = s.bucket.GetObjectACL(objectName)
  773. c.Assert(err, IsNil)
  774. testLogger.Println("GetObjectACL:", acl)
  775. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  776. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  777. c.Assert(err, IsNil)
  778. testLogger.Println("GetObjectDetailedMeta:", meta)
  779. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  780. err = s.bucket.DeleteObject(objectName)
  781. c.Assert(err, IsNil)
  782. os.Remove(newFile)
  783. }
  784. // TestPutObjectFromFile
  785. func (s *OssBucketSuite) TestPutObjectFromFileType(c *C) {
  786. objectName := objectNamePrefix + RandStr(8)
  787. localFile := "../sample/BingWallpaper-2015-11-07.jpg"
  788. newFile := RandStr(8) + ".jpg"
  789. // Put
  790. err := s.bucket.PutObjectFromFile(objectName, localFile)
  791. c.Assert(err, IsNil)
  792. // Check
  793. err = s.bucket.GetObjectToFile(objectName, newFile)
  794. c.Assert(err, IsNil)
  795. eq, err := compareFiles(localFile, newFile)
  796. c.Assert(err, IsNil)
  797. c.Assert(eq, Equals, true)
  798. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  799. c.Assert(err, IsNil)
  800. c.Assert(meta.Get("Content-Type"), Equals, "image/jpeg")
  801. err = s.bucket.DeleteObject(objectName)
  802. c.Assert(err, IsNil)
  803. os.Remove(newFile)
  804. }
  805. // TestGetObject
  806. func (s *OssBucketSuite) TestGetObjectNormal(c *C) {
  807. objectName := objectNamePrefix + RandStr(8)
  808. objectValue := "长忆观潮,满郭人争江上望。来疑沧海尽成空,万面鼓声中。弄潮儿向涛头立,手把红旗旗不湿。别来几向梦中看,梦觉尚心寒。"
  809. // Put
  810. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  811. c.Assert(err, IsNil)
  812. // Check
  813. body, err := s.bucket.GetObject(objectName)
  814. c.Assert(err, IsNil)
  815. data, err := ioutil.ReadAll(body)
  816. body.Close()
  817. str := string(data)
  818. c.Assert(str, Equals, objectValue)
  819. testLogger.Println("GetObjec:", str)
  820. // Range
  821. var subObjectValue = string(([]byte(objectValue))[15:36])
  822. body, err = s.bucket.GetObject(objectName, Range(15, 35))
  823. c.Assert(err, IsNil)
  824. data, err = ioutil.ReadAll(body)
  825. body.Close()
  826. str = string(data)
  827. c.Assert(str, Equals, subObjectValue)
  828. testLogger.Println("GetObject:", str, ",", subObjectValue)
  829. // If-Modified-Since
  830. _, err = s.bucket.GetObject(objectName, IfModifiedSince(futureDate))
  831. c.Assert(err, NotNil)
  832. // If-Unmodified-Since
  833. body, err = s.bucket.GetObject(objectName, IfUnmodifiedSince(futureDate))
  834. c.Assert(err, IsNil)
  835. data, err = ioutil.ReadAll(body)
  836. body.Close()
  837. c.Assert(string(data), Equals, objectValue)
  838. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  839. c.Assert(err, IsNil)
  840. // If-Match
  841. body, err = s.bucket.GetObject(objectName, IfMatch(meta.Get("Etag")))
  842. c.Assert(err, IsNil)
  843. data, err = ioutil.ReadAll(body)
  844. body.Close()
  845. c.Assert(string(data), Equals, objectValue)
  846. // If-None-Match
  847. _, err = s.bucket.GetObject(objectName, IfNoneMatch(meta.Get("Etag")))
  848. c.Assert(err, NotNil)
  849. // process
  850. err = s.bucket.PutObjectFromFile(objectName, "../sample/BingWallpaper-2015-11-07.jpg")
  851. c.Assert(err, IsNil)
  852. _, err = s.bucket.GetObject(objectName, Process("image/format,png"))
  853. c.Assert(err, IsNil)
  854. err = s.bucket.DeleteObject(objectName)
  855. c.Assert(err, IsNil)
  856. }
  857. // TestGetObjectNegative
  858. func (s *OssBucketSuite) TestGetObjectToWriterNegative(c *C) {
  859. objectName := objectNamePrefix + RandStr(8)
  860. objectValue := "长忆观潮,满郭人争江上望。"
  861. // Object not exist
  862. _, err := s.bucket.GetObject("NotExist")
  863. c.Assert(err, NotNil)
  864. // Constraint invalid
  865. err = s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  866. c.Assert(err, IsNil)
  867. // Out of range
  868. _, err = s.bucket.GetObject(objectName, Range(15, 1000))
  869. c.Assert(err, IsNil)
  870. // Not exist
  871. err = s.bucket.GetObjectToFile(objectName, "/root1/123abc9874")
  872. c.Assert(err, NotNil)
  873. // Invalid option
  874. _, err = s.bucket.GetObject(objectName, ACL(ACLPublicRead))
  875. c.Assert(err, IsNil)
  876. err = s.bucket.GetObjectToFile(objectName, "newpic15.jpg", ACL(ACLPublicRead))
  877. c.Assert(err, IsNil)
  878. err = s.bucket.DeleteObject(objectName)
  879. c.Assert(err, IsNil)
  880. }
  881. // TestGetObjectToFile
  882. func (s *OssBucketSuite) TestGetObjectToFile(c *C) {
  883. objectName := objectNamePrefix + RandStr(8)
  884. objectValue := "江南好,风景旧曾谙;日出江花红胜火,春来江水绿如蓝。能不忆江南?江南忆,最忆是杭州;山寺月中寻桂子,郡亭枕上看潮头。何日更重游!"
  885. newFile := RandStr(8) + ".jpg"
  886. // Put
  887. var val = []byte(objectValue)
  888. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  889. c.Assert(err, IsNil)
  890. // Check
  891. err = s.bucket.GetObjectToFile(objectName, newFile)
  892. c.Assert(err, IsNil)
  893. eq, err := compareFileData(newFile, val)
  894. c.Assert(err, IsNil)
  895. c.Assert(eq, Equals, true)
  896. os.Remove(newFile)
  897. // Range
  898. err = s.bucket.GetObjectToFile(objectName, newFile, Range(15, 35))
  899. c.Assert(err, IsNil)
  900. eq, err = compareFileData(newFile, val[15:36])
  901. c.Assert(err, IsNil)
  902. c.Assert(eq, Equals, true)
  903. os.Remove(newFile)
  904. err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("15-35"))
  905. c.Assert(err, IsNil)
  906. eq, err = compareFileData(newFile, val[15:36])
  907. c.Assert(err, IsNil)
  908. c.Assert(eq, Equals, true)
  909. os.Remove(newFile)
  910. err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("15-"))
  911. c.Assert(err, IsNil)
  912. eq, err = compareFileData(newFile, val[15:])
  913. c.Assert(err, IsNil)
  914. c.Assert(eq, Equals, true)
  915. os.Remove(newFile)
  916. err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("-10"))
  917. c.Assert(err, IsNil)
  918. eq, err = compareFileData(newFile, val[(len(val)-10):len(val)])
  919. c.Assert(err, IsNil)
  920. c.Assert(eq, Equals, true)
  921. os.Remove(newFile)
  922. // If-Modified-Since
  923. err = s.bucket.GetObjectToFile(objectName, newFile, IfModifiedSince(futureDate))
  924. c.Assert(err, NotNil)
  925. // If-Unmodified-Since
  926. err = s.bucket.GetObjectToFile(objectName, newFile, IfUnmodifiedSince(futureDate))
  927. c.Assert(err, IsNil)
  928. eq, err = compareFileData(newFile, val)
  929. c.Assert(err, IsNil)
  930. c.Assert(eq, Equals, true)
  931. os.Remove(newFile)
  932. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  933. c.Assert(err, IsNil)
  934. testLogger.Println("GetObjectDetailedMeta:", meta)
  935. // If-Match
  936. err = s.bucket.GetObjectToFile(objectName, newFile, IfMatch(meta.Get("Etag")))
  937. c.Assert(err, IsNil)
  938. eq, err = compareFileData(newFile, val)
  939. c.Assert(err, IsNil)
  940. c.Assert(eq, Equals, true)
  941. // If-None-Match
  942. err = s.bucket.GetObjectToFile(objectName, newFile, IfNoneMatch(meta.Get("Etag")))
  943. c.Assert(err, NotNil)
  944. // Accept-Encoding:gzip
  945. err = s.bucket.PutObjectFromFile(objectName, "../sample/The Go Programming Language.html")
  946. c.Assert(err, IsNil)
  947. err = s.bucket.GetObjectToFile(objectName, newFile, AcceptEncoding("gzip"))
  948. c.Assert(err, IsNil)
  949. os.Remove(newFile)
  950. err = s.bucket.DeleteObject(objectName)
  951. c.Assert(err, IsNil)
  952. }
  953. // TestListObjects
  954. func (s *OssBucketSuite) TestListObjects(c *C) {
  955. objectName := objectNamePrefix + RandStr(8)
  956. // List empty bucket
  957. lor, err := s.bucket.ListObjects()
  958. c.Assert(err, IsNil)
  959. left := len(lor.Objects)
  960. // Put three objects
  961. err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  962. c.Assert(err, IsNil)
  963. err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
  964. c.Assert(err, IsNil)
  965. err = s.bucket.PutObject(objectName+"3", strings.NewReader(""))
  966. c.Assert(err, IsNil)
  967. // List
  968. lor, err = s.bucket.ListObjects()
  969. c.Assert(err, IsNil)
  970. c.Assert(len(lor.Objects), Equals, left+3)
  971. // List with prefix
  972. lor, err = s.bucket.ListObjects(Prefix(objectName + "2"))
  973. c.Assert(err, IsNil)
  974. c.Assert(len(lor.Objects), Equals, 1)
  975. lor, err = s.bucket.ListObjects(Prefix(objectName + "22"))
  976. c.Assert(err, IsNil)
  977. c.Assert(len(lor.Objects), Equals, 0)
  978. // List with max keys
  979. lor, err = s.bucket.ListObjects(Prefix(objectName), MaxKeys(2))
  980. c.Assert(err, IsNil)
  981. c.Assert(len(lor.Objects), Equals, 2)
  982. // List with marker
  983. lor, err = s.bucket.ListObjects(Marker(objectName+"1"), MaxKeys(1))
  984. c.Assert(err, IsNil)
  985. c.Assert(len(lor.Objects), Equals, 1)
  986. err = s.bucket.DeleteObject(objectName + "1")
  987. c.Assert(err, IsNil)
  988. err = s.bucket.DeleteObject(objectName + "2")
  989. c.Assert(err, IsNil)
  990. err = s.bucket.DeleteObject(objectName + "3")
  991. c.Assert(err, IsNil)
  992. }
  993. // TestListObjects
  994. func (s *OssBucketSuite) TestListObjectsEncodingType(c *C) {
  995. prefix := objectNamePrefix + "床前明月光,疑是地上霜。举头望明月,低头思故乡。"
  996. for i := 0; i < 10; i++ {
  997. err := s.bucket.PutObject(prefix+strconv.Itoa(i), strings.NewReader(""))
  998. c.Assert(err, IsNil)
  999. }
  1000. lor, err := s.bucket.ListObjects(Prefix(objectNamePrefix + "床前明月光,"))
  1001. c.Assert(err, IsNil)
  1002. c.Assert(len(lor.Objects), Equals, 10)
  1003. lor, err = s.bucket.ListObjects(Marker(objectNamePrefix + "床前明月光,疑是地上霜。举头望明月,低头思故乡。"))
  1004. c.Assert(err, IsNil)
  1005. c.Assert(len(lor.Objects), Equals, 10)
  1006. lor, err = s.bucket.ListObjects(Prefix(objectNamePrefix + "床前明月光"))
  1007. c.Assert(err, IsNil)
  1008. for i, obj := range lor.Objects {
  1009. c.Assert(obj.Key, Equals, prefix+strconv.Itoa(i))
  1010. }
  1011. for i := 0; i < 10; i++ {
  1012. err = s.bucket.DeleteObject(prefix + strconv.Itoa(i))
  1013. c.Assert(err, IsNil)
  1014. }
  1015. // Special characters
  1016. objectName := objectNamePrefix + "` ~ ! @ # $ % ^ & * () - _ + =[] {} \\ | < > , . ? / 0"
  1017. err = s.bucket.PutObject(objectName, strings.NewReader("明月几时有,把酒问青天"))
  1018. c.Assert(err, IsNil)
  1019. lor, err = s.bucket.ListObjects(Prefix(objectName))
  1020. c.Assert(err, IsNil)
  1021. c.Assert(len(lor.Objects), Equals, 1)
  1022. err = s.bucket.DeleteObject(objectName)
  1023. c.Assert(err, IsNil)
  1024. objectName = objectNamePrefix + "中国 日本 +-#&=*"
  1025. err = s.bucket.PutObject(objectName, strings.NewReader("明月几时有,把酒问青天"))
  1026. c.Assert(err, IsNil)
  1027. lor, err = s.bucket.ListObjects(Prefix(objectName))
  1028. c.Assert(err, IsNil)
  1029. c.Assert(len(lor.Objects), Equals, 1)
  1030. err = s.bucket.DeleteObject(objectName)
  1031. c.Assert(err, IsNil)
  1032. }
  1033. // TestIsBucketExist
  1034. func (s *OssBucketSuite) TestIsObjectExist(c *C) {
  1035. objectName := objectNamePrefix + RandStr(8)
  1036. // Put three objects
  1037. err := s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  1038. c.Assert(err, IsNil)
  1039. err = s.bucket.PutObject(objectName+"11", strings.NewReader(""))
  1040. c.Assert(err, IsNil)
  1041. err = s.bucket.PutObject(objectName+"111", strings.NewReader(""))
  1042. c.Assert(err, IsNil)
  1043. // Exist
  1044. exist, err := s.bucket.IsObjectExist(objectName + "11")
  1045. c.Assert(err, IsNil)
  1046. c.Assert(exist, Equals, true)
  1047. exist, err = s.bucket.IsObjectExist(objectName + "1")
  1048. c.Assert(err, IsNil)
  1049. c.Assert(exist, Equals, true)
  1050. exist, err = s.bucket.IsObjectExist(objectName + "111")
  1051. c.Assert(err, IsNil)
  1052. c.Assert(exist, Equals, true)
  1053. // Not exist
  1054. exist, err = s.bucket.IsObjectExist(objectName + "1111")
  1055. c.Assert(err, IsNil)
  1056. c.Assert(exist, Equals, false)
  1057. exist, err = s.bucket.IsObjectExist(objectName)
  1058. c.Assert(err, IsNil)
  1059. c.Assert(exist, Equals, false)
  1060. err = s.bucket.DeleteObject(objectName + "1")
  1061. c.Assert(err, IsNil)
  1062. err = s.bucket.DeleteObject(objectName + "11")
  1063. c.Assert(err, IsNil)
  1064. err = s.bucket.DeleteObject(objectName + "111")
  1065. c.Assert(err, IsNil)
  1066. }
  1067. // TestDeleteObject
  1068. func (s *OssBucketSuite) TestDeleteObject(c *C) {
  1069. objectName := objectNamePrefix + RandStr(8)
  1070. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  1071. c.Assert(err, IsNil)
  1072. lor, err := s.bucket.ListObjects(Prefix(objectName))
  1073. c.Assert(err, IsNil)
  1074. c.Assert(len(lor.Objects), Equals, 1)
  1075. // Delete
  1076. err = s.bucket.DeleteObject(objectName)
  1077. c.Assert(err, IsNil)
  1078. // Duplicate delete
  1079. err = s.bucket.DeleteObject(objectName)
  1080. c.Assert(err, IsNil)
  1081. lor, err = s.bucket.ListObjects(Prefix(objectName))
  1082. c.Assert(err, IsNil)
  1083. c.Assert(len(lor.Objects), Equals, 0)
  1084. }
  1085. // TestDeleteObjects
  1086. func (s *OssBucketSuite) TestDeleteObjectsNormal(c *C) {
  1087. objectName := objectNamePrefix + RandStr(8)
  1088. // Delete objects
  1089. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  1090. c.Assert(err, IsNil)
  1091. res, err := s.bucket.DeleteObjects([]string{objectName})
  1092. c.Assert(err, IsNil)
  1093. c.Assert(len(res.DeletedObjects), Equals, 1)
  1094. lor, err := s.bucket.ListObjects(Prefix(objectName))
  1095. c.Assert(err, IsNil)
  1096. c.Assert(len(lor.Objects), Equals, 0)
  1097. // Delete objects
  1098. err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  1099. c.Assert(err, IsNil)
  1100. err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
  1101. c.Assert(err, IsNil)
  1102. res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"})
  1103. c.Assert(err, IsNil)
  1104. c.Assert(len(res.DeletedObjects), Equals, 2)
  1105. lor, err = s.bucket.ListObjects(Prefix(objectName))
  1106. c.Assert(err, IsNil)
  1107. c.Assert(len(lor.Objects), Equals, 0)
  1108. // Delete 0
  1109. _, err = s.bucket.DeleteObjects([]string{})
  1110. c.Assert(err, NotNil)
  1111. // DeleteObjectsQuiet
  1112. err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  1113. c.Assert(err, IsNil)
  1114. err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
  1115. c.Assert(err, IsNil)
  1116. res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"},
  1117. DeleteObjectsQuiet(false))
  1118. c.Assert(err, IsNil)
  1119. c.Assert(len(res.DeletedObjects), Equals, 2)
  1120. lor, err = s.bucket.ListObjects(Prefix(objectName))
  1121. c.Assert(err, IsNil)
  1122. c.Assert(len(lor.Objects), Equals, 0)
  1123. // DeleteObjectsQuiet
  1124. err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  1125. c.Assert(err, IsNil)
  1126. err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
  1127. c.Assert(err, IsNil)
  1128. res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"},
  1129. DeleteObjectsQuiet(true))
  1130. c.Assert(err, IsNil)
  1131. c.Assert(len(res.DeletedObjects), Equals, 0)
  1132. lor, err = s.bucket.ListObjects(Prefix(objectName))
  1133. c.Assert(err, IsNil)
  1134. c.Assert(len(lor.Objects), Equals, 0)
  1135. // EncodingType
  1136. err = s.bucket.PutObject("中国人", strings.NewReader(""))
  1137. c.Assert(err, IsNil)
  1138. res, err = s.bucket.DeleteObjects([]string{"中国人"})
  1139. c.Assert(err, IsNil)
  1140. c.Assert(len(res.DeletedObjects), Equals, 1)
  1141. c.Assert(res.DeletedObjects[0], Equals, "中国人")
  1142. // EncodingType
  1143. err = s.bucket.PutObject("中国人", strings.NewReader(""))
  1144. c.Assert(err, IsNil)
  1145. res, err = s.bucket.DeleteObjects([]string{"中国人"}, DeleteObjectsQuiet(false))
  1146. c.Assert(err, IsNil)
  1147. c.Assert(len(res.DeletedObjects), Equals, 1)
  1148. c.Assert(res.DeletedObjects[0], Equals, "中国人")
  1149. // EncodingType
  1150. err = s.bucket.PutObject("中国人", strings.NewReader(""))
  1151. c.Assert(err, IsNil)
  1152. res, err = s.bucket.DeleteObjects([]string{"中国人"}, DeleteObjectsQuiet(true))
  1153. c.Assert(err, IsNil)
  1154. c.Assert(len(res.DeletedObjects), Equals, 0)
  1155. // Special characters
  1156. key := "A ' < > \" & ~ ` ! @ # $ % ^ & * ( ) [] {} - _ + = / | \\ ? . , : ; A"
  1157. err = s.bucket.PutObject(key, strings.NewReader("value"))
  1158. c.Assert(err, IsNil)
  1159. _, err = s.bucket.DeleteObjects([]string{key})
  1160. c.Assert(err, IsNil)
  1161. ress, err := s.bucket.ListObjects(Prefix(key))
  1162. c.Assert(err, IsNil)
  1163. c.Assert(len(ress.Objects), Equals, 0)
  1164. // Not exist
  1165. _, err = s.bucket.DeleteObjects([]string{"NotExistObject"})
  1166. c.Assert(err, IsNil)
  1167. }
  1168. // TestSetObjectMeta
  1169. func (s *OssBucketSuite) TestSetObjectMeta(c *C) {
  1170. objectName := objectNamePrefix + RandStr(8)
  1171. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  1172. c.Assert(err, IsNil)
  1173. err = s.bucket.SetObjectMeta(objectName,
  1174. Expires(futureDate),
  1175. Meta("myprop", "mypropval"))
  1176. c.Assert(err, IsNil)
  1177. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  1178. c.Assert(err, IsNil)
  1179. testLogger.Println("Meta:", meta)
  1180. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  1181. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  1182. acl, err := s.bucket.GetObjectACL(objectName)
  1183. c.Assert(err, IsNil)
  1184. c.Assert(acl.ACL, Equals, "default")
  1185. // Invalid option
  1186. err = s.bucket.SetObjectMeta(objectName, AcceptEncoding("url"))
  1187. c.Assert(err, IsNil)
  1188. // Invalid option value
  1189. err = s.bucket.SetObjectMeta(objectName, ServerSideEncryption("invalid"))
  1190. c.Assert(err, NotNil)
  1191. err = s.bucket.DeleteObject(objectName)
  1192. c.Assert(err, IsNil)
  1193. // Not exist
  1194. err = s.bucket.SetObjectMeta(objectName, Expires(futureDate))
  1195. c.Assert(err, NotNil)
  1196. }
  1197. // TestGetObjectMeta
  1198. func (s *OssBucketSuite) TestGetObjectMeta(c *C) {
  1199. objectName := objectNamePrefix + RandStr(8)
  1200. // Put
  1201. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  1202. c.Assert(err, IsNil)
  1203. meta, err := s.bucket.GetObjectMeta(objectName)
  1204. c.Assert(err, IsNil)
  1205. c.Assert(len(meta) > 0, Equals, true)
  1206. err = s.bucket.DeleteObject(objectName)
  1207. c.Assert(err, IsNil)
  1208. _, err = s.bucket.GetObjectMeta("NotExistObject")
  1209. c.Assert(err, NotNil)
  1210. }
  1211. // TestGetObjectDetailedMeta
  1212. func (s *OssBucketSuite) TestGetObjectDetailedMeta(c *C) {
  1213. objectName := objectNamePrefix + RandStr(8)
  1214. // Put
  1215. err := s.bucket.PutObject(objectName, strings.NewReader(""),
  1216. Expires(futureDate), Meta("myprop", "mypropval"))
  1217. c.Assert(err, IsNil)
  1218. // Check
  1219. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  1220. c.Assert(err, IsNil)
  1221. testLogger.Println("GetObjectDetailedMeta:", meta)
  1222. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  1223. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  1224. c.Assert(meta.Get("Content-Length"), Equals, "0")
  1225. c.Assert(len(meta.Get("Date")) > 0, Equals, true)
  1226. c.Assert(len(meta.Get("X-Oss-Request-Id")) > 0, Equals, true)
  1227. c.Assert(len(meta.Get("Last-Modified")) > 0, Equals, true)
  1228. // IfModifiedSince/IfModifiedSince
  1229. _, err = s.bucket.GetObjectDetailedMeta(objectName, IfModifiedSince(futureDate))
  1230. c.Assert(err, NotNil)
  1231. meta, err = s.bucket.GetObjectDetailedMeta(objectName, IfUnmodifiedSince(futureDate))
  1232. c.Assert(err, IsNil)
  1233. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  1234. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  1235. // IfMatch/IfNoneMatch
  1236. _, err = s.bucket.GetObjectDetailedMeta(objectName, IfNoneMatch(meta.Get("Etag")))
  1237. c.Assert(err, NotNil)
  1238. meta, err = s.bucket.GetObjectDetailedMeta(objectName, IfMatch(meta.Get("Etag")))
  1239. c.Assert(err, IsNil)
  1240. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  1241. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  1242. err = s.bucket.DeleteObject(objectName)
  1243. c.Assert(err, IsNil)
  1244. _, err = s.bucket.GetObjectDetailedMeta("NotExistObject")
  1245. c.Assert(err, NotNil)
  1246. }
  1247. // TestSetAndGetObjectAcl
  1248. func (s *OssBucketSuite) TestSetAndGetObjectAcl(c *C) {
  1249. objectName := objectNamePrefix + RandStr(8)
  1250. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  1251. c.Assert(err, IsNil)
  1252. // Default
  1253. acl, err := s.bucket.GetObjectACL(objectName)
  1254. c.Assert(err, IsNil)
  1255. c.Assert(acl.ACL, Equals, "default")
  1256. // Set ACL_PUBLIC_RW
  1257. err = s.bucket.SetObjectACL(objectName, ACLPublicReadWrite)
  1258. c.Assert(err, IsNil)
  1259. acl, err = s.bucket.GetObjectACL(objectName)
  1260. c.Assert(err, IsNil)
  1261. c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
  1262. // Set ACL_PRIVATE
  1263. err = s.bucket.SetObjectACL(objectName, ACLPrivate)
  1264. c.Assert(err, IsNil)
  1265. acl, err = s.bucket.GetObjectACL(objectName)
  1266. c.Assert(err, IsNil)
  1267. c.Assert(acl.ACL, Equals, string(ACLPrivate))
  1268. // Set ACL_PUBLIC_R
  1269. err = s.bucket.SetObjectACL(objectName, ACLPublicRead)
  1270. c.Assert(err, IsNil)
  1271. acl, err = s.bucket.GetObjectACL(objectName)
  1272. c.Assert(err, IsNil)
  1273. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  1274. err = s.bucket.DeleteObject(objectName)
  1275. c.Assert(err, IsNil)
  1276. }
  1277. // TestSetAndGetObjectAclNegative
  1278. func (s *OssBucketSuite) TestSetAndGetObjectAclNegative(c *C) {
  1279. objectName := objectNamePrefix + RandStr(8)
  1280. // Object not exist
  1281. err := s.bucket.SetObjectACL(objectName, ACLPublicRead)
  1282. c.Assert(err, NotNil)
  1283. }
  1284. // TestCopyObject
  1285. func (s *OssBucketSuite) TestCopyObject(c *C) {
  1286. objectName := objectNamePrefix + RandStr(8)
  1287. objectValue := "男儿何不带吴钩,收取关山五十州。请君暂上凌烟阁,若个书生万户侯?"
  1288. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue),
  1289. ACL(ACLPublicRead), Meta("my", "myprop"))
  1290. c.Assert(err, IsNil)
  1291. // Copy
  1292. var objectNameDest = objectName + "dest"
  1293. _, err = s.bucket.CopyObject(objectName, objectNameDest)
  1294. c.Assert(err, IsNil)
  1295. // Check
  1296. lor, err := s.bucket.ListObjects(Prefix(objectName))
  1297. c.Assert(err, IsNil)
  1298. testLogger.Println("objects:", lor.Objects)
  1299. c.Assert(len(lor.Objects), Equals, 2)
  1300. body, err := s.bucket.GetObject(objectName)
  1301. c.Assert(err, IsNil)
  1302. str, err := readBody(body)
  1303. c.Assert(err, IsNil)
  1304. c.Assert(str, Equals, objectValue)
  1305. err = s.bucket.DeleteObject(objectNameDest)
  1306. c.Assert(err, IsNil)
  1307. // Copy with constraints x-oss-copy-source-if-modified-since
  1308. _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfModifiedSince(futureDate))
  1309. c.Assert(err, NotNil)
  1310. testLogger.Println("CopyObject:", err)
  1311. // Copy with constraints x-oss-copy-source-if-unmodified-since
  1312. _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfUnmodifiedSince(futureDate))
  1313. c.Assert(err, IsNil)
  1314. // Check
  1315. lor, err = s.bucket.ListObjects(Prefix(objectName))
  1316. c.Assert(err, IsNil)
  1317. testLogger.Println("objects:", lor.Objects)
  1318. c.Assert(len(lor.Objects), Equals, 2)
  1319. body, err = s.bucket.GetObject(objectName)
  1320. c.Assert(err, IsNil)
  1321. str, err = readBody(body)
  1322. c.Assert(err, IsNil)
  1323. c.Assert(str, Equals, objectValue)
  1324. err = s.bucket.DeleteObject(objectNameDest)
  1325. c.Assert(err, IsNil)
  1326. // Copy with constraints x-oss-copy-source-if-match
  1327. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  1328. c.Assert(err, IsNil)
  1329. testLogger.Println("GetObjectDetailedMeta:", meta)
  1330. _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfMatch(meta.Get("Etag")))
  1331. c.Assert(err, IsNil)
  1332. // Check
  1333. body, err = s.bucket.GetObject(objectName)
  1334. c.Assert(err, IsNil)
  1335. str, err = readBody(body)
  1336. c.Assert(err, IsNil)
  1337. c.Assert(str, Equals, objectValue)
  1338. err = s.bucket.DeleteObject(objectNameDest)
  1339. c.Assert(err, IsNil)
  1340. // Copy with constraints x-oss-copy-source-if-none-match
  1341. _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfNoneMatch(meta.Get("Etag")))
  1342. c.Assert(err, NotNil)
  1343. // Copy with constraints x-oss-metadata-directive
  1344. _, err = s.bucket.CopyObject(objectName, objectNameDest, Meta("my", "mydestprop"),
  1345. MetadataDirective(MetaCopy))
  1346. c.Assert(err, IsNil)
  1347. // Check
  1348. body, err = s.bucket.GetObject(objectName)
  1349. c.Assert(err, IsNil)
  1350. str, err = readBody(body)
  1351. c.Assert(err, IsNil)
  1352. c.Assert(str, Equals, objectValue)
  1353. destMeta, err := s.bucket.GetObjectDetailedMeta(objectNameDest)
  1354. c.Assert(err, IsNil)
  1355. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
  1356. acl, err := s.bucket.GetObjectACL(objectNameDest)
  1357. c.Assert(err, IsNil)
  1358. c.Assert(acl.ACL, Equals, "default")
  1359. err = s.bucket.DeleteObject(objectNameDest)
  1360. c.Assert(err, IsNil)
  1361. // Copy with constraints x-oss-metadata-directive and self defined dest object meta
  1362. options := []Option{
  1363. ObjectACL(ACLPublicReadWrite),
  1364. Meta("my", "mydestprop"),
  1365. MetadataDirective(MetaReplace),
  1366. }
  1367. _, err = s.bucket.CopyObject(objectName, objectNameDest, options...)
  1368. c.Assert(err, IsNil)
  1369. // Check
  1370. body, err = s.bucket.GetObject(objectName)
  1371. c.Assert(err, IsNil)
  1372. str, err = readBody(body)
  1373. c.Assert(err, IsNil)
  1374. c.Assert(str, Equals, objectValue)
  1375. destMeta, err = s.bucket.GetObjectDetailedMeta(objectNameDest)
  1376. c.Assert(err, IsNil)
  1377. c.Assert(destMeta.Get("X-Oss-Meta-My"), Equals, "mydestprop")
  1378. acl, err = s.bucket.GetObjectACL(objectNameDest)
  1379. c.Assert(err, IsNil)
  1380. c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
  1381. err = s.bucket.DeleteObject(objectNameDest)
  1382. c.Assert(err, IsNil)
  1383. err = s.bucket.DeleteObject(objectName)
  1384. c.Assert(err, IsNil)
  1385. }
  1386. // TestCopyObjectToOrFrom
  1387. func (s *OssBucketSuite) TestCopyObjectToOrFrom(c *C) {
  1388. objectName := objectNamePrefix + RandStr(8)
  1389. objectValue := "男儿何不带吴钩,收取关山五十州。请君暂上凌烟阁,若个书生万户侯?"
  1390. destBucketName := bucketName + "-dest"
  1391. objectNameDest := objectName + "-dest"
  1392. err := s.client.CreateBucket(destBucketName)
  1393. c.Assert(err, IsNil)
  1394. destBucket, err := s.client.Bucket(destBucketName)
  1395. c.Assert(err, IsNil)
  1396. err = s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  1397. c.Assert(err, IsNil)
  1398. // Copy from
  1399. _, err = destBucket.CopyObjectFrom(bucketName, objectName, objectNameDest)
  1400. c.Assert(err, IsNil)
  1401. // Check
  1402. body, err := destBucket.GetObject(objectNameDest)
  1403. c.Assert(err, IsNil)
  1404. str, err := readBody(body)
  1405. c.Assert(err, IsNil)
  1406. c.Assert(str, Equals, objectValue)
  1407. err = s.bucket.DeleteObject(objectName)
  1408. c.Assert(err, IsNil)
  1409. // Copy to
  1410. _, err = destBucket.CopyObjectTo(bucketName, objectName, objectNameDest)
  1411. c.Assert(err, IsNil)
  1412. // Check
  1413. body, err = s.bucket.GetObject(objectName)
  1414. c.Assert(err, IsNil)
  1415. str, err = readBody(body)
  1416. c.Assert(err, IsNil)
  1417. c.Assert(str, Equals, objectValue)
  1418. // Clean
  1419. err = destBucket.DeleteObject(objectNameDest)
  1420. c.Assert(err, IsNil)
  1421. err = s.bucket.DeleteObject(objectName)
  1422. c.Assert(err, IsNil)
  1423. err = s.client.DeleteBucket(destBucketName)
  1424. c.Assert(err, IsNil)
  1425. }
  1426. // TestCopyObjectToOrFromNegative
  1427. func (s *OssBucketSuite) TestCopyObjectToOrFromNegative(c *C) {
  1428. objectName := objectNamePrefix + RandStr(8)
  1429. destBucket := bucketName + "-dest"
  1430. objectNameDest := objectName + "-dest"
  1431. // Object not exist
  1432. _, err := s.bucket.CopyObjectTo(bucketName, objectName, objectNameDest)
  1433. c.Assert(err, NotNil)
  1434. // Bucket not exist
  1435. _, err = s.bucket.CopyObjectFrom(destBucket, objectNameDest, objectName)
  1436. c.Assert(err, NotNil)
  1437. }
  1438. // TestAppendObject
  1439. func (s *OssBucketSuite) TestAppendObject(c *C) {
  1440. objectName := objectNamePrefix + RandStr(8)
  1441. objectValue := "昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。"
  1442. var val = []byte(objectValue)
  1443. var localFile = RandStr(8) + ".txt"
  1444. var nextPos int64
  1445. var midPos = 1 + rand.Intn(len(val)-1)
  1446. var err = CreateFileAndWrite(localFile+"1", val[0:midPos])
  1447. c.Assert(err, IsNil)
  1448. err = CreateFileAndWrite(localFile+"2", val[midPos:])
  1449. c.Assert(err, IsNil)
  1450. // String append
  1451. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,"), nextPos)
  1452. c.Assert(err, IsNil)
  1453. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("却道海棠依旧。知否?知否?应是绿肥红瘦。"), nextPos)
  1454. c.Assert(err, IsNil)
  1455. body, err := s.bucket.GetObject(objectName)
  1456. c.Assert(err, IsNil)
  1457. str, err := readBody(body)
  1458. c.Assert(err, IsNil)
  1459. c.Assert(str, Equals, objectValue)
  1460. err = s.bucket.DeleteObject(objectName)
  1461. c.Assert(err, IsNil)
  1462. // Byte append
  1463. nextPos = 0
  1464. nextPos, err = s.bucket.AppendObject(objectName, bytes.NewReader(val[0:midPos]), nextPos)
  1465. c.Assert(err, IsNil)
  1466. nextPos, err = s.bucket.AppendObject(objectName, bytes.NewReader(val[midPos:]), nextPos)
  1467. c.Assert(err, IsNil)
  1468. body, err = s.bucket.GetObject(objectName)
  1469. c.Assert(err, IsNil)
  1470. str, err = readBody(body)
  1471. c.Assert(err, IsNil)
  1472. c.Assert(str, Equals, objectValue)
  1473. err = s.bucket.DeleteObject(objectName)
  1474. c.Assert(err, IsNil)
  1475. // File append
  1476. options := []Option{
  1477. ObjectACL(ACLPublicReadWrite),
  1478. Meta("my", "myprop"),
  1479. }
  1480. fd, err := os.Open(localFile + "1")
  1481. c.Assert(err, IsNil)
  1482. defer fd.Close()
  1483. nextPos = 0
  1484. nextPos, err = s.bucket.AppendObject(objectName, fd, nextPos, options...)
  1485. c.Assert(err, IsNil)
  1486. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  1487. c.Assert(err, IsNil)
  1488. testLogger.Println("GetObjectDetailedMeta:", meta, ",", nextPos)
  1489. c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Appendable")
  1490. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
  1491. c.Assert(meta.Get("x-oss-Meta-Mine"), Equals, "")
  1492. c.Assert(meta.Get("X-Oss-Next-Append-Position"), Equals, strconv.FormatInt(nextPos, 10))
  1493. acl, err := s.bucket.GetObjectACL(objectName)
  1494. c.Assert(err, IsNil)
  1495. testLogger.Println("GetObjectACL:", acl)
  1496. c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
  1497. // Second append
  1498. options = []Option{
  1499. ObjectACL(ACLPublicRead),
  1500. Meta("my", "myproptwo"),
  1501. Meta("mine", "mypropmine"),
  1502. }
  1503. fd, err = os.Open(localFile + "2")
  1504. c.Assert(err, IsNil)
  1505. defer fd.Close()
  1506. nextPos, err = s.bucket.AppendObject(objectName, fd, nextPos, options...)
  1507. c.Assert(err, IsNil)
  1508. body, err = s.bucket.GetObject(objectName)
  1509. c.Assert(err, IsNil)
  1510. str, err = readBody(body)
  1511. c.Assert(err, IsNil)
  1512. c.Assert(str, Equals, objectValue)
  1513. meta, err = s.bucket.GetObjectDetailedMeta(objectName)
  1514. c.Assert(err, IsNil)
  1515. testLogger.Println("GetObjectDetailedMeta xxx:", meta)
  1516. c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Appendable")
  1517. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
  1518. c.Assert(meta.Get("x-Oss-Meta-Mine"), Equals, "")
  1519. c.Assert(meta.Get("X-Oss-Next-Append-Position"), Equals, strconv.FormatInt(nextPos, 10))
  1520. acl, err = s.bucket.GetObjectACL(objectName)
  1521. c.Assert(err, IsNil)
  1522. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  1523. err = s.bucket.DeleteObject(objectName)
  1524. c.Assert(err, IsNil)
  1525. }
  1526. // TestAppendObjectNegative
  1527. func (s *OssBucketSuite) TestAppendObjectNegative(c *C) {
  1528. objectName := objectNamePrefix + RandStr(8)
  1529. nextPos := int64(0)
  1530. nextPos, err := s.bucket.AppendObject(objectName, strings.NewReader("ObjectValue"), nextPos)
  1531. c.Assert(err, IsNil)
  1532. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("ObjectValue"), 0)
  1533. c.Assert(err, NotNil)
  1534. err = s.bucket.DeleteObject(objectName)
  1535. c.Assert(err, IsNil)
  1536. }
  1537. // TestContentType
  1538. func (s *OssBucketSuite) TestAddContentType(c *C) {
  1539. opts := AddContentType(nil, "abc.txt")
  1540. typ, err := FindOption(opts, HTTPHeaderContentType, "")
  1541. c.Assert(err, IsNil)
  1542. c.Assert(strings.Contains(typ.(string), "text/plain"), Equals, true)
  1543. opts = AddContentType(nil)
  1544. typ, err = FindOption(opts, HTTPHeaderContentType, "")
  1545. c.Assert(err, IsNil)
  1546. c.Assert(len(opts), Equals, 1)
  1547. c.Assert(strings.Contains(typ.(string), "application/octet-stream"), Equals, true)
  1548. opts = AddContentType(nil, "abc.txt", "abc.pdf")
  1549. typ, err = FindOption(opts, HTTPHeaderContentType, "")
  1550. c.Assert(err, IsNil)
  1551. c.Assert(strings.Contains(typ.(string), "text/plain"), Equals, true)
  1552. opts = AddContentType(nil, "abc", "abc.txt", "abc.pdf")
  1553. typ, err = FindOption(opts, HTTPHeaderContentType, "")
  1554. c.Assert(err, IsNil)
  1555. c.Assert(strings.Contains(typ.(string), "text/plain"), Equals, true)
  1556. opts = AddContentType(nil, "abc", "abc", "edf")
  1557. typ, err = FindOption(opts, HTTPHeaderContentType, "")
  1558. c.Assert(err, IsNil)
  1559. c.Assert(strings.Contains(typ.(string), "application/octet-stream"), Equals, true)
  1560. opts = AddContentType([]Option{Meta("meta", "my")}, "abc", "abc.txt", "abc.pdf")
  1561. typ, err = FindOption(opts, HTTPHeaderContentType, "")
  1562. c.Assert(err, IsNil)
  1563. c.Assert(len(opts), Equals, 2)
  1564. c.Assert(strings.Contains(typ.(string), "text/plain"), Equals, true)
  1565. }
  1566. func (s *OssBucketSuite) TestGetConfig(c *C) {
  1567. client, err := New(endpoint, accessID, accessKey, UseCname(true),
  1568. Timeout(11, 12), SecurityToken("token"), EnableMD5(false))
  1569. c.Assert(err, IsNil)
  1570. bucket, err := client.Bucket(bucketName)
  1571. c.Assert(err, IsNil)
  1572. c.Assert(bucket.GetConfig().HTTPTimeout.ConnectTimeout, Equals, time.Second*11)
  1573. c.Assert(bucket.GetConfig().HTTPTimeout.ReadWriteTimeout, Equals, time.Second*12)
  1574. c.Assert(bucket.GetConfig().HTTPTimeout.HeaderTimeout, Equals, time.Second*12)
  1575. c.Assert(bucket.GetConfig().HTTPTimeout.IdleConnTimeout, Equals, time.Second*12)
  1576. c.Assert(bucket.GetConfig().HTTPTimeout.LongTimeout, Equals, time.Second*12*10)
  1577. c.Assert(bucket.GetConfig().SecurityToken, Equals, "token")
  1578. c.Assert(bucket.GetConfig().IsCname, Equals, true)
  1579. c.Assert(bucket.GetConfig().IsEnableMD5, Equals, false)
  1580. }
  1581. func (s *OssBucketSuite) TestSTSToken(c *C) {
  1582. objectName := objectNamePrefix + RandStr(8)
  1583. objectValue := "红藕香残玉簟秋。轻解罗裳,独上兰舟。云中谁寄锦书来?雁字回时,月满西楼。"
  1584. stsClient := sts.NewClient(stsaccessID, stsaccessKey, stsARN, "oss_test_sess")
  1585. resp, err := stsClient.AssumeRole(1800)
  1586. c.Assert(err, IsNil)
  1587. client, err := New(endpoint, resp.Credentials.AccessKeyId, resp.Credentials.AccessKeySecret,
  1588. SecurityToken(resp.Credentials.SecurityToken))
  1589. c.Assert(err, IsNil)
  1590. bucket, err := client.Bucket(bucketName)
  1591. c.Assert(err, IsNil)
  1592. // Put
  1593. err = bucket.PutObject(objectName, strings.NewReader(objectValue))
  1594. c.Assert(err, IsNil)
  1595. // Get
  1596. body, err := bucket.GetObject(objectName)
  1597. c.Assert(err, IsNil)
  1598. str, err := readBody(body)
  1599. c.Assert(err, IsNil)
  1600. c.Assert(str, Equals, objectValue)
  1601. // List
  1602. lor, err := bucket.ListObjects()
  1603. c.Assert(err, IsNil)
  1604. testLogger.Println("Objects:", lor.Objects)
  1605. // Put with URL
  1606. signedURL, err := bucket.SignURL(objectName, HTTPPut, 3600)
  1607. c.Assert(err, IsNil)
  1608. err = bucket.PutObjectWithURL(signedURL, strings.NewReader(objectValue))
  1609. c.Assert(err, IsNil)
  1610. // Get with URL
  1611. signedURL, err = bucket.SignURL(objectName, HTTPGet, 3600)
  1612. c.Assert(err, IsNil)
  1613. body, err = bucket.GetObjectWithURL(signedURL)
  1614. c.Assert(err, IsNil)
  1615. str, err = readBody(body)
  1616. c.Assert(err, IsNil)
  1617. c.Assert(str, Equals, objectValue)
  1618. // Delete
  1619. err = bucket.DeleteObject(objectName)
  1620. c.Assert(err, IsNil)
  1621. }
  1622. func (s *OssBucketSuite) TestSTSTonekNegative(c *C) {
  1623. objectName := objectNamePrefix + RandStr(8)
  1624. localFile := objectName + ".jpg"
  1625. client, err := New(endpoint, accessID, accessKey, SecurityToken("Invalid"))
  1626. c.Assert(err, IsNil)
  1627. _, err = client.ListBuckets()
  1628. c.Assert(err, NotNil)
  1629. bucket, err := client.Bucket(bucketName)
  1630. c.Assert(err, IsNil)
  1631. err = bucket.PutObject(objectName, strings.NewReader(""))
  1632. c.Assert(err, NotNil)
  1633. err = bucket.PutObjectFromFile(objectName, "")
  1634. c.Assert(err, NotNil)
  1635. _, err = bucket.GetObject(objectName)
  1636. c.Assert(err, NotNil)
  1637. err = bucket.GetObjectToFile(objectName, "")
  1638. c.Assert(err, NotNil)
  1639. _, err = bucket.ListObjects()
  1640. c.Assert(err, NotNil)
  1641. err = bucket.SetObjectACL(objectName, ACLPublicRead)
  1642. c.Assert(err, NotNil)
  1643. _, err = bucket.GetObjectACL(objectName)
  1644. c.Assert(err, NotNil)
  1645. err = bucket.UploadFile(objectName, localFile, MinPartSize)
  1646. c.Assert(err, NotNil)
  1647. err = bucket.DownloadFile(objectName, localFile, MinPartSize)
  1648. c.Assert(err, NotNil)
  1649. _, err = bucket.IsObjectExist(objectName)
  1650. c.Assert(err, NotNil)
  1651. _, err = bucket.ListMultipartUploads()
  1652. c.Assert(err, NotNil)
  1653. err = bucket.DeleteObject(objectName)
  1654. c.Assert(err, NotNil)
  1655. _, err = bucket.DeleteObjects([]string{objectName})
  1656. c.Assert(err, NotNil)
  1657. err = client.DeleteBucket(bucketName)
  1658. c.Assert(err, NotNil)
  1659. }
  1660. func (s *OssBucketSuite) TestUploadBigFile(c *C) {
  1661. objectName := objectNamePrefix + RandStr(8)
  1662. bigFile := "D:\\tmp\\bigfile.zip"
  1663. newFile := "D:\\tmp\\newbigfile.zip"
  1664. exist, err := isFileExist(bigFile)
  1665. c.Assert(err, IsNil)
  1666. if !exist {
  1667. return
  1668. }
  1669. // Put
  1670. start := GetNowSec()
  1671. err = s.bucket.PutObjectFromFile(objectName, bigFile)
  1672. c.Assert(err, IsNil)
  1673. end := GetNowSec()
  1674. testLogger.Println("Put big file:", bigFile, "use sec:", end-start)
  1675. // Check
  1676. start = GetNowSec()
  1677. err = s.bucket.GetObjectToFile(objectName, newFile)
  1678. c.Assert(err, IsNil)
  1679. end = GetNowSec()
  1680. testLogger.Println("Get big file:", bigFile, "use sec:", end-start)
  1681. start = GetNowSec()
  1682. eq, err := compareFiles(bigFile, newFile)
  1683. c.Assert(err, IsNil)
  1684. c.Assert(eq, Equals, true)
  1685. end = GetNowSec()
  1686. testLogger.Println("Compare big file:", bigFile, "use sec:", end-start)
  1687. err = s.bucket.DeleteObject(objectName)
  1688. c.Assert(err, IsNil)
  1689. }
  1690. func (s *OssBucketSuite) TestSymlink(c *C) {
  1691. objectName := objectNamePrefix + RandStr(8)
  1692. targetObjectName := objectName + "target"
  1693. err := s.bucket.DeleteObject(objectName)
  1694. c.Assert(err, IsNil)
  1695. err = s.bucket.DeleteObject(targetObjectName)
  1696. c.Assert(err, IsNil)
  1697. meta, err := s.bucket.GetSymlink(objectName)
  1698. c.Assert(err, NotNil)
  1699. // Put symlink
  1700. err = s.bucket.PutSymlink(objectName, targetObjectName)
  1701. c.Assert(err, IsNil)
  1702. err = s.bucket.PutObject(targetObjectName, strings.NewReader("target"))
  1703. c.Assert(err, IsNil)
  1704. err = s.bucket.PutSymlink(objectName, targetObjectName)
  1705. c.Assert(err, IsNil)
  1706. meta, err = s.bucket.GetSymlink(objectName)
  1707. c.Assert(err, IsNil)
  1708. c.Assert(meta.Get(HTTPHeaderOssSymlinkTarget), Equals, targetObjectName)
  1709. // List object
  1710. lor, err := s.bucket.ListObjects()
  1711. c.Assert(err, IsNil)
  1712. exist, v := s.getObject(lor.Objects, objectName)
  1713. c.Assert(exist, Equals, true)
  1714. c.Assert(v.Type, Equals, "Symlink")
  1715. body, err := s.bucket.GetObject(objectName)
  1716. c.Assert(err, IsNil)
  1717. str, err := readBody(body)
  1718. c.Assert(err, IsNil)
  1719. c.Assert(str, Equals, "target")
  1720. meta, err = s.bucket.GetSymlink(targetObjectName)
  1721. c.Assert(err, NotNil)
  1722. err = s.bucket.PutObject(objectName, strings.NewReader("src"))
  1723. c.Assert(err, IsNil)
  1724. body, err = s.bucket.GetObject(objectName)
  1725. c.Assert(err, IsNil)
  1726. str, err = readBody(body)
  1727. c.Assert(err, IsNil)
  1728. c.Assert(str, Equals, "src")
  1729. err = s.bucket.DeleteObject(objectName)
  1730. c.Assert(err, IsNil)
  1731. err = s.bucket.DeleteObject(targetObjectName)
  1732. c.Assert(err, IsNil)
  1733. // Put symlink again
  1734. objectName = objectNamePrefix + RandStr(8)
  1735. targetObjectName = objectName + "-target"
  1736. err = s.bucket.PutSymlink(objectName, targetObjectName)
  1737. c.Assert(err, IsNil)
  1738. err = s.bucket.PutObject(targetObjectName, strings.NewReader("target1"))
  1739. c.Assert(err, IsNil)
  1740. meta, err = s.bucket.GetSymlink(objectName)
  1741. c.Assert(err, IsNil)
  1742. c.Assert(meta.Get(HTTPHeaderOssSymlinkTarget), Equals, targetObjectName)
  1743. body, err = s.bucket.GetObject(objectName)
  1744. c.Assert(err, IsNil)
  1745. str, err = readBody(body)
  1746. c.Assert(err, IsNil)
  1747. c.Assert(str, Equals, "target1")
  1748. err = s.bucket.DeleteObject(objectName)
  1749. c.Assert(err, IsNil)
  1750. err = s.bucket.DeleteObject(targetObjectName)
  1751. c.Assert(err, IsNil)
  1752. }
  1753. // TestRestoreObject
  1754. func (s *OssBucketSuite) TestRestoreObject(c *C) {
  1755. objectName := objectNamePrefix + RandStr(8)
  1756. // List objects
  1757. lor, err := s.archiveBucket.ListObjects()
  1758. c.Assert(err, IsNil)
  1759. left := len(lor.Objects)
  1760. // Put object
  1761. err = s.archiveBucket.PutObject(objectName, strings.NewReader(""))
  1762. c.Assert(err, IsNil)
  1763. // List
  1764. lor, err = s.archiveBucket.ListObjects()
  1765. c.Assert(err, IsNil)
  1766. c.Assert(len(lor.Objects), Equals, left+1)
  1767. for _, object := range lor.Objects {
  1768. c.Assert(object.StorageClass, Equals, string(StorageArchive))
  1769. c.Assert(object.Type, Equals, "Normal")
  1770. }
  1771. // Head object
  1772. meta, err := s.archiveBucket.GetObjectDetailedMeta(objectName)
  1773. c.Assert(err, IsNil)
  1774. _, ok := meta["X-Oss-Restore"]
  1775. c.Assert(ok, Equals, false)
  1776. c.Assert(meta.Get("X-Oss-Storage-Class"), Equals, "Archive")
  1777. // Error restore object
  1778. err = s.archiveBucket.RestoreObject("notexistobject")
  1779. c.Assert(err, NotNil)
  1780. // Restore object
  1781. err = s.archiveBucket.RestoreObject(objectName)
  1782. c.Assert(err, IsNil)
  1783. // Head object
  1784. meta, err = s.archiveBucket.GetObjectDetailedMeta(objectName)
  1785. c.Assert(err, IsNil)
  1786. c.Assert(meta.Get("X-Oss-Restore"), Equals, "ongoing-request=\"true\"")
  1787. c.Assert(meta.Get("X-Oss-Storage-Class"), Equals, "Archive")
  1788. }
  1789. // TestRestoreObjectWithXml
  1790. func (s *OssBucketSuite) TestRestoreObjectWithConfig(c *C) {
  1791. // create a bucket with default proprety
  1792. client, err := New(endpoint, accessID, accessKey)
  1793. c.Assert(err, IsNil)
  1794. bucketName := bucketNamePrefix + RandLowStr(6)
  1795. err = client.CreateBucket(bucketName, StorageClass(StorageColdArchive))
  1796. c.Assert(err, IsNil)
  1797. bucket, err := client.Bucket(bucketName)
  1798. objectName := objectNamePrefix + RandStr(8)
  1799. // Put object
  1800. err = bucket.PutObject(objectName, strings.NewReader("123456789"), ObjectStorageClass(StorageColdArchive))
  1801. c.Assert(err, IsNil)
  1802. var restoreConfig RestoreConfiguration
  1803. restoreConfig.Days = 2
  1804. err = bucket.RestoreObjectDetail(objectName, restoreConfig)
  1805. c.Assert(err, IsNil)
  1806. objectName = objectNamePrefix + RandStr(8)
  1807. err = bucket.PutObject(objectName, strings.NewReader("123456789"), ObjectStorageClass(StorageColdArchive))
  1808. c.Assert(err, IsNil)
  1809. restoreConfig.Tier = string(RestoreBulk)
  1810. err = bucket.RestoreObjectDetail(objectName, restoreConfig)
  1811. c.Assert(err, IsNil)
  1812. objectName = objectNamePrefix + RandStr(8)
  1813. err = bucket.PutObject(objectName, strings.NewReader("123456789"), ObjectStorageClass(StorageColdArchive))
  1814. c.Assert(err, IsNil)
  1815. restoreConfig.Days = 0
  1816. err = bucket.RestoreObjectDetail(objectName, restoreConfig)
  1817. c.Assert(err, IsNil)
  1818. ForceDeleteBucket(client, bucketName, c)
  1819. }
  1820. // TestProcessObject
  1821. func (s *OssBucketSuite) TestProcessObject(c *C) {
  1822. objectName := objectNamePrefix + RandStr(8) + ".jpg"
  1823. err := s.bucket.PutObjectFromFile(objectName, "../sample/BingWallpaper-2015-11-07.jpg")
  1824. c.Assert(err, IsNil)
  1825. // If bucket-name not specified, it is saved to the current bucket by default.
  1826. destObjName := objectNamePrefix + RandStr(8) + "-dest.jpg"
  1827. process := fmt.Sprintf("image/resize,w_100|sys/saveas,o_%v", base64.URLEncoding.EncodeToString([]byte(destObjName)))
  1828. result, err := s.bucket.ProcessObject(objectName, process)
  1829. c.Assert(err, IsNil)
  1830. exist, _ := s.bucket.IsObjectExist(destObjName)
  1831. c.Assert(exist, Equals, true)
  1832. c.Assert(result.Bucket, Equals, "")
  1833. c.Assert(result.Object, Equals, destObjName)
  1834. destObjName = objectNamePrefix + RandStr(8) + "-dest.jpg"
  1835. process = fmt.Sprintf("image/resize,w_100|sys/saveas,o_%v,b_%v", base64.URLEncoding.EncodeToString([]byte(destObjName)), base64.URLEncoding.EncodeToString([]byte(s.bucket.BucketName)))
  1836. result, err = s.bucket.ProcessObject(objectName, process)
  1837. c.Assert(err, IsNil)
  1838. exist, _ = s.bucket.IsObjectExist(destObjName)
  1839. c.Assert(exist, Equals, true)
  1840. c.Assert(result.Bucket, Equals, s.bucket.BucketName)
  1841. c.Assert(result.Object, Equals, destObjName)
  1842. //no support process
  1843. process = fmt.Sprintf("image/resize,w_100|saveas,o_%v,b_%v", base64.URLEncoding.EncodeToString([]byte(destObjName)), base64.URLEncoding.EncodeToString([]byte(s.bucket.BucketName)))
  1844. result, err = s.bucket.ProcessObject(objectName, process)
  1845. c.Assert(err, NotNil)
  1846. }
  1847. // Private
  1848. func CreateFileAndWrite(fileName string, data []byte) error {
  1849. os.Remove(fileName)
  1850. fo, err := os.Create(fileName)
  1851. if err != nil {
  1852. return err
  1853. }
  1854. defer fo.Close()
  1855. bytes, err := fo.Write(data)
  1856. if err != nil {
  1857. return err
  1858. }
  1859. if bytes != len(data) {
  1860. return fmt.Errorf(fmt.Sprintf("write %d bytes not equal data length %d", bytes, len(data)))
  1861. }
  1862. return nil
  1863. }
  1864. // Compare the content between fileL and fileR
  1865. func compareFiles(fileL string, fileR string) (bool, error) {
  1866. finL, err := os.Open(fileL)
  1867. if err != nil {
  1868. return false, err
  1869. }
  1870. defer finL.Close()
  1871. finR, err := os.Open(fileR)
  1872. if err != nil {
  1873. return false, err
  1874. }
  1875. defer finR.Close()
  1876. statL, err := finL.Stat()
  1877. if err != nil {
  1878. return false, err
  1879. }
  1880. statR, err := finR.Stat()
  1881. if err != nil {
  1882. return false, err
  1883. }
  1884. if statL.Size() != statR.Size() {
  1885. return false, nil
  1886. }
  1887. size := statL.Size()
  1888. if size > 102400 {
  1889. size = 102400
  1890. }
  1891. bufL := make([]byte, size)
  1892. bufR := make([]byte, size)
  1893. for {
  1894. n, _ := finL.Read(bufL)
  1895. if 0 == n {
  1896. break
  1897. }
  1898. n, _ = finR.Read(bufR)
  1899. if 0 == n {
  1900. break
  1901. }
  1902. if !bytes.Equal(bufL, bufR) {
  1903. return false, nil
  1904. }
  1905. }
  1906. return true, nil
  1907. }
  1908. // Compare the content of file and data
  1909. func compareFileData(file string, data []byte) (bool, error) {
  1910. fin, err := os.Open(file)
  1911. if err != nil {
  1912. return false, err
  1913. }
  1914. defer fin.Close()
  1915. stat, err := fin.Stat()
  1916. if err != nil {
  1917. return false, err
  1918. }
  1919. if stat.Size() != (int64)(len(data)) {
  1920. return false, nil
  1921. }
  1922. buf := make([]byte, stat.Size())
  1923. n, err := fin.Read(buf)
  1924. if err != nil {
  1925. return false, err
  1926. }
  1927. if stat.Size() != (int64)(n) {
  1928. return false, errors.New("read error")
  1929. }
  1930. if !bytes.Equal(buf, data) {
  1931. return false, nil
  1932. }
  1933. return true, nil
  1934. }
  1935. func walkDir(dirPth, suffix string) ([]string, error) {
  1936. var files = []string{}
  1937. suffix = strings.ToUpper(suffix)
  1938. err := filepath.Walk(dirPth,
  1939. func(filename string, fi os.FileInfo, err error) error {
  1940. if err != nil {
  1941. return err
  1942. }
  1943. if fi.IsDir() {
  1944. return nil
  1945. }
  1946. if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
  1947. files = append(files, filename)
  1948. }
  1949. return nil
  1950. })
  1951. return files, err
  1952. }
  1953. func removeTempFiles(path string, prefix string) error {
  1954. files, err := walkDir(path, prefix)
  1955. if err != nil {
  1956. return nil
  1957. }
  1958. for _, file := range files {
  1959. os.Remove(file)
  1960. }
  1961. return nil
  1962. }
  1963. func isFileExist(filename string) (bool, error) {
  1964. _, err := os.Stat(filename)
  1965. if err != nil && os.IsNotExist(err) {
  1966. return false, nil
  1967. } else if err != nil {
  1968. return false, err
  1969. } else {
  1970. return true, nil
  1971. }
  1972. }
  1973. func readBody(body io.ReadCloser) (string, error) {
  1974. data, err := ioutil.ReadAll(body)
  1975. body.Close()
  1976. if err != nil {
  1977. return "", err
  1978. }
  1979. return string(data), nil
  1980. }
  1981. func (s *OssBucketSuite) getObject(objects []ObjectProperties, object string) (bool, ObjectProperties) {
  1982. for _, v := range objects {
  1983. if v.Key == object {
  1984. return true, v
  1985. }
  1986. }
  1987. return false, ObjectProperties{}
  1988. }
  1989. func (s *OssBucketSuite) detectUploadSpeed(bucket *Bucket, c *C) (upSpeed int) {
  1990. objectName := objectNamePrefix + RandStr(8)
  1991. // 1M byte
  1992. textBuffer := RandStr(1024 * 1024)
  1993. // Put string
  1994. startT := time.Now()
  1995. err := bucket.PutObject(objectName, strings.NewReader(textBuffer))
  1996. endT := time.Now()
  1997. c.Assert(err, IsNil)
  1998. err = bucket.DeleteObject(objectName)
  1999. c.Assert(err, IsNil)
  2000. // byte/s
  2001. upSpeed = len(textBuffer) * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  2002. return upSpeed
  2003. }
  2004. func (s *OssBucketSuite) TestPutSingleObjectLimitSpeed(c *C) {
  2005. // create client and bucket
  2006. client, err := New(endpoint, accessID, accessKey)
  2007. c.Assert(err, IsNil)
  2008. err = client.LimitUploadSpeed(1)
  2009. if err != nil {
  2010. // go version is less than go1.7,not support limit upload speed
  2011. // doesn't run this test
  2012. return
  2013. }
  2014. // set unlimited again
  2015. client.LimitUploadSpeed(0)
  2016. bucketName := bucketNamePrefix + RandLowStr(6)
  2017. err = client.CreateBucket(bucketName)
  2018. c.Assert(err, IsNil)
  2019. bucket, err := client.Bucket(bucketName)
  2020. c.Assert(err, IsNil)
  2021. //detect speed:byte/s
  2022. detectSpeed := s.detectUploadSpeed(bucket, c)
  2023. var limitSpeed = 0
  2024. if detectSpeed <= perTokenBandwidthSize*2 {
  2025. limitSpeed = perTokenBandwidthSize
  2026. } else {
  2027. //this situation, the test works better
  2028. limitSpeed = detectSpeed / 2
  2029. }
  2030. // KB/s
  2031. err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
  2032. c.Assert(err, IsNil)
  2033. objectName := objectNamePrefix + RandStr(8)
  2034. // 1M byte
  2035. textBuffer := RandStr(1024 * 1024)
  2036. // Put body
  2037. startT := time.Now()
  2038. err = bucket.PutObject(objectName, strings.NewReader(textBuffer))
  2039. endT := time.Now()
  2040. realSpeed := int64(len(textBuffer)) * 1000 / (endT.UnixNano()/1000/1000 - startT.UnixNano()/1000/1000)
  2041. fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
  2042. c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
  2043. if detectSpeed > perTokenBandwidthSize {
  2044. // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
  2045. c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
  2046. }
  2047. // Get object and compare content
  2048. body, err := bucket.GetObject(objectName)
  2049. c.Assert(err, IsNil)
  2050. str, err := readBody(body)
  2051. c.Assert(err, IsNil)
  2052. c.Assert(str, Equals, textBuffer)
  2053. bucket.DeleteObject(objectName)
  2054. client.DeleteBucket(bucketName)
  2055. c.Assert(err, IsNil)
  2056. return
  2057. }
  2058. func putObjectRoutin(bucket *Bucket, object string, textBuffer *string, notifyChan chan int) error {
  2059. err := bucket.PutObject(object, strings.NewReader(*textBuffer))
  2060. if err == nil {
  2061. notifyChan <- 1
  2062. } else {
  2063. notifyChan <- 0
  2064. }
  2065. return err
  2066. }
  2067. func (s *OssBucketSuite) TestPutManyObjectLimitSpeed(c *C) {
  2068. // create client and bucket
  2069. client, err := New(endpoint, accessID, accessKey)
  2070. c.Assert(err, IsNil)
  2071. err = client.LimitUploadSpeed(1)
  2072. if err != nil {
  2073. // go version is less than go1.7,not support limit upload speed
  2074. // doesn't run this test
  2075. return
  2076. }
  2077. // set unlimited
  2078. client.LimitUploadSpeed(0)
  2079. bucketName := bucketNamePrefix + RandLowStr(6)
  2080. err = client.CreateBucket(bucketName)
  2081. c.Assert(err, IsNil)
  2082. bucket, err := client.Bucket(bucketName)
  2083. c.Assert(err, IsNil)
  2084. //detect speed:byte/s
  2085. detectSpeed := s.detectUploadSpeed(bucket, c)
  2086. var limitSpeed = 0
  2087. if detectSpeed <= perTokenBandwidthSize*2 {
  2088. limitSpeed = perTokenBandwidthSize
  2089. } else {
  2090. limitSpeed = detectSpeed / 2
  2091. }
  2092. // KB/s
  2093. err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
  2094. c.Assert(err, IsNil)
  2095. // object1
  2096. objectNameFirst := objectNamePrefix + RandStr(8)
  2097. objectNameSecond := objectNamePrefix + RandStr(8)
  2098. // 1M byte
  2099. textBuffer := RandStr(1024 * 1024)
  2100. objectCount := 2
  2101. notifyChan := make(chan int, objectCount)
  2102. //start routin
  2103. startT := time.Now()
  2104. go putObjectRoutin(bucket, objectNameFirst, &textBuffer, notifyChan)
  2105. go putObjectRoutin(bucket, objectNameSecond, &textBuffer, notifyChan)
  2106. // wait routin end
  2107. sum := int(0)
  2108. for j := 0; j < objectCount; j++ {
  2109. result := <-notifyChan
  2110. sum += result
  2111. }
  2112. endT := time.Now()
  2113. realSpeed := len(textBuffer) * 2 * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  2114. c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
  2115. if detectSpeed > perTokenBandwidthSize {
  2116. // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
  2117. c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
  2118. }
  2119. c.Assert(sum, Equals, 2)
  2120. // Get object and compare content
  2121. body, err := bucket.GetObject(objectNameFirst)
  2122. c.Assert(err, IsNil)
  2123. str, err := readBody(body)
  2124. c.Assert(err, IsNil)
  2125. c.Assert(str, Equals, textBuffer)
  2126. body, err = bucket.GetObject(objectNameSecond)
  2127. c.Assert(err, IsNil)
  2128. str, err = readBody(body)
  2129. c.Assert(err, IsNil)
  2130. c.Assert(str, Equals, textBuffer)
  2131. // clear bucket and object
  2132. bucket.DeleteObject(objectNameFirst)
  2133. bucket.DeleteObject(objectNameSecond)
  2134. client.DeleteBucket(bucketName)
  2135. fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
  2136. return
  2137. }
  2138. func (s *OssBucketSuite) TestPutMultipartObjectLimitSpeed(c *C) {
  2139. // create client and bucket
  2140. client, err := New(endpoint, accessID, accessKey)
  2141. c.Assert(err, IsNil)
  2142. err = client.LimitUploadSpeed(1)
  2143. if err != nil {
  2144. // go version is less than go1.7,not support limit upload speed
  2145. // doesn't run this test
  2146. return
  2147. }
  2148. // set unlimited
  2149. client.LimitUploadSpeed(0)
  2150. bucketName := bucketNamePrefix + RandLowStr(6)
  2151. err = client.CreateBucket(bucketName)
  2152. c.Assert(err, IsNil)
  2153. bucket, err := client.Bucket(bucketName)
  2154. c.Assert(err, IsNil)
  2155. //detect speed:byte/s
  2156. detectSpeed := s.detectUploadSpeed(bucket, c)
  2157. var limitSpeed = 0
  2158. if detectSpeed <= perTokenBandwidthSize*2 {
  2159. limitSpeed = perTokenBandwidthSize
  2160. } else {
  2161. //this situation, the test works better
  2162. limitSpeed = detectSpeed / 2
  2163. }
  2164. // KB/s
  2165. err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
  2166. c.Assert(err, IsNil)
  2167. objectName := objectNamePrefix + RandStr(8)
  2168. fileName := "." + string(os.PathSeparator) + objectName
  2169. // 1M byte
  2170. fileSize := 0
  2171. textBuffer := RandStr(1024 * 1024)
  2172. if detectSpeed < perTokenBandwidthSize {
  2173. ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
  2174. f, err := os.Stat(fileName)
  2175. c.Assert(err, IsNil)
  2176. fileSize = int(f.Size())
  2177. c.Assert(fileSize, Equals, len(textBuffer))
  2178. } else {
  2179. loopCount := 5
  2180. f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
  2181. c.Assert(err, IsNil)
  2182. for i := 0; i < loopCount; i++ {
  2183. f.Write([]byte(textBuffer))
  2184. }
  2185. fileInfo, err := f.Stat()
  2186. c.Assert(err, IsNil)
  2187. fileSize = int(fileInfo.Size())
  2188. c.Assert(fileSize, Equals, len(textBuffer)*loopCount)
  2189. f.Close()
  2190. }
  2191. // Put body
  2192. startT := time.Now()
  2193. err = bucket.UploadFile(objectName, fileName, 100*1024, Routines(3), Checkpoint(true, ""))
  2194. endT := time.Now()
  2195. c.Assert(err, IsNil)
  2196. realSpeed := fileSize * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  2197. c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
  2198. if detectSpeed > perTokenBandwidthSize {
  2199. // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
  2200. c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
  2201. }
  2202. // Get object and compare content
  2203. body, err := bucket.GetObject(objectName)
  2204. c.Assert(err, IsNil)
  2205. str, err := readBody(body)
  2206. c.Assert(err, IsNil)
  2207. fileBody, err := ioutil.ReadFile(fileName)
  2208. c.Assert(err, IsNil)
  2209. c.Assert(str, Equals, string(fileBody))
  2210. // delete bucket、object、file
  2211. bucket.DeleteObject(objectName)
  2212. client.DeleteBucket(bucketName)
  2213. os.Remove(fileName)
  2214. fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
  2215. return
  2216. }
  2217. func (s *OssBucketSuite) TestPutObjectFromFileLimitSpeed(c *C) {
  2218. // create client and bucket
  2219. client, err := New(endpoint, accessID, accessKey)
  2220. c.Assert(err, IsNil)
  2221. err = client.LimitUploadSpeed(1)
  2222. if err != nil {
  2223. // go version is less than go1.7,not support limit upload speed
  2224. // doesn't run this test
  2225. return
  2226. }
  2227. // set unlimited
  2228. client.LimitUploadSpeed(0)
  2229. bucketName := bucketNamePrefix + RandLowStr(6)
  2230. err = client.CreateBucket(bucketName)
  2231. c.Assert(err, IsNil)
  2232. bucket, err := client.Bucket(bucketName)
  2233. c.Assert(err, IsNil)
  2234. //detect speed:byte/s
  2235. detectSpeed := s.detectUploadSpeed(bucket, c)
  2236. var limitSpeed = 0
  2237. if detectSpeed <= perTokenBandwidthSize*2 {
  2238. limitSpeed = perTokenBandwidthSize
  2239. } else {
  2240. //this situation, the test works better
  2241. limitSpeed = detectSpeed / 2
  2242. }
  2243. // KB/s
  2244. err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
  2245. c.Assert(err, IsNil)
  2246. objectName := objectNamePrefix + RandStr(8)
  2247. fileName := "." + string(os.PathSeparator) + objectName
  2248. // 1M byte
  2249. fileSize := 0
  2250. textBuffer := RandStr(1024 * 1024)
  2251. if detectSpeed < perTokenBandwidthSize {
  2252. ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
  2253. f, err := os.Stat(fileName)
  2254. c.Assert(err, IsNil)
  2255. fileSize = int(f.Size())
  2256. c.Assert(fileSize, Equals, len(textBuffer))
  2257. } else {
  2258. loopCount := 2
  2259. f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
  2260. c.Assert(err, IsNil)
  2261. for i := 0; i < loopCount; i++ {
  2262. f.Write([]byte(textBuffer))
  2263. }
  2264. fileInfo, err := f.Stat()
  2265. c.Assert(err, IsNil)
  2266. fileSize = int(fileInfo.Size())
  2267. c.Assert(fileSize, Equals, len(textBuffer)*loopCount)
  2268. f.Close()
  2269. }
  2270. // Put body
  2271. startT := time.Now()
  2272. err = bucket.PutObjectFromFile(objectName, fileName)
  2273. endT := time.Now()
  2274. c.Assert(err, IsNil)
  2275. realSpeed := fileSize * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  2276. c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
  2277. if detectSpeed > perTokenBandwidthSize {
  2278. // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
  2279. c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
  2280. }
  2281. // Get object and compare content
  2282. body, err := bucket.GetObject(objectName)
  2283. c.Assert(err, IsNil)
  2284. str, err := readBody(body)
  2285. c.Assert(err, IsNil)
  2286. fileBody, err := ioutil.ReadFile(fileName)
  2287. c.Assert(err, IsNil)
  2288. c.Assert(str, Equals, string(fileBody))
  2289. // delete bucket、file、object
  2290. bucket.DeleteObject(objectName)
  2291. client.DeleteBucket(bucketName)
  2292. os.Remove(fileName)
  2293. fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
  2294. return
  2295. }
  2296. // upload speed limit parameters will not affect download speed
  2297. func (s *OssBucketSuite) TestUploadObjectLimitSpeed(c *C) {
  2298. // create limit client and bucket
  2299. client, err := New(endpoint, accessID, accessKey)
  2300. c.Assert(err, IsNil)
  2301. tokenCount := 1
  2302. err = client.LimitUploadSpeed(tokenCount)
  2303. if err != nil {
  2304. // go version is less than go1.7,not support limit upload speed
  2305. // doesn't run this test
  2306. return
  2307. }
  2308. // set unlimited
  2309. client.LimitUploadSpeed(0)
  2310. bucketName := bucketNamePrefix + RandLowStr(6)
  2311. err = client.CreateBucket(bucketName)
  2312. c.Assert(err, IsNil)
  2313. bucket, err := client.Bucket(bucketName)
  2314. c.Assert(err, IsNil)
  2315. //first:upload a object
  2316. textBuffer := RandStr(1024 * 100)
  2317. objectName := objectNamePrefix + RandStr(8)
  2318. err = bucket.PutObject(objectName, strings.NewReader(textBuffer))
  2319. c.Assert(err, IsNil)
  2320. // limit upload speed
  2321. err = client.LimitUploadSpeed(tokenCount)
  2322. c.Assert(err, IsNil)
  2323. // then download the object
  2324. startT := time.Now()
  2325. body, err := bucket.GetObject(objectName)
  2326. c.Assert(err, IsNil)
  2327. str, err := readBody(body)
  2328. c.Assert(err, IsNil)
  2329. endT := time.Now()
  2330. c.Assert(str, Equals, textBuffer)
  2331. // byte/s
  2332. downloadSpeed := len(textBuffer) * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  2333. // upload speed limit parameters will not affect download speed
  2334. c.Assert(downloadSpeed > 2*tokenCount*perTokenBandwidthSize, Equals, true)
  2335. bucket.DeleteObject(objectName)
  2336. client.DeleteBucket(bucketName)
  2337. }
  2338. // test LimitUploadSpeed failure
  2339. func (s *OssBucketSuite) TestLimitUploadSpeedFail(c *C) {
  2340. // create limit client and bucket
  2341. client, err := New(endpoint, accessID, accessKey)
  2342. c.Assert(err, IsNil)
  2343. err = client.LimitUploadSpeed(-1)
  2344. c.Assert(err, NotNil)
  2345. client.Config = nil
  2346. err = client.LimitUploadSpeed(100)
  2347. c.Assert(err, NotNil)
  2348. }
  2349. // upload webp object
  2350. func (s *OssBucketSuite) TestUploadObjectWithWebpFormat(c *C) {
  2351. client, err := New(endpoint, accessID, accessKey)
  2352. c.Assert(err, IsNil)
  2353. bucketName := bucketNamePrefix + RandLowStr(6)
  2354. err = client.CreateBucket(bucketName)
  2355. c.Assert(err, IsNil)
  2356. bucket, err := client.Bucket(bucketName)
  2357. c.Assert(err, IsNil)
  2358. // create webp file
  2359. textBuffer := RandStr(1024)
  2360. objectName := objectNamePrefix + RandStr(8)
  2361. fileName := "." + string(os.PathSeparator) + objectName + ".webp"
  2362. ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
  2363. _, err = os.Stat(fileName)
  2364. c.Assert(err, IsNil)
  2365. err = bucket.PutObjectFromFile(objectName, fileName)
  2366. c.Assert(err, IsNil)
  2367. // check object content-type
  2368. props, err := bucket.GetObjectDetailedMeta(objectName)
  2369. c.Assert(err, IsNil)
  2370. c.Assert(props["Content-Type"][0], Equals, "image/webp")
  2371. os.Remove(fileName)
  2372. bucket.DeleteObject(objectName)
  2373. client.DeleteBucket(bucketName)
  2374. }
  2375. func (s *OssBucketSuite) TestPutObjectTagging(c *C) {
  2376. // put object with tagging
  2377. objectName := objectNamePrefix + RandStr(8)
  2378. tag1 := Tag{
  2379. Key: RandStr(8),
  2380. Value: RandStr(9),
  2381. }
  2382. tag2 := Tag{
  2383. Key: RandStr(10),
  2384. Value: RandStr(11),
  2385. }
  2386. tagging := Tagging{
  2387. Tags: []Tag{tag1, tag2},
  2388. }
  2389. err := s.bucket.PutObject(objectName, strings.NewReader(RandStr(1024)), SetTagging(tagging))
  2390. c.Assert(err, IsNil)
  2391. headers, err := s.bucket.GetObjectDetailedMeta(objectName)
  2392. taggingCount, err := strconv.Atoi(headers["X-Oss-Tagging-Count"][0])
  2393. c.Assert(err, IsNil)
  2394. c.Assert(taggingCount, Equals, 2)
  2395. // copy object with default option
  2396. destObjectName := objectNamePrefix + RandStr(8)
  2397. _, err = s.bucket.CopyObject(objectName, destObjectName)
  2398. c.Assert(err, IsNil)
  2399. headers, err = s.bucket.GetObjectDetailedMeta(destObjectName)
  2400. taggingCount, err = strconv.Atoi(headers["X-Oss-Tagging-Count"][0])
  2401. c.Assert(err, IsNil)
  2402. c.Assert(taggingCount, Equals, 2)
  2403. // delete object tagging
  2404. err = s.bucket.DeleteObjectTagging(objectName)
  2405. c.Assert(err, IsNil)
  2406. // get object tagging again
  2407. taggingResult, err := s.bucket.GetObjectTagging(objectName)
  2408. c.Assert(err, IsNil)
  2409. c.Assert(len(taggingResult.Tags), Equals, 0)
  2410. // put tagging
  2411. tag := Tag{
  2412. Key: RandStr(8),
  2413. Value: RandStr(16),
  2414. }
  2415. tagging.Tags = []Tag{tag}
  2416. err = s.bucket.PutObjectTagging(objectName, tagging)
  2417. c.Assert(err, IsNil)
  2418. taggingResult, err = s.bucket.GetObjectTagging(objectName)
  2419. c.Assert(len(taggingResult.Tags), Equals, 1)
  2420. c.Assert(taggingResult.Tags[0].Key, Equals, tag.Key)
  2421. c.Assert(taggingResult.Tags[0].Value, Equals, tag.Value)
  2422. //put tagging, the length of the key exceeds 128
  2423. tag = Tag{
  2424. Key: RandStr(129),
  2425. Value: RandStr(16),
  2426. }
  2427. tagging.Tags = []Tag{tag}
  2428. err = s.bucket.PutObjectTagging(objectName, tagging)
  2429. c.Assert(err, NotNil)
  2430. //put tagging, the length of the value exceeds 256
  2431. tag = Tag{
  2432. Key: RandStr(8),
  2433. Value: RandStr(257),
  2434. }
  2435. tagging.Tags = []Tag{tag}
  2436. err = s.bucket.PutObjectTagging(objectName, tagging)
  2437. c.Assert(err, NotNil)
  2438. //put tagging, the lens of tags exceed 10
  2439. tagging.Tags = []Tag{}
  2440. for i := 0; i < 11; i++ {
  2441. tag = Tag{
  2442. Key: RandStr(8),
  2443. Value: RandStr(16),
  2444. }
  2445. tagging.Tags = append(tagging.Tags, tag)
  2446. }
  2447. err = s.bucket.PutObjectTagging(objectName, tagging)
  2448. c.Assert(err, NotNil)
  2449. //put tagging, invalid value of tag key
  2450. tag = Tag{
  2451. Key: RandStr(8) + "&",
  2452. Value: RandStr(16),
  2453. }
  2454. tagging.Tags = []Tag{tag}
  2455. err = s.bucket.PutObjectTagging(objectName, tagging)
  2456. c.Assert(err, NotNil)
  2457. //put tagging, invalid value of tag value
  2458. tag = Tag{
  2459. Key: RandStr(8),
  2460. Value: RandStr(16) + "&",
  2461. }
  2462. tagging.Tags = []Tag{tag}
  2463. err = s.bucket.PutObjectTagging(objectName, tagging)
  2464. c.Assert(err, NotNil)
  2465. //put tagging, repeated tag keys
  2466. tag1 = Tag{
  2467. Key: RandStr(8),
  2468. Value: RandStr(16),
  2469. }
  2470. tag2 = Tag{
  2471. Key: tag1.Key,
  2472. Value: RandStr(16),
  2473. }
  2474. tagging.Tags = []Tag{tag1, tag2}
  2475. err = s.bucket.PutObjectTagging(objectName, tagging)
  2476. c.Assert(err, NotNil)
  2477. s.bucket.DeleteObject(destObjectName)
  2478. s.bucket.DeleteObject(objectName)
  2479. }
  2480. func (s *OssBucketSuite) TestGetObjectTagging(c *C) {
  2481. // get object which has 2 tags
  2482. objectName := objectNamePrefix + RandStr(8)
  2483. tag1 := Tag{
  2484. Key: RandStr(8),
  2485. Value: RandStr(9),
  2486. }
  2487. tag2 := Tag{
  2488. Key: RandStr(10),
  2489. Value: RandStr(11),
  2490. }
  2491. taggingInfo := Tagging{
  2492. Tags: []Tag{tag1, tag2},
  2493. }
  2494. err := s.bucket.PutObject(objectName, strings.NewReader(RandStr(1024)), SetTagging(taggingInfo))
  2495. c.Assert(err, IsNil)
  2496. tagging, err := s.bucket.GetObjectTagging(objectName)
  2497. c.Assert(len(tagging.Tags), Equals, 2)
  2498. if tagging.Tags[0].Key == tag1.Key {
  2499. c.Assert(tagging.Tags[0].Value, Equals, tag1.Value)
  2500. c.Assert(tagging.Tags[1].Key, Equals, tag2.Key)
  2501. c.Assert(tagging.Tags[1].Value, Equals, tag2.Value)
  2502. } else {
  2503. c.Assert(tagging.Tags[0].Key, Equals, tag2.Key)
  2504. c.Assert(tagging.Tags[0].Value, Equals, tag2.Value)
  2505. c.Assert(tagging.Tags[1].Key, Equals, tag1.Key)
  2506. c.Assert(tagging.Tags[1].Value, Equals, tag1.Value)
  2507. }
  2508. // get tagging of an object that is not exist
  2509. err = s.bucket.DeleteObject(objectName)
  2510. c.Assert(err, IsNil)
  2511. tagging, err = s.bucket.GetObjectTagging(objectName)
  2512. c.Assert(err, NotNil)
  2513. c.Assert(len(tagging.Tags), Equals, 0)
  2514. // get object which has no tag
  2515. objectName = objectNamePrefix + RandStr(8)
  2516. err = s.bucket.PutObject(objectName, strings.NewReader(RandStr(1024)))
  2517. c.Assert(err, IsNil)
  2518. tagging, err = s.bucket.GetObjectTagging(objectName)
  2519. c.Assert(err, IsNil)
  2520. c.Assert(len(tagging.Tags), Equals, 0)
  2521. // copy object, with tagging option
  2522. destObjectName := objectName + "-dest"
  2523. tagging.Tags = []Tag{tag1, tag2}
  2524. _, err = s.bucket.CopyObject(objectName, destObjectName, SetTagging(taggingInfo))
  2525. c.Assert(err, IsNil)
  2526. tagging, err = s.bucket.GetObjectTagging(objectName)
  2527. c.Assert(err, IsNil)
  2528. c.Assert(len(tagging.Tags), Equals, 0)
  2529. // copy object, with tagging option, the value of tagging directive is "REPLACE"
  2530. tagging.Tags = []Tag{tag1, tag2}
  2531. _, err = s.bucket.CopyObject(objectName, destObjectName, SetTagging(taggingInfo), TaggingDirective(TaggingReplace))
  2532. c.Assert(err, IsNil)
  2533. tagging, err = s.bucket.GetObjectTagging(destObjectName)
  2534. c.Assert(err, IsNil)
  2535. c.Assert(len(tagging.Tags), Equals, 2)
  2536. if tagging.Tags[0].Key == tag1.Key {
  2537. c.Assert(tagging.Tags[0].Value, Equals, tag1.Value)
  2538. c.Assert(tagging.Tags[1].Key, Equals, tag2.Key)
  2539. c.Assert(tagging.Tags[1].Value, Equals, tag2.Value)
  2540. } else {
  2541. c.Assert(tagging.Tags[0].Key, Equals, tag2.Key)
  2542. c.Assert(tagging.Tags[0].Value, Equals, tag2.Value)
  2543. c.Assert(tagging.Tags[1].Key, Equals, tag1.Key)
  2544. c.Assert(tagging.Tags[1].Value, Equals, tag1.Value)
  2545. }
  2546. s.bucket.DeleteObject(objectName)
  2547. s.bucket.DeleteObject(destObjectName)
  2548. }
  2549. func (s *OssBucketSuite) TestDeleteObjectTagging(c *C) {
  2550. // delete object tagging, the object is not exist
  2551. objectName := objectNamePrefix + RandStr(8)
  2552. err := s.bucket.DeleteObjectTagging(objectName)
  2553. c.Assert(err, NotNil)
  2554. // delete object tagging
  2555. tag := Tag{
  2556. Key: RandStr(8),
  2557. Value: RandStr(16),
  2558. }
  2559. tagging := Tagging{
  2560. Tags: []Tag{tag},
  2561. }
  2562. err = s.bucket.PutObject(objectName, strings.NewReader(RandStr(1024)), SetTagging(tagging))
  2563. c.Assert(err, IsNil)
  2564. err = s.bucket.DeleteObjectTagging(objectName)
  2565. c.Assert(err, IsNil)
  2566. taggingResult, err := s.bucket.GetObjectTagging(objectName)
  2567. c.Assert(err, IsNil)
  2568. c.Assert(len(taggingResult.Tags), Equals, 0)
  2569. //delete object tagging again
  2570. err = s.bucket.DeleteObjectTagging(objectName)
  2571. c.Assert(err, IsNil)
  2572. s.bucket.DeleteObject(objectName)
  2573. }
  2574. func (s *OssBucketSuite) TestUploadFileMimeShtml(c *C) {
  2575. // create a bucket with default proprety
  2576. client, err := New(endpoint, accessID, accessKey)
  2577. c.Assert(err, IsNil)
  2578. bucketName := bucketNamePrefix + RandLowStr(6)
  2579. err = client.CreateBucket(bucketName)
  2580. c.Assert(err, IsNil)
  2581. bucket, err := client.Bucket(bucketName)
  2582. objectName := objectNamePrefix + RandStr(8)
  2583. fileName := "oss-sdk-test-file-" + RandLowStr(5) + ".shtml"
  2584. CreateFile(fileName, "123", c)
  2585. err = bucket.PutObjectFromFile(objectName, fileName)
  2586. c.Assert(err, IsNil)
  2587. headResult, err := bucket.GetObjectDetailedMeta(objectName)
  2588. c.Assert(err, IsNil)
  2589. strContentType := headResult.Get("Content-Type")
  2590. c.Assert(strings.Contains(strContentType, "text/html"), Equals, true)
  2591. os.Remove(fileName)
  2592. ForceDeleteBucket(client, bucketName, c)
  2593. }
  2594. func (s *OssBucketSuite) TestVersioningBucketVerison(c *C) {
  2595. // create a bucket with default proprety
  2596. client, err := New(endpoint, accessID, accessKey)
  2597. c.Assert(err, IsNil)
  2598. bucketName := bucketNamePrefix + RandLowStr(6)
  2599. err = client.CreateBucket(bucketName)
  2600. c.Assert(err, IsNil)
  2601. // Get default bucket info
  2602. bucketResult, err := client.GetBucketInfo(bucketName)
  2603. c.Assert(err, IsNil)
  2604. c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
  2605. c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "")
  2606. c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
  2607. // put bucket version:enabled
  2608. var respHeader http.Header
  2609. var versioningConfig VersioningConfig
  2610. versioningConfig.Status = string(VersionEnabled)
  2611. err = client.SetBucketVersioning(bucketName, versioningConfig, GetResponseHeader(&respHeader))
  2612. c.Assert(err, IsNil)
  2613. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  2614. bucketResult, err = client.GetBucketInfo(bucketName)
  2615. c.Assert(err, IsNil)
  2616. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2617. // put bucket version:Suspended
  2618. versioningConfig.Status = string(VersionSuspended)
  2619. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2620. c.Assert(err, IsNil)
  2621. bucketResult, err = client.GetBucketInfo(bucketName)
  2622. c.Assert(err, IsNil)
  2623. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionSuspended))
  2624. ForceDeleteBucket(client, bucketName, c)
  2625. }
  2626. func (s *OssBucketSuite) TestVersioningPutAndGetObject(c *C) {
  2627. // create a bucket with default proprety
  2628. client, err := New(endpoint, accessID, accessKey)
  2629. c.Assert(err, IsNil)
  2630. bucketName := bucketNamePrefix + RandLowStr(6)
  2631. err = client.CreateBucket(bucketName)
  2632. c.Assert(err, IsNil)
  2633. bucket, err := client.Bucket(bucketName)
  2634. // put bucket version:enabled
  2635. var versioningConfig VersioningConfig
  2636. versioningConfig.Status = string(VersionEnabled)
  2637. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2638. c.Assert(err, IsNil)
  2639. bucketResult, err := client.GetBucketInfo(bucketName)
  2640. c.Assert(err, IsNil)
  2641. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2642. // put object v1
  2643. objectName := objectNamePrefix + RandStr(8)
  2644. contextV1 := RandStr(100)
  2645. versionIdV1 := ""
  2646. var respHeader http.Header
  2647. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2648. c.Assert(err, IsNil)
  2649. versionIdV1 = GetVersionId(respHeader)
  2650. c.Assert(len(versionIdV1) > 0, Equals, true)
  2651. // put object v2
  2652. contextV2 := RandStr(200)
  2653. versionIdV2 := ""
  2654. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2655. c.Assert(err, IsNil)
  2656. versionIdV2 = GetVersionId(respHeader)
  2657. c.Assert(len(versionIdV2) > 0, Equals, true)
  2658. // check v1 and v2
  2659. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2660. // get object v1
  2661. body, err := bucket.GetObject(objectName, VersionId(versionIdV1))
  2662. c.Assert(err, IsNil)
  2663. str, err := readBody(body)
  2664. c.Assert(err, IsNil)
  2665. body.Close()
  2666. c.Assert(str, Equals, contextV1)
  2667. // get object v2
  2668. body, err = bucket.GetObject(objectName, VersionId(versionIdV2))
  2669. c.Assert(err, IsNil)
  2670. str, err = readBody(body)
  2671. c.Assert(err, IsNil)
  2672. body.Close()
  2673. c.Assert(str, Equals, contextV2)
  2674. // get object without version
  2675. body, err = bucket.GetObject(objectName)
  2676. c.Assert(err, IsNil)
  2677. str, err = readBody(body)
  2678. c.Assert(err, IsNil)
  2679. body.Close()
  2680. c.Assert(str, Equals, contextV2)
  2681. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2682. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2683. ForceDeleteBucket(client, bucketName, c)
  2684. }
  2685. func (s *OssBucketSuite) TestVersioningHeadObject(c *C) {
  2686. // create a bucket with default proprety
  2687. client, err := New(endpoint, accessID, accessKey)
  2688. c.Assert(err, IsNil)
  2689. bucketName := bucketNamePrefix + RandLowStr(6)
  2690. err = client.CreateBucket(bucketName)
  2691. c.Assert(err, IsNil)
  2692. bucket, err := client.Bucket(bucketName)
  2693. // put bucket version:enabled
  2694. var versioningConfig VersioningConfig
  2695. versioningConfig.Status = string(VersionEnabled)
  2696. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2697. c.Assert(err, IsNil)
  2698. bucketResult, err := client.GetBucketInfo(bucketName)
  2699. c.Assert(err, IsNil)
  2700. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2701. // put object v1
  2702. objectName := objectNamePrefix + RandStr(8)
  2703. contextV1 := RandStr(100)
  2704. versionIdV1 := ""
  2705. var respHeader http.Header
  2706. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2707. c.Assert(err, IsNil)
  2708. versionIdV1 = GetVersionId(respHeader)
  2709. c.Assert(len(versionIdV1) > 0, Equals, true)
  2710. // put object v2
  2711. contextV2 := RandStr(200)
  2712. versionIdV2 := ""
  2713. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2714. c.Assert(err, IsNil)
  2715. versionIdV2 = GetVersionId(respHeader)
  2716. c.Assert(len(versionIdV2) > 0, Equals, true)
  2717. // check v1 and v2
  2718. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2719. // head object v1
  2720. headResultV1, err := bucket.GetObjectMeta(objectName, VersionId(versionIdV1))
  2721. objLen, err := strconv.Atoi(headResultV1.Get("Content-Length"))
  2722. c.Assert(objLen, Equals, len(contextV1))
  2723. headResultV1, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV1))
  2724. objLen, err = strconv.Atoi(headResultV1.Get("Content-Length"))
  2725. c.Assert(objLen, Equals, len(contextV1))
  2726. // head object v2
  2727. headResultV2, err := bucket.GetObjectMeta(objectName, VersionId(versionIdV2))
  2728. objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
  2729. c.Assert(objLen, Equals, len(contextV2))
  2730. headResultV2, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV2))
  2731. objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
  2732. c.Assert(objLen, Equals, len(contextV2))
  2733. // head object without version
  2734. // head object v2
  2735. headResult, err := bucket.GetObjectMeta(objectName)
  2736. objLen, err = strconv.Atoi(headResult.Get("Content-Length"))
  2737. c.Assert(objLen, Equals, len(contextV2))
  2738. headResult, err = bucket.GetObjectDetailedMeta(objectName)
  2739. objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
  2740. c.Assert(objLen, Equals, len(contextV2))
  2741. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2742. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2743. ForceDeleteBucket(client, bucketName, c)
  2744. }
  2745. func (s *OssBucketSuite) TestVersioningDeleteLatestVersionObject(c *C) {
  2746. // create a bucket with default proprety
  2747. client, err := New(endpoint, accessID, accessKey)
  2748. c.Assert(err, IsNil)
  2749. bucketName := bucketNamePrefix + RandLowStr(6)
  2750. err = client.CreateBucket(bucketName)
  2751. c.Assert(err, IsNil)
  2752. bucket, err := client.Bucket(bucketName)
  2753. // put bucket version:enabled
  2754. var versioningConfig VersioningConfig
  2755. versioningConfig.Status = string(VersionEnabled)
  2756. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2757. c.Assert(err, IsNil)
  2758. bucketResult, err := client.GetBucketInfo(bucketName)
  2759. c.Assert(err, IsNil)
  2760. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2761. // put object v1
  2762. objectName := objectNamePrefix + RandStr(8)
  2763. contextV1 := RandStr(100)
  2764. versionIdV1 := ""
  2765. var respHeader http.Header
  2766. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2767. c.Assert(err, IsNil)
  2768. versionIdV1 = GetVersionId(respHeader)
  2769. c.Assert(len(versionIdV1) > 0, Equals, true)
  2770. // put object v2
  2771. contextV2 := RandStr(200)
  2772. versionIdV2 := ""
  2773. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2774. c.Assert(err, IsNil)
  2775. versionIdV2 = GetVersionId(respHeader)
  2776. c.Assert(len(versionIdV2) > 0, Equals, true)
  2777. // check v1 and v2
  2778. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2779. // delete v2 object:permently delete
  2780. options := []Option{VersionId(versionIdV2), GetResponseHeader(&respHeader)}
  2781. err = bucket.DeleteObject(objectName, options...)
  2782. c.Assert(err, IsNil)
  2783. c.Assert(GetVersionId(respHeader), Equals, versionIdV2)
  2784. // get v2 object failure
  2785. body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
  2786. c.Assert(err, NotNil)
  2787. c.Assert(err.(ServiceError).Code, Equals, "NoSuchVersion")
  2788. // get v1 object success
  2789. body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
  2790. c.Assert(err, IsNil)
  2791. str, err := readBody(body)
  2792. body.Close()
  2793. c.Assert(err, IsNil)
  2794. c.Assert(str, Equals, contextV1)
  2795. // get default object success:v1
  2796. body, err = bucket.GetObject(objectName)
  2797. c.Assert(err, IsNil)
  2798. str, err = readBody(body)
  2799. body.Close()
  2800. c.Assert(err, IsNil)
  2801. c.Assert(str, Equals, contextV1)
  2802. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2803. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2804. ForceDeleteBucket(client, bucketName, c)
  2805. }
  2806. func (s *OssBucketSuite) TestVersioningDeleteOldVersionObject(c *C) {
  2807. // create a bucket with default proprety
  2808. client, err := New(endpoint, accessID, accessKey)
  2809. c.Assert(err, IsNil)
  2810. bucketName := bucketNamePrefix + RandLowStr(6)
  2811. err = client.CreateBucket(bucketName)
  2812. c.Assert(err, IsNil)
  2813. bucket, err := client.Bucket(bucketName)
  2814. // put bucket version:enabled
  2815. var versioningConfig VersioningConfig
  2816. versioningConfig.Status = string(VersionEnabled)
  2817. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2818. c.Assert(err, IsNil)
  2819. bucketResult, err := client.GetBucketInfo(bucketName)
  2820. c.Assert(err, IsNil)
  2821. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2822. // put object v1
  2823. objectName := objectNamePrefix + RandStr(8)
  2824. contextV1 := RandStr(100)
  2825. versionIdV1 := ""
  2826. var respHeader http.Header
  2827. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2828. c.Assert(err, IsNil)
  2829. versionIdV1 = GetVersionId(respHeader)
  2830. c.Assert(len(versionIdV1) > 0, Equals, true)
  2831. // put object v2
  2832. contextV2 := RandStr(200)
  2833. versionIdV2 := ""
  2834. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2835. c.Assert(err, IsNil)
  2836. versionIdV2 = GetVersionId(respHeader)
  2837. c.Assert(len(versionIdV2) > 0, Equals, true)
  2838. // check v1 and v2
  2839. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2840. // delete v1 object:permently delete
  2841. options := []Option{VersionId(versionIdV1), GetResponseHeader(&respHeader)}
  2842. err = bucket.DeleteObject(objectName, options...)
  2843. c.Assert(err, IsNil)
  2844. c.Assert(GetVersionId(respHeader), Equals, versionIdV1)
  2845. // get v2 object success
  2846. body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
  2847. c.Assert(err, IsNil)
  2848. str, err := readBody(body)
  2849. body.Close()
  2850. c.Assert(err, IsNil)
  2851. c.Assert(str, Equals, contextV2)
  2852. // get v1 object faliure
  2853. body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
  2854. c.Assert(err, NotNil)
  2855. c.Assert(err.(ServiceError).Code, Equals, "NoSuchVersion")
  2856. // get default object success:v2
  2857. body, err = bucket.GetObject(objectName)
  2858. c.Assert(err, IsNil)
  2859. str, err = readBody(body)
  2860. body.Close()
  2861. c.Assert(err, IsNil)
  2862. c.Assert(str, Equals, contextV2)
  2863. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2864. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2865. ForceDeleteBucket(client, bucketName, c)
  2866. }
  2867. func (s *OssBucketSuite) TestVersioningDeleteDefaultVersionObject(c *C) {
  2868. // create a bucket with default proprety
  2869. client, err := New(endpoint, accessID, accessKey)
  2870. c.Assert(err, IsNil)
  2871. bucketName := bucketNamePrefix + RandLowStr(6)
  2872. err = client.CreateBucket(bucketName)
  2873. c.Assert(err, IsNil)
  2874. bucket, err := client.Bucket(bucketName)
  2875. // put bucket version:enabled
  2876. var versioningConfig VersioningConfig
  2877. versioningConfig.Status = string(VersionEnabled)
  2878. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2879. c.Assert(err, IsNil)
  2880. bucketResult, err := client.GetBucketInfo(bucketName)
  2881. c.Assert(err, IsNil)
  2882. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2883. // put object v1
  2884. objectName := objectNamePrefix + RandStr(8)
  2885. contextV1 := RandStr(100)
  2886. versionIdV1 := ""
  2887. var respHeader http.Header
  2888. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2889. c.Assert(err, IsNil)
  2890. versionIdV1 = GetVersionId(respHeader)
  2891. c.Assert(len(versionIdV1) > 0, Equals, true)
  2892. // put object v2
  2893. contextV2 := RandStr(200)
  2894. versionIdV2 := ""
  2895. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2896. c.Assert(err, IsNil)
  2897. versionIdV2 = GetVersionId(respHeader)
  2898. c.Assert(len(versionIdV2) > 0, Equals, true)
  2899. // check v1 and v2
  2900. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2901. // delete default object:mark delete v2
  2902. options := []Option{GetResponseHeader(&respHeader)}
  2903. err = bucket.DeleteObject(objectName, options...)
  2904. c.Assert(err, IsNil)
  2905. markVersionId := GetVersionId(respHeader)
  2906. c.Assert(len(markVersionId) > 0, Equals, true)
  2907. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  2908. // get v2 object success
  2909. body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
  2910. c.Assert(err, IsNil)
  2911. str, err := readBody(body)
  2912. body.Close()
  2913. c.Assert(err, IsNil)
  2914. c.Assert(str, Equals, contextV2)
  2915. // get v1 object success
  2916. body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
  2917. c.Assert(err, IsNil)
  2918. str, err = readBody(body)
  2919. body.Close()
  2920. c.Assert(err, IsNil)
  2921. c.Assert(str, Equals, contextV1)
  2922. // get default object failure:marker v2
  2923. body, err = bucket.GetObject(objectName, GetResponseHeader(&respHeader))
  2924. c.Assert(err, NotNil)
  2925. c.Assert(err.(ServiceError).Code, Equals, "NoSuchKey")
  2926. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  2927. // delete mark v2
  2928. options = []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
  2929. err = bucket.DeleteObject(objectName, options...)
  2930. c.Assert(err, IsNil)
  2931. c.Assert(GetVersionId(respHeader), Equals, markVersionId)
  2932. // get default object success:v2
  2933. body, err = bucket.GetObject(objectName, VersionId(versionIdV2))
  2934. c.Assert(err, IsNil)
  2935. str, err = readBody(body)
  2936. body.Close()
  2937. c.Assert(err, IsNil)
  2938. c.Assert(str, Equals, contextV2)
  2939. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2940. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2941. ForceDeleteBucket(client, bucketName, c)
  2942. }
  2943. func (s *OssBucketSuite) TestVersioningListObjectVersions(c *C) {
  2944. // create a bucket with default proprety
  2945. client, err := New(endpoint, accessID, accessKey)
  2946. c.Assert(err, IsNil)
  2947. bucketName := bucketNamePrefix + RandLowStr(6)
  2948. err = client.CreateBucket(bucketName)
  2949. c.Assert(err, IsNil)
  2950. bucket, err := client.Bucket(bucketName)
  2951. // put bucket version:enabled
  2952. var versioningConfig VersioningConfig
  2953. versioningConfig.Status = string(VersionEnabled)
  2954. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2955. c.Assert(err, IsNil)
  2956. bucketResult, err := client.GetBucketInfo(bucketName)
  2957. c.Assert(err, IsNil)
  2958. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2959. // put object v1
  2960. objectName := objectNamePrefix + RandStr(8)
  2961. contextV1 := RandStr(100)
  2962. versionIdV1 := ""
  2963. var respHeader http.Header
  2964. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2965. c.Assert(err, IsNil)
  2966. versionIdV1 = GetVersionId(respHeader)
  2967. c.Assert(len(versionIdV1) > 0, Equals, true)
  2968. // put object v2
  2969. contextV2 := RandStr(200)
  2970. versionIdV2 := ""
  2971. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2972. c.Assert(err, IsNil)
  2973. versionIdV2 = GetVersionId(respHeader)
  2974. c.Assert(len(versionIdV2) > 0, Equals, true)
  2975. // check v1 and v2
  2976. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2977. // delete default object:mark delete v2
  2978. options := []Option{GetResponseHeader(&respHeader)}
  2979. err = bucket.DeleteObject(objectName, options...)
  2980. c.Assert(err, IsNil)
  2981. markVersionId := GetVersionId(respHeader)
  2982. c.Assert(len(markVersionId) > 0, Equals, true)
  2983. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  2984. // delete default object again:mark delete v2
  2985. err = bucket.DeleteObject(objectName, options...)
  2986. c.Assert(err, IsNil)
  2987. markVersionIdAgain := GetVersionId(respHeader)
  2988. c.Assert(len(markVersionIdAgain) > 0, Equals, true)
  2989. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  2990. c.Assert(markVersionId != markVersionIdAgain, Equals, true)
  2991. // list bucket versions
  2992. listResult, err := bucket.ListObjectVersions()
  2993. c.Assert(err, IsNil)
  2994. c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 2)
  2995. c.Assert(len(listResult.ObjectVersions), Equals, 2)
  2996. mapMarkVersion := map[string]string{}
  2997. mapMarkVersion[listResult.ObjectDeleteMarkers[0].VersionId] = listResult.ObjectDeleteMarkers[0].VersionId
  2998. mapMarkVersion[listResult.ObjectDeleteMarkers[1].VersionId] = listResult.ObjectDeleteMarkers[1].VersionId
  2999. // check delete mark
  3000. _, ok := mapMarkVersion[markVersionId]
  3001. c.Assert(ok == true, Equals, true)
  3002. _, ok = mapMarkVersion[markVersionIdAgain]
  3003. c.Assert(ok == true, Equals, true)
  3004. // check versionId
  3005. mapVersion := map[string]string{}
  3006. mapVersion[listResult.ObjectVersions[0].VersionId] = listResult.ObjectVersions[0].VersionId
  3007. mapVersion[listResult.ObjectVersions[1].VersionId] = listResult.ObjectVersions[1].VersionId
  3008. _, ok = mapVersion[versionIdV1]
  3009. c.Assert(ok == true, Equals, true)
  3010. _, ok = mapVersion[versionIdV2]
  3011. c.Assert(ok == true, Equals, true)
  3012. // delete deleteMark v2
  3013. options = []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
  3014. err = bucket.DeleteObject(objectName, options...)
  3015. c.Assert(err, IsNil)
  3016. c.Assert(GetVersionId(respHeader), Equals, markVersionId)
  3017. // delete deleteMark v2 again
  3018. options = []Option{VersionId(markVersionIdAgain), GetResponseHeader(&respHeader)}
  3019. err = bucket.DeleteObject(objectName, options...)
  3020. c.Assert(err, IsNil)
  3021. c.Assert(GetVersionId(respHeader), Equals, markVersionIdAgain)
  3022. // delete versionId
  3023. bucket.DeleteObject(objectName, VersionId(versionIdV1))
  3024. bucket.DeleteObject(objectName, VersionId(versionIdV2))
  3025. ForceDeleteBucket(client, bucketName, c)
  3026. }
  3027. func (s *OssBucketSuite) TestVersioningBatchDeleteVersionObjects(c *C) {
  3028. // create a bucket with default proprety
  3029. client, err := New(endpoint, accessID, accessKey)
  3030. c.Assert(err, IsNil)
  3031. bucketName := bucketNamePrefix + RandLowStr(6)
  3032. err = client.CreateBucket(bucketName)
  3033. c.Assert(err, IsNil)
  3034. bucket, err := client.Bucket(bucketName)
  3035. // put bucket version:enabled
  3036. var versioningConfig VersioningConfig
  3037. versioningConfig.Status = string(VersionEnabled)
  3038. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3039. c.Assert(err, IsNil)
  3040. bucketResult, err := client.GetBucketInfo(bucketName)
  3041. c.Assert(err, IsNil)
  3042. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  3043. // put object v1
  3044. objectName1 := objectNamePrefix + RandStr(8)
  3045. contextV1 := RandStr(100)
  3046. versionIdV1 := ""
  3047. var respHeader http.Header
  3048. err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3049. c.Assert(err, IsNil)
  3050. versionIdV1 = GetVersionId(respHeader)
  3051. c.Assert(len(versionIdV1) > 0, Equals, true)
  3052. // put object v2
  3053. objectName2 := objectNamePrefix + RandStr(8)
  3054. contextV2 := RandStr(200)
  3055. versionIdV2 := ""
  3056. err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3057. c.Assert(err, IsNil)
  3058. versionIdV2 = GetVersionId(respHeader)
  3059. c.Assert(len(versionIdV2) > 0, Equals, true)
  3060. // check v1 and v2
  3061. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3062. //batch delete objects
  3063. versionIds := []DeleteObject{DeleteObject{Key: objectName1, VersionId: versionIdV1},
  3064. DeleteObject{Key: objectName2, VersionId: versionIdV2}}
  3065. deleteResult, err := bucket.DeleteObjectVersions(versionIds)
  3066. c.Assert(err, IsNil)
  3067. c.Assert(len(deleteResult.DeletedObjectsDetail), Equals, 2)
  3068. // check delete detail info:key
  3069. deleteMap := map[string]string{}
  3070. deleteMap[deleteResult.DeletedObjectsDetail[0].Key] = deleteResult.DeletedObjectsDetail[0].VersionId
  3071. deleteMap[deleteResult.DeletedObjectsDetail[1].Key] = deleteResult.DeletedObjectsDetail[1].VersionId
  3072. id1, ok := deleteMap[objectName1]
  3073. c.Assert(ok, Equals, true)
  3074. c.Assert(id1, Equals, versionIdV1)
  3075. id2, ok := deleteMap[objectName2]
  3076. c.Assert(ok, Equals, true)
  3077. c.Assert(id2, Equals, versionIdV2)
  3078. // list bucket versions
  3079. listResult, err := bucket.ListObjectVersions()
  3080. c.Assert(err, IsNil)
  3081. c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 0)
  3082. c.Assert(len(listResult.ObjectVersions), Equals, 0)
  3083. ForceDeleteBucket(client, bucketName, c)
  3084. }
  3085. func (s *OssBucketSuite) TestVersioningBatchDeleteDefaultVersionObjects(c *C) {
  3086. // create a bucket with default proprety
  3087. client, err := New(endpoint, accessID, accessKey)
  3088. c.Assert(err, IsNil)
  3089. bucketName := bucketNamePrefix + RandLowStr(6)
  3090. err = client.CreateBucket(bucketName)
  3091. c.Assert(err, IsNil)
  3092. bucket, err := client.Bucket(bucketName)
  3093. // put bucket version:enabled
  3094. var versioningConfig VersioningConfig
  3095. versioningConfig.Status = string(VersionEnabled)
  3096. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3097. c.Assert(err, IsNil)
  3098. bucketResult, err := client.GetBucketInfo(bucketName)
  3099. c.Assert(err, IsNil)
  3100. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  3101. // put object v1
  3102. objectName1 := objectNamePrefix + RandStr(8)
  3103. contextV1 := RandStr(100)
  3104. versionIdV1 := ""
  3105. var respHeader http.Header
  3106. err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3107. c.Assert(err, IsNil)
  3108. versionIdV1 = GetVersionId(respHeader)
  3109. c.Assert(len(versionIdV1) > 0, Equals, true)
  3110. // put object v2
  3111. objectName2 := objectNamePrefix + RandStr(8)
  3112. contextV2 := RandStr(200)
  3113. versionIdV2 := ""
  3114. err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3115. c.Assert(err, IsNil)
  3116. versionIdV2 = GetVersionId(respHeader)
  3117. c.Assert(len(versionIdV2) > 0, Equals, true)
  3118. // check v1 and v2
  3119. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3120. //batch delete objects
  3121. versionIds := []DeleteObject{DeleteObject{Key: objectName1, VersionId: ""},
  3122. DeleteObject{Key: objectName2, VersionId: ""}}
  3123. deleteResult, err := bucket.DeleteObjectVersions(versionIds)
  3124. c.Assert(err, IsNil)
  3125. // check delete detail info:key
  3126. deleteDetailMap := map[string]DeletedKeyInfo{}
  3127. deleteDetailMap[deleteResult.DeletedObjectsDetail[0].Key] = deleteResult.DeletedObjectsDetail[0]
  3128. deleteDetailMap[deleteResult.DeletedObjectsDetail[1].Key] = deleteResult.DeletedObjectsDetail[1]
  3129. keyInfo1, ok := deleteDetailMap[objectName1]
  3130. c.Assert(ok, Equals, true)
  3131. c.Assert(keyInfo1.Key, Equals, objectName1)
  3132. c.Assert(keyInfo1.VersionId, Equals, "")
  3133. c.Assert(keyInfo1.DeleteMarker, Equals, true)
  3134. c.Assert(keyInfo1.DeleteMarkerVersionId != versionIdV1, Equals, true)
  3135. keyInfo2, ok := deleteDetailMap[objectName2]
  3136. c.Assert(ok, Equals, true)
  3137. c.Assert(keyInfo2.Key, Equals, objectName2)
  3138. c.Assert(keyInfo2.VersionId, Equals, "")
  3139. c.Assert(keyInfo2.DeleteMarker, Equals, true)
  3140. c.Assert(keyInfo2.DeleteMarkerVersionId != versionIdV2, Equals, true)
  3141. // list bucket versions
  3142. listResult, err := bucket.ListObjectVersions()
  3143. c.Assert(err, IsNil)
  3144. c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 2)
  3145. c.Assert(len(listResult.ObjectVersions), Equals, 2)
  3146. // delete version object
  3147. versionIds = []DeleteObject{DeleteObject{Key: objectName1, VersionId: versionIdV1},
  3148. DeleteObject{Key: objectName2, VersionId: versionIdV2}}
  3149. deleteResult, err = bucket.DeleteObjectVersions(versionIds)
  3150. c.Assert(err, IsNil)
  3151. // delete deleteMark object
  3152. versionIds = []DeleteObject{DeleteObject{Key: objectName1, VersionId: keyInfo1.DeleteMarkerVersionId},
  3153. DeleteObject{Key: objectName2, VersionId: keyInfo2.DeleteMarkerVersionId}}
  3154. deleteResult, err = bucket.DeleteObjectVersions(versionIds)
  3155. c.Assert(err, IsNil)
  3156. ForceDeleteBucket(client, bucketName, c)
  3157. }
  3158. // bucket has no versioning flag
  3159. func (s *OssBucketSuite) TestVersioningBatchDeleteNormalObjects(c *C) {
  3160. // create a bucket with default proprety
  3161. client, err := New(endpoint, accessID, accessKey)
  3162. c.Assert(err, IsNil)
  3163. bucketName := bucketNamePrefix + RandLowStr(6)
  3164. err = client.CreateBucket(bucketName)
  3165. c.Assert(err, IsNil)
  3166. // not put bucket versioning
  3167. bucket, err := client.Bucket(bucketName)
  3168. // put object v1
  3169. objectName1 := objectNamePrefix + RandStr(8)
  3170. contextV1 := RandStr(100)
  3171. versionIdV1 := ""
  3172. var respHeader http.Header
  3173. err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3174. c.Assert(err, IsNil)
  3175. versionIdV1 = GetVersionId(respHeader)
  3176. c.Assert(len(versionIdV1), Equals, 0)
  3177. // put object v2
  3178. objectName2 := objectNamePrefix + RandStr(8)
  3179. contextV2 := RandStr(200)
  3180. versionIdV2 := ""
  3181. err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3182. c.Assert(err, IsNil)
  3183. versionIdV2 = GetVersionId(respHeader)
  3184. c.Assert(len(versionIdV2), Equals, 0)
  3185. //batch delete objects
  3186. keys := []string{objectName1, objectName2}
  3187. deleteResult, err := bucket.DeleteObjects(keys)
  3188. c.Assert(len(deleteResult.DeletedObjects), Equals, 2)
  3189. // check delete info
  3190. deleteMap := map[string]string{}
  3191. deleteMap[deleteResult.DeletedObjects[0]] = deleteResult.DeletedObjects[0]
  3192. deleteMap[deleteResult.DeletedObjects[1]] = deleteResult.DeletedObjects[1]
  3193. _, ok := deleteMap[objectName1]
  3194. c.Assert(ok, Equals, true)
  3195. _, ok = deleteMap[objectName2]
  3196. c.Assert(ok, Equals, true)
  3197. ForceDeleteBucket(client, bucketName, c)
  3198. c.Assert(err, IsNil)
  3199. }
  3200. func (s *OssBucketSuite) TestVersioningSymlink(c *C) {
  3201. // create a bucket with default proprety
  3202. client, err := New(endpoint, accessID, accessKey)
  3203. c.Assert(err, IsNil)
  3204. bucketName := bucketNamePrefix + RandLowStr(6)
  3205. err = client.CreateBucket(bucketName)
  3206. c.Assert(err, IsNil)
  3207. bucket, err := client.Bucket(bucketName)
  3208. // put bucket version:enabled
  3209. var versioningConfig VersioningConfig
  3210. versioningConfig.Status = string(VersionEnabled)
  3211. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3212. c.Assert(err, IsNil)
  3213. // put object 1
  3214. objectName1 := objectNamePrefix + RandStr(8)
  3215. contextV1 := RandStr(100)
  3216. versionIdV1 := ""
  3217. var respHeader http.Header
  3218. err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3219. c.Assert(err, IsNil)
  3220. versionIdV1 = GetVersionId(respHeader)
  3221. c.Assert(len(versionIdV1) > 0, Equals, true)
  3222. // put object 2
  3223. objectName2 := objectNamePrefix + RandStr(8)
  3224. contextV2 := RandStr(200)
  3225. versionIdV2 := ""
  3226. err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3227. c.Assert(err, IsNil)
  3228. versionIdV2 = GetVersionId(respHeader)
  3229. c.Assert(len(versionIdV2) > 0, Equals, true)
  3230. // check v1 and v2
  3231. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3232. // put symlink for object 1
  3233. linkName := objectNamePrefix + RandStr(8)
  3234. err = bucket.PutSymlink(linkName, objectName1, GetResponseHeader(&respHeader))
  3235. c.Assert(err, IsNil)
  3236. linkVersionIdV1 := GetVersionId(respHeader)
  3237. // PutSymlink for object 2
  3238. err = bucket.PutSymlink(linkName, objectName2, GetResponseHeader(&respHeader))
  3239. c.Assert(err, IsNil)
  3240. linkVersionIdV2 := GetVersionId(respHeader)
  3241. // check v1 and v2
  3242. c.Assert(linkVersionIdV1 != linkVersionIdV2, Equals, true)
  3243. // GetSymlink for object1
  3244. getResult, err := bucket.GetSymlink(linkName, VersionId(linkVersionIdV1))
  3245. c.Assert(err, IsNil)
  3246. c.Assert(getResult.Get("x-oss-symlink-target"), Equals, objectName1)
  3247. // GetSymlink for object2
  3248. getResult, err = bucket.GetSymlink(linkName, VersionId(linkVersionIdV2))
  3249. c.Assert(err, IsNil)
  3250. c.Assert(getResult.Get("x-oss-symlink-target"), Equals, objectName2)
  3251. bucket.DeleteObject(linkName)
  3252. bucket.DeleteObject(objectName1)
  3253. bucket.DeleteObject(objectName2)
  3254. ForceDeleteBucket(client, bucketName, c)
  3255. }
  3256. func (s *OssBucketSuite) TestVersioningObjectAcl(c *C) {
  3257. // create a bucket with default proprety
  3258. client, err := New(endpoint, accessID, accessKey)
  3259. c.Assert(err, IsNil)
  3260. bucketName := bucketNamePrefix + RandLowStr(6)
  3261. err = client.CreateBucket(bucketName)
  3262. c.Assert(err, IsNil)
  3263. bucket, err := client.Bucket(bucketName)
  3264. // put bucket version:enabled
  3265. var versioningConfig VersioningConfig
  3266. versioningConfig.Status = string(VersionEnabled)
  3267. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3268. c.Assert(err, IsNil)
  3269. // put object v1
  3270. objectName := objectNamePrefix + RandStr(8)
  3271. contextV1 := RandStr(100)
  3272. versionIdV1 := ""
  3273. var respHeader http.Header
  3274. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3275. c.Assert(err, IsNil)
  3276. versionIdV1 = GetVersionId(respHeader)
  3277. c.Assert(len(versionIdV1) > 0, Equals, true)
  3278. // put object v2
  3279. contextV2 := RandStr(200)
  3280. versionIdV2 := ""
  3281. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3282. c.Assert(err, IsNil)
  3283. versionIdV2 = GetVersionId(respHeader)
  3284. c.Assert(len(versionIdV2) > 0, Equals, true)
  3285. // check v1 and v2
  3286. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3287. // put Acl for v1
  3288. err = bucket.SetObjectACL(objectName, ACLPublicRead, VersionId(versionIdV1))
  3289. c.Assert(err, IsNil)
  3290. // put Acl for v2
  3291. err = bucket.SetObjectACL(objectName, ACLPublicReadWrite, VersionId(versionIdV2))
  3292. c.Assert(err, IsNil)
  3293. // GetAcl for v1
  3294. getResult, err := bucket.GetObjectACL(objectName, VersionId(versionIdV1))
  3295. c.Assert(err, IsNil)
  3296. c.Assert(getResult.ACL, Equals, string(ACLPublicRead))
  3297. // GetAcl for v2
  3298. getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV2))
  3299. c.Assert(err, IsNil)
  3300. c.Assert(getResult.ACL, Equals, string(ACLPublicReadWrite))
  3301. // delete default version
  3302. err = bucket.DeleteObject(objectName, GetResponseHeader(&respHeader))
  3303. c.Assert(len(GetVersionId(respHeader)) > 0, Equals, true)
  3304. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  3305. // GetAcl for v1 agagin
  3306. getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV1))
  3307. c.Assert(err, IsNil)
  3308. c.Assert(getResult.ACL, Equals, string(ACLPublicRead))
  3309. // GetAcl for v2 again
  3310. getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV2))
  3311. c.Assert(err, IsNil)
  3312. c.Assert(getResult.ACL, Equals, string(ACLPublicReadWrite))
  3313. // GetAcl for default failure
  3314. getResult, err = bucket.GetObjectACL(objectName)
  3315. c.Assert(err, NotNil)
  3316. bucket.DeleteObject(objectName)
  3317. ForceDeleteBucket(client, bucketName, c)
  3318. }
  3319. func (s *OssBucketSuite) TestVersioningAppendObject(c *C) {
  3320. // create a bucket with default proprety
  3321. client, err := New(endpoint, accessID, accessKey)
  3322. c.Assert(err, IsNil)
  3323. bucketName := bucketNamePrefix + RandLowStr(6)
  3324. err = client.CreateBucket(bucketName)
  3325. c.Assert(err, IsNil)
  3326. bucket, err := client.Bucket(bucketName)
  3327. // put bucket version:enabled
  3328. var versioningConfig VersioningConfig
  3329. versioningConfig.Status = string(VersionEnabled)
  3330. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3331. c.Assert(err, IsNil)
  3332. // append object
  3333. var nextPos int64 = 0
  3334. var respHeader http.Header
  3335. objectName := objectNamePrefix + RandStr(8)
  3336. nextPos, err = bucket.AppendObject(objectName, strings.NewReader("123"), nextPos, GetResponseHeader(&respHeader))
  3337. c.Assert(err, IsNil)
  3338. c.Assert(GetVersionId(respHeader), Equals, NullVersion)
  3339. nextPos, err = bucket.AppendObject(objectName, strings.NewReader("456"), nextPos, GetResponseHeader(&respHeader))
  3340. c.Assert(err, IsNil)
  3341. c.Assert(GetVersionId(respHeader), Equals, NullVersion)
  3342. // delete object
  3343. err = bucket.DeleteObject(objectName, GetResponseHeader(&respHeader))
  3344. markVersionId := GetVersionId(respHeader)
  3345. // get default object failure
  3346. _, err = bucket.GetObject(objectName)
  3347. c.Assert(err, NotNil)
  3348. // get null version success
  3349. body, err := bucket.GetObject(objectName, VersionId(NullVersion))
  3350. c.Assert(err, IsNil)
  3351. str, err := readBody(body)
  3352. c.Assert(err, IsNil)
  3353. c.Assert(str, Equals, "123456")
  3354. // append object again:failure
  3355. nextPos, err = bucket.AppendObject(objectName, strings.NewReader("789"), nextPos, GetResponseHeader(&respHeader))
  3356. c.Assert(err, NotNil)
  3357. // delete deletemark
  3358. options := []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
  3359. err = bucket.DeleteObject(objectName, options...)
  3360. c.Assert(markVersionId, Equals, GetVersionId(respHeader))
  3361. // append object again:success
  3362. nextPos, err = bucket.AppendObject(objectName, strings.NewReader("789"), nextPos, GetResponseHeader(&respHeader))
  3363. c.Assert(err, IsNil)
  3364. c.Assert(int(nextPos), Equals, 9)
  3365. bucket.DeleteObject(objectName)
  3366. ForceDeleteBucket(client, bucketName, c)
  3367. }
  3368. func (s *OssBucketSuite) TestVersioningCopyObject(c *C) {
  3369. // create a bucket with default proprety
  3370. client, err := New(endpoint, accessID, accessKey)
  3371. c.Assert(err, IsNil)
  3372. bucketName := bucketNamePrefix + RandLowStr(6)
  3373. err = client.CreateBucket(bucketName)
  3374. c.Assert(err, IsNil)
  3375. bucket, err := client.Bucket(bucketName)
  3376. // put bucket version:enabled
  3377. var versioningConfig VersioningConfig
  3378. versioningConfig.Status = string(VersionEnabled)
  3379. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3380. c.Assert(err, IsNil)
  3381. // put object v1
  3382. objectName := objectNamePrefix + RandStr(8)
  3383. contextV1 := RandStr(100)
  3384. versionIdV1 := ""
  3385. var respHeader http.Header
  3386. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3387. c.Assert(err, IsNil)
  3388. versionIdV1 = GetVersionId(respHeader)
  3389. c.Assert(len(versionIdV1) > 0, Equals, true)
  3390. // put object v2
  3391. contextV2 := RandStr(200)
  3392. versionIdV2 := ""
  3393. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3394. c.Assert(err, IsNil)
  3395. versionIdV2 = GetVersionId(respHeader)
  3396. c.Assert(len(versionIdV2) > 0, Equals, true)
  3397. // check v1 and v2
  3398. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3399. destObjectKey := objectNamePrefix + RandStr(8)
  3400. // copyobject default
  3401. _, err = bucket.CopyObject(objectName, destObjectKey, GetResponseHeader(&respHeader))
  3402. c.Assert(err, IsNil)
  3403. srcVersionId := GetCopySrcVersionId(respHeader)
  3404. c.Assert(srcVersionId, Equals, versionIdV2)
  3405. body, err := bucket.GetObject(destObjectKey)
  3406. c.Assert(err, IsNil)
  3407. str, err := readBody(body)
  3408. c.Assert(err, IsNil)
  3409. c.Assert(str, Equals, contextV2)
  3410. // copyobject v1
  3411. options := []Option{VersionId(versionIdV1), GetResponseHeader(&respHeader)}
  3412. _, err = bucket.CopyObject(objectName, destObjectKey, options...)
  3413. c.Assert(err, IsNil)
  3414. srcVersionId = GetCopySrcVersionId(respHeader)
  3415. c.Assert(srcVersionId, Equals, versionIdV1)
  3416. body, err = bucket.GetObject(destObjectKey)
  3417. c.Assert(err, IsNil)
  3418. str, err = readBody(body)
  3419. c.Assert(err, IsNil)
  3420. c.Assert(str, Equals, contextV1)
  3421. // delete object
  3422. err = bucket.DeleteObject(objectName)
  3423. c.Assert(err, IsNil)
  3424. // default copyobject again,failuer
  3425. _, err = bucket.CopyObject(objectName, destObjectKey, GetResponseHeader(&respHeader))
  3426. c.Assert(err, NotNil)
  3427. bucket.DeleteObject(objectName)
  3428. ForceDeleteBucket(client, bucketName, c)
  3429. }
  3430. func (s *OssBucketSuite) TestVersioningCompleteMultipartUpload(c *C) {
  3431. // create a bucket with default proprety
  3432. client, err := New(endpoint, accessID, accessKey)
  3433. c.Assert(err, IsNil)
  3434. bucketName := bucketNamePrefix + RandLowStr(6)
  3435. err = client.CreateBucket(bucketName)
  3436. c.Assert(err, IsNil)
  3437. bucket, err := client.Bucket(bucketName)
  3438. // put bucket version:enabled
  3439. var versioningConfig VersioningConfig
  3440. versioningConfig.Status = string(VersionEnabled)
  3441. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3442. c.Assert(err, IsNil)
  3443. objectName := objectNamePrefix + RandStr(8)
  3444. var fileName = "test-file-" + RandStr(8)
  3445. content := RandStr(500 * 1024)
  3446. CreateFile(fileName, content, c)
  3447. chunks, err := SplitFileByPartNum(fileName, 3)
  3448. c.Assert(err, IsNil)
  3449. options := []Option{
  3450. Expires(futureDate), Meta("my", "myprop"),
  3451. }
  3452. fd, err := os.Open(fileName)
  3453. c.Assert(err, IsNil)
  3454. defer fd.Close()
  3455. imur, err := bucket.InitiateMultipartUpload(objectName, options...)
  3456. c.Assert(err, IsNil)
  3457. var parts []UploadPart
  3458. for _, chunk := range chunks {
  3459. fd.Seek(chunk.Offset, os.SEEK_SET)
  3460. part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number)
  3461. c.Assert(err, IsNil)
  3462. parts = append(parts, part)
  3463. }
  3464. var respHeader http.Header
  3465. _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
  3466. c.Assert(err, IsNil)
  3467. //get versionId
  3468. versionIdV1 := GetVersionId(respHeader)
  3469. c.Assert(len(versionIdV1) > 0, Equals, true)
  3470. meta, err := bucket.GetObjectDetailedMeta(objectName)
  3471. c.Assert(err, IsNil)
  3472. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
  3473. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  3474. c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Multipart")
  3475. // put object agagin
  3476. err = bucket.PutObject(objectName, strings.NewReader(""), GetResponseHeader(&respHeader))
  3477. c.Assert(err, IsNil)
  3478. versionIdV2 := GetVersionId(respHeader)
  3479. c.Assert(versionIdV1 == versionIdV2, Equals, false)
  3480. // get meta v1
  3481. meta, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV1))
  3482. c.Assert(err, IsNil)
  3483. c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(content)))
  3484. // get meta v2
  3485. meta, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV2))
  3486. c.Assert(err, IsNil)
  3487. c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(0))
  3488. os.Remove(fileName)
  3489. bucket.DeleteObject(objectName)
  3490. ForceDeleteBucket(client, bucketName, c)
  3491. }
  3492. func (s *OssBucketSuite) TestVersioningUploadPartCopy(c *C) {
  3493. // create a bucket with default proprety
  3494. client, err := New(endpoint, accessID, accessKey)
  3495. c.Assert(err, IsNil)
  3496. bucketName := bucketNamePrefix + RandLowStr(6)
  3497. err = client.CreateBucket(bucketName)
  3498. c.Assert(err, IsNil)
  3499. bucket, err := client.Bucket(bucketName)
  3500. // put bucket version:enabled
  3501. var versioningConfig VersioningConfig
  3502. versioningConfig.Status = string(VersionEnabled)
  3503. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3504. c.Assert(err, IsNil)
  3505. // put object v1
  3506. objectName := objectNamePrefix + RandStr(8)
  3507. contextV1 := RandStr(100)
  3508. versionIdV1 := ""
  3509. var respHeader http.Header
  3510. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3511. c.Assert(err, IsNil)
  3512. versionIdV1 = GetVersionId(respHeader)
  3513. c.Assert(len(versionIdV1) > 0, Equals, true)
  3514. // put object v2
  3515. contextV2 := RandStr(200)
  3516. versionIdV2 := ""
  3517. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3518. c.Assert(err, IsNil)
  3519. versionIdV2 = GetVersionId(respHeader)
  3520. c.Assert(len(versionIdV2) > 0, Equals, true)
  3521. // upload mutlipart object with v1
  3522. multiName := objectNamePrefix + RandStr(8)
  3523. var parts []UploadPart
  3524. imur, err := bucket.InitiateMultipartUpload(multiName)
  3525. c.Assert(err, IsNil)
  3526. part, err := bucket.UploadPartCopy(imur, bucketName, objectName, 0, int64(len(contextV1)), 1, VersionId(versionIdV1))
  3527. parts = []UploadPart{part}
  3528. c.Assert(err, IsNil)
  3529. _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
  3530. c.Assert(err, IsNil)
  3531. //get versionId
  3532. partVersionIdV1 := GetVersionId(respHeader)
  3533. c.Assert(len(partVersionIdV1) > 0, Equals, true)
  3534. // get meta v1
  3535. meta, err := bucket.GetObjectDetailedMeta(multiName, VersionId(partVersionIdV1))
  3536. c.Assert(err, IsNil)
  3537. c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(contextV1)))
  3538. // upload mutlipart object with v2
  3539. imur, err = bucket.InitiateMultipartUpload(multiName)
  3540. part, err = bucket.UploadPartCopy(imur, bucketName, objectName, 0, int64(len(contextV2)), 1, VersionId(versionIdV2))
  3541. parts = []UploadPart{part}
  3542. _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
  3543. c.Assert(err, IsNil)
  3544. //get versionId
  3545. partVersionIdV2 := GetVersionId(respHeader)
  3546. c.Assert(len(partVersionIdV2) > 0, Equals, true)
  3547. // get meta v2
  3548. meta, err = bucket.GetObjectDetailedMeta(multiName, VersionId(partVersionIdV2))
  3549. c.Assert(err, IsNil)
  3550. c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(contextV2)))
  3551. bucket.DeleteObject(objectName)
  3552. bucket.DeleteObject(multiName)
  3553. ForceDeleteBucket(client, bucketName, c)
  3554. }
  3555. func (s *OssBucketSuite) TestVersioningRestoreObject(c *C) {
  3556. // create a bucket with default proprety
  3557. client, err := New(endpoint, accessID, accessKey)
  3558. c.Assert(err, IsNil)
  3559. bucketName := bucketNamePrefix + RandLowStr(6)
  3560. err = client.CreateBucket(bucketName, StorageClass(StorageArchive))
  3561. c.Assert(err, IsNil)
  3562. bucket, err := client.Bucket(bucketName)
  3563. // put bucket version:enabled
  3564. var versioningConfig VersioningConfig
  3565. versioningConfig.Status = string(VersionEnabled)
  3566. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3567. c.Assert(err, IsNil)
  3568. // put object v1
  3569. objectName := objectNamePrefix + RandStr(8)
  3570. contextV1 := RandStr(100)
  3571. versionIdV1 := ""
  3572. var respHeader http.Header
  3573. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3574. c.Assert(err, IsNil)
  3575. versionIdV1 = GetVersionId(respHeader)
  3576. c.Assert(len(versionIdV1) > 0, Equals, true)
  3577. // put object v2
  3578. contextV2 := RandStr(200)
  3579. versionIdV2 := ""
  3580. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3581. c.Assert(err, IsNil)
  3582. versionIdV2 = GetVersionId(respHeader)
  3583. c.Assert(len(versionIdV2) > 0, Equals, true)
  3584. // RestoreObject v1
  3585. options := []Option{GetResponseHeader(&respHeader), VersionId(versionIdV1)}
  3586. err = bucket.RestoreObject(objectName, options...)
  3587. c.Assert(err, IsNil)
  3588. c.Assert(GetVersionId(respHeader), Equals, versionIdV1)
  3589. // RestoreObject v2
  3590. options = []Option{GetResponseHeader(&respHeader), VersionId(versionIdV2)}
  3591. err = bucket.RestoreObject(objectName, options...)
  3592. c.Assert(err, IsNil)
  3593. c.Assert(GetVersionId(respHeader), Equals, versionIdV2)
  3594. bucket.DeleteObject(objectName)
  3595. ForceDeleteBucket(client, bucketName, c)
  3596. }
  3597. func (s *OssBucketSuite) TestVersioningObjectTagging(c *C) {
  3598. // create a bucket with default proprety
  3599. client, err := New(endpoint, accessID, accessKey)
  3600. c.Assert(err, IsNil)
  3601. bucketName := bucketNamePrefix + RandLowStr(6)
  3602. err = client.CreateBucket(bucketName, StorageClass(StorageArchive))
  3603. c.Assert(err, IsNil)
  3604. bucket, err := client.Bucket(bucketName)
  3605. // put bucket version:enabled
  3606. var versioningConfig VersioningConfig
  3607. versioningConfig.Status = string(VersionEnabled)
  3608. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3609. c.Assert(err, IsNil)
  3610. // put object v1
  3611. objectName := objectNamePrefix + RandStr(8)
  3612. contextV1 := RandStr(100)
  3613. versionIdV1 := ""
  3614. var respHeader http.Header
  3615. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3616. c.Assert(err, IsNil)
  3617. versionIdV1 = GetVersionId(respHeader)
  3618. c.Assert(len(versionIdV1) > 0, Equals, true)
  3619. // put object v2
  3620. contextV2 := RandStr(200)
  3621. versionIdV2 := ""
  3622. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3623. c.Assert(err, IsNil)
  3624. versionIdV2 = GetVersionId(respHeader)
  3625. c.Assert(len(versionIdV2) > 0, Equals, true)
  3626. // ObjectTagging v1
  3627. var tagging1 Tagging
  3628. tagging1.Tags = []Tag{Tag{Key: "testkey1", Value: "testvalue1"}}
  3629. err = bucket.PutObjectTagging(objectName, tagging1, VersionId(versionIdV1))
  3630. c.Assert(err, IsNil)
  3631. getResult, err := bucket.GetObjectTagging(objectName, VersionId(versionIdV1))
  3632. c.Assert(err, IsNil)
  3633. c.Assert(getResult.Tags[0].Key, Equals, tagging1.Tags[0].Key)
  3634. c.Assert(getResult.Tags[0].Value, Equals, tagging1.Tags[0].Value)
  3635. // ObjectTagging v2
  3636. var tagging2 Tagging
  3637. tagging2.Tags = []Tag{Tag{Key: "testkey2", Value: "testvalue2"}}
  3638. err = bucket.PutObjectTagging(objectName, tagging2, VersionId(versionIdV2))
  3639. c.Assert(err, IsNil)
  3640. getResult, err = bucket.GetObjectTagging(objectName, VersionId(versionIdV2))
  3641. c.Assert(err, IsNil)
  3642. c.Assert(getResult.Tags[0].Key, Equals, tagging2.Tags[0].Key)
  3643. c.Assert(getResult.Tags[0].Value, Equals, tagging2.Tags[0].Value)
  3644. // delete ObjectTagging v2
  3645. err = bucket.DeleteObjectTagging(objectName, VersionId(versionIdV2))
  3646. c.Assert(err, IsNil)
  3647. getResult, err = bucket.GetObjectTagging(objectName, VersionId(versionIdV2))
  3648. c.Assert(err, IsNil)
  3649. c.Assert(len(getResult.Tags), Equals, 0)
  3650. bucket.DeleteObject(objectName)
  3651. ForceDeleteBucket(client, bucketName, c)
  3652. }
  3653. func (s *OssBucketSuite) TestVersioningIsObjectExist(c *C) {
  3654. // create a bucket with default proprety
  3655. client, err := New(endpoint, accessID, accessKey)
  3656. c.Assert(err, IsNil)
  3657. bucketName := bucketNamePrefix + RandLowStr(6)
  3658. err = client.CreateBucket(bucketName)
  3659. c.Assert(err, IsNil)
  3660. bucket, err := client.Bucket(bucketName)
  3661. // put bucket version:enabled
  3662. var versioningConfig VersioningConfig
  3663. versioningConfig.Status = string(VersionEnabled)
  3664. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3665. c.Assert(err, IsNil)
  3666. // put object v1
  3667. objectName := objectNamePrefix + RandStr(8)
  3668. contextV1 := RandStr(100)
  3669. versionIdV1 := ""
  3670. var respHeader http.Header
  3671. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3672. c.Assert(err, IsNil)
  3673. versionIdV1 = GetVersionId(respHeader)
  3674. c.Assert(len(versionIdV1) > 0, Equals, true)
  3675. // put object v2
  3676. contextV2 := RandStr(200)
  3677. versionIdV2 := ""
  3678. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3679. c.Assert(err, IsNil)
  3680. versionIdV2 = GetVersionId(respHeader)
  3681. c.Assert(len(versionIdV2) > 0, Equals, true)
  3682. // check v1 and v2
  3683. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3684. // check default exist
  3685. exist, err := bucket.IsObjectExist(objectName)
  3686. c.Assert(err, IsNil)
  3687. c.Assert(exist, Equals, true)
  3688. // check object v1 exist
  3689. exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV1))
  3690. c.Assert(err, IsNil)
  3691. c.Assert(exist, Equals, true)
  3692. // check object v2 exist
  3693. exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV2))
  3694. c.Assert(err, IsNil)
  3695. c.Assert(exist, Equals, true)
  3696. // rm v2
  3697. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  3698. c.Assert(err, IsNil)
  3699. // check object v2 not exist
  3700. exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV2))
  3701. c.Assert(err, IsNil)
  3702. c.Assert(exist, Equals, false)
  3703. // rm default
  3704. err = bucket.DeleteObject(objectName)
  3705. c.Assert(err, IsNil)
  3706. // check default exist
  3707. exist, err = bucket.IsObjectExist(objectName)
  3708. c.Assert(err, IsNil)
  3709. c.Assert(exist, Equals, false)
  3710. // check v1 exist
  3711. exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV1))
  3712. c.Assert(err, IsNil)
  3713. c.Assert(exist, Equals, true)
  3714. ForceDeleteBucket(client, bucketName, c)
  3715. }
  3716. func (s *OssBucketSuite) TestOptionsMethod(c *C) {
  3717. // create a bucket with default proprety
  3718. client, err := New(endpoint, accessID, accessKey)
  3719. c.Assert(err, IsNil)
  3720. bucketName := bucketNamePrefix + RandLowStr(6)
  3721. err = client.CreateBucket(bucketName)
  3722. c.Assert(err, IsNil)
  3723. bucket, err := client.Bucket(bucketName)
  3724. // put bucket cors
  3725. var rule = CORSRule{
  3726. AllowedOrigin: []string{"www.aliyun.com"},
  3727. AllowedMethod: []string{"PUT", "GET", "POST"},
  3728. AllowedHeader: []string{"x-oss-meta-author"},
  3729. ExposeHeader: []string{"x-oss-meta-name"},
  3730. MaxAgeSeconds: 100,
  3731. }
  3732. // set cors
  3733. err = client.SetBucketCORS(bucketName, []CORSRule{rule})
  3734. c.Assert(err, IsNil)
  3735. // bucket options success
  3736. options := []Option{}
  3737. originOption := Origin("www.aliyun.com")
  3738. acMethodOption := ACReqMethod("PUT")
  3739. acHeadersOption := ACReqHeaders("x-oss-meta-author")
  3740. options = append(options, originOption)
  3741. options = append(options, acMethodOption)
  3742. options = append(options, acHeadersOption)
  3743. _, err = bucket.OptionsMethod("", options...)
  3744. c.Assert(err, IsNil)
  3745. // options failure
  3746. options = []Option{}
  3747. originOption = Origin("www.aliyun.com")
  3748. acMethodOption = ACReqMethod("PUT")
  3749. acHeadersOption = ACReqHeaders("x-oss-meta-author-1")
  3750. options = append(options, originOption)
  3751. options = append(options, acMethodOption)
  3752. options = append(options, acHeadersOption)
  3753. _, err = bucket.OptionsMethod("", options...)
  3754. c.Assert(err, NotNil)
  3755. // put object
  3756. objectName := objectNamePrefix + RandStr(8)
  3757. context := RandStr(100)
  3758. err = bucket.PutObject(objectName, strings.NewReader(context))
  3759. c.Assert(err, IsNil)
  3760. // object options success
  3761. options = []Option{}
  3762. originOption = Origin("www.aliyun.com")
  3763. acMethodOption = ACReqMethod("PUT")
  3764. acHeadersOption = ACReqHeaders("x-oss-meta-author")
  3765. options = append(options, originOption)
  3766. options = append(options, acMethodOption)
  3767. options = append(options, acHeadersOption)
  3768. _, err = bucket.OptionsMethod("", options...)
  3769. c.Assert(err, IsNil)
  3770. // options failure
  3771. options = []Option{}
  3772. originOption = Origin("www.aliyun.com")
  3773. acMethodOption = ACReqMethod("PUT")
  3774. acHeadersOption = ACReqHeaders("x-oss-meta-author-1")
  3775. options = append(options, originOption)
  3776. options = append(options, acMethodOption)
  3777. options = append(options, acHeadersOption)
  3778. _, err = bucket.OptionsMethod("", options...)
  3779. c.Assert(err, NotNil)
  3780. bucket.DeleteObject(objectName)
  3781. ForceDeleteBucket(client, bucketName, c)
  3782. }
  3783. func (s *OssBucketSuite) TestBucketTrafficLimitObject1(c *C) {
  3784. // create a bucket with default proprety
  3785. client, err := New(endpoint, accessID, accessKey)
  3786. c.Assert(err, IsNil)
  3787. bucketName := bucketNamePrefix + RandLowStr(6)
  3788. err = client.CreateBucket(bucketName)
  3789. c.Assert(err, IsNil)
  3790. bucket, err := client.Bucket(bucketName)
  3791. var respHeader http.Header
  3792. var qosDelayTime string
  3793. var traffic int64 = 819220 // 100KB
  3794. maxTraffic := traffic * 120 / 100
  3795. objectName := objectNamePrefix + RandStr(8)
  3796. localFile := "../sample/BingWallpaper-2015-11-07.jpg"
  3797. fd, err := os.Open(localFile)
  3798. c.Assert(err, IsNil)
  3799. defer fd.Close()
  3800. tryGetFileSize := func(f *os.File) int64 {
  3801. fInfo, _ := f.Stat()
  3802. return fInfo.Size()
  3803. }
  3804. contentLength := tryGetFileSize(fd) * 8
  3805. // put object
  3806. start := time.Now().UnixNano() / 1000 / 1000
  3807. err = bucket.PutObject(objectName, fd, TrafficLimitHeader(traffic), GetResponseHeader(&respHeader))
  3808. c.Assert(err, IsNil)
  3809. endingTime := time.Now().UnixNano() / 1000 / 1000
  3810. costT := endingTime - start
  3811. costV := contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3812. c.Assert((costV < maxTraffic), Equals, true)
  3813. qosDelayTime = GetQosDelayTime(respHeader)
  3814. c.Assert(len(qosDelayTime) > 0, Equals, true)
  3815. // putobject without TrafficLimit
  3816. //
  3817. // fd, err = os.Open(localFile)
  3818. // c.Assert(err, IsNil)
  3819. // defer fd.Close()
  3820. // start = time.Now().UnixNano() / 1000 / 1000
  3821. // err = bucket.PutObject(objectName, fd)
  3822. // c.Assert(err, IsNil)
  3823. // endingTime = time.Now().UnixNano() / 1000 / 1000
  3824. // costT = endingTime - start
  3825. // costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3826. // testLogger.Println(traffic, maxTraffic, contentLength, costT, costV)
  3827. // c.Assert((costV < maxTraffic), Equals, true)
  3828. // get object to file
  3829. newFile := "test-file-" + RandStr(10)
  3830. start = time.Now().UnixNano() / 1000 / 1000
  3831. err = bucket.GetObjectToFile(objectName, newFile, TrafficLimitHeader(traffic))
  3832. c.Assert(err, IsNil)
  3833. endingTime = time.Now().UnixNano() / 1000 / 1000
  3834. costT = endingTime - start
  3835. costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3836. c.Assert((costV < maxTraffic), Equals, true)
  3837. os.Remove(newFile)
  3838. // append object
  3839. newFile = "test-file-" + RandStr(10)
  3840. objectKey := objectNamePrefix + RandStr(8)
  3841. var nextPos int64
  3842. fd, err = os.Open(localFile)
  3843. c.Assert(err, IsNil)
  3844. defer fd.Close()
  3845. start = time.Now().UnixNano() / 1000 / 1000
  3846. nextPos, err = bucket.AppendObject(objectKey, strings.NewReader(RandStr(18)), nextPos)
  3847. c.Assert(err, IsNil)
  3848. var respAppendHeader http.Header
  3849. nextPos, err = bucket.AppendObject(objectKey, fd, nextPos, TrafficLimitHeader(traffic), GetResponseHeader(&respAppendHeader))
  3850. c.Assert(err, IsNil)
  3851. endingTime = time.Now().UnixNano() / 1000 / 1000
  3852. costT = endingTime - start
  3853. costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3854. c.Assert((costV < maxTraffic), Equals, true)
  3855. qosDelayTime = GetQosDelayTime(respAppendHeader)
  3856. c.Assert(len(qosDelayTime) > 0, Equals, true)
  3857. err = bucket.GetObjectToFile(objectKey, newFile, TrafficLimitHeader(traffic))
  3858. c.Assert(err, IsNil)
  3859. err = bucket.DeleteObject(objectKey)
  3860. c.Assert(err, IsNil)
  3861. os.Remove(newFile)
  3862. // put object with url
  3863. fd, err = os.Open(localFile)
  3864. c.Assert(err, IsNil)
  3865. defer fd.Close()
  3866. strURL, err := bucket.SignURL(objectName, HTTPPut, 60, TrafficLimitParam(traffic))
  3867. start = time.Now().UnixNano() / 1000 / 1000
  3868. err = bucket.PutObjectWithURL(strURL, fd)
  3869. c.Assert(err, IsNil)
  3870. endingTime = time.Now().UnixNano() / 1000 / 1000
  3871. costT = endingTime - start
  3872. costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3873. c.Assert((costV < maxTraffic), Equals, true)
  3874. // get object with url
  3875. newFile = "test-file-" + RandStr(10)
  3876. strURL, err = bucket.SignURL(objectName, HTTPGet, 60, TrafficLimitParam(traffic))
  3877. c.Assert(err, IsNil)
  3878. start = time.Now().UnixNano() / 1000 / 1000
  3879. err = bucket.GetObjectToFileWithURL(strURL, newFile)
  3880. c.Assert(err, IsNil)
  3881. endingTime = time.Now().UnixNano() / 1000 / 1000
  3882. costT = endingTime - start
  3883. costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3884. c.Assert((costV < maxTraffic), Equals, true)
  3885. os.Remove(newFile)
  3886. // copy object
  3887. destObjectName := objectNamePrefix + RandStr(8)
  3888. _, err = bucket.CopyObject(objectName, destObjectName, TrafficLimitHeader(traffic))
  3889. c.Assert(err, IsNil)
  3890. err = bucket.DeleteObject(destObjectName)
  3891. c.Assert(err, IsNil)
  3892. ForceDeleteBucket(client, bucketName, c)
  3893. }
  3894. func (s *OssBucketSuite) TestBucketTrafficLimitUpload(c *C) {
  3895. // create a bucket with default proprety
  3896. client, err := New(endpoint, accessID, accessKey)
  3897. c.Assert(err, IsNil)
  3898. bucketName := bucketNamePrefix + RandLowStr(6)
  3899. err = client.CreateBucket(bucketName)
  3900. c.Assert(err, IsNil)
  3901. bucket, err := client.Bucket(bucketName)
  3902. var traffic int64 = 819220 // 100KB
  3903. maxTraffic := traffic * 120 / 100
  3904. contentLength := 500 * 1024
  3905. var fileName = "test-file-" + RandStr(8)
  3906. objectName := objectNamePrefix + RandStr(8)
  3907. content := RandStr(contentLength)
  3908. CreateFile(fileName, content, c)
  3909. chunks, err := SplitFileByPartNum(fileName, 3)
  3910. c.Assert(err, IsNil)
  3911. options := []Option{
  3912. Expires(futureDate), Meta("my", "myprop"),
  3913. }
  3914. fd, err := os.Open(fileName)
  3915. c.Assert(err, IsNil)
  3916. defer fd.Close()
  3917. imur, err := bucket.InitiateMultipartUpload(objectName, options...)
  3918. c.Assert(err, IsNil)
  3919. var parts []UploadPart
  3920. start := time.Now().UnixNano() / 1000 / 1000
  3921. for _, chunk := range chunks {
  3922. fd.Seek(chunk.Offset, os.SEEK_SET)
  3923. part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number, TrafficLimitHeader(traffic))
  3924. c.Assert(err, IsNil)
  3925. parts = append(parts, part)
  3926. }
  3927. _, err = bucket.CompleteMultipartUpload(imur, parts)
  3928. c.Assert(err, IsNil)
  3929. endingTime := time.Now().UnixNano() / 1000 / 1000
  3930. costT := endingTime - start
  3931. costV := int64(contentLength) * 8 * 1000 / costT // B * 8 * 1000 / Millisecond = bit/s
  3932. c.Assert((costV < maxTraffic), Equals, true)
  3933. os.Remove(fileName)
  3934. ForceDeleteBucket(client, bucketName, c)
  3935. }
  3936. func (s *OssBucketSuite) TestPutObjectWithForbidOverWrite(c *C) {
  3937. // create a bucket with default proprety
  3938. client, err := New(endpoint, accessID, accessKey)
  3939. c.Assert(err, IsNil)
  3940. bucketName := bucketNamePrefix + RandLowStr(6)
  3941. err = client.CreateBucket(bucketName)
  3942. c.Assert(err, IsNil)
  3943. bucket, err := client.Bucket(bucketName)
  3944. contentLength := 1024
  3945. objectName := objectNamePrefix + RandStr(8)
  3946. content := RandStr(contentLength)
  3947. // first put success
  3948. err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(true))
  3949. c.Assert(err, IsNil)
  3950. // second put failure with ForbidOverWrite true
  3951. var respHeader http.Header
  3952. err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(true), GetResponseHeader(&respHeader))
  3953. c.Assert(err, NotNil)
  3954. // third put success with ForbidOverWrite false
  3955. err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(false))
  3956. c.Assert(err, IsNil)
  3957. ForceDeleteBucket(client, bucketName, c)
  3958. }
  3959. func (s *OssBucketSuite) TestCopyObjectWithForbidOverWrite(c *C) {
  3960. // create a bucket with default proprety
  3961. client, err := New(endpoint, accessID, accessKey)
  3962. c.Assert(err, IsNil)
  3963. bucketName := bucketNamePrefix + RandLowStr(6)
  3964. err = client.CreateBucket(bucketName)
  3965. c.Assert(err, IsNil)
  3966. bucket, err := client.Bucket(bucketName)
  3967. contentLength := 1024
  3968. objectName := objectNamePrefix + RandStr(8)
  3969. content := RandStr(contentLength)
  3970. err = bucket.PutObject(objectName, strings.NewReader(content))
  3971. c.Assert(err, IsNil)
  3972. // first copy success
  3973. copyObjectName := objectName + "-copy"
  3974. _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(true))
  3975. c.Assert(err, IsNil)
  3976. // second copy failure with ForbidOverWrite true
  3977. var respHeader http.Header
  3978. _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(true), GetResponseHeader(&respHeader))
  3979. c.Assert(err, NotNil)
  3980. // third copy success with ForbidOverWrite false
  3981. _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(false))
  3982. c.Assert(err, IsNil)
  3983. ForceDeleteBucket(client, bucketName, c)
  3984. }
  3985. func (s *OssBucketSuite) TestDeleteObjectsWithSpecialCharacter(c *C) {
  3986. // create a bucket with default proprety
  3987. client, err := New(endpoint, accessID, accessKey)
  3988. c.Assert(err, IsNil)
  3989. bucketName := bucketNamePrefix + RandLowStr(6)
  3990. err = client.CreateBucket(bucketName)
  3991. c.Assert(err, IsNil)
  3992. bucket, err := client.Bucket(bucketName)
  3993. contentLength := 100
  3994. objectName1 := objectNamePrefix + RandStr(8) + "<-->+&*\r%%"
  3995. objectName2 := objectNamePrefix + RandStr(8) + "\r&*\r%%"
  3996. //objectName2 := objectNamePrefix + RandStr(8) + "%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2Fetc%2Fprofile"
  3997. //objectName2, err = url.QueryUnescape(objectName2)
  3998. c.Assert(err, IsNil)
  3999. content := RandStr(contentLength)
  4000. err = bucket.PutObject(objectName1, strings.NewReader(content))
  4001. c.Assert(err, IsNil)
  4002. err = bucket.PutObject(objectName2, strings.NewReader(content))
  4003. c.Assert(err, IsNil)
  4004. // delete objectName1 objectName2
  4005. objectKeys := []string{objectName1, objectName2}
  4006. _, err = bucket.DeleteObjects(objectKeys)
  4007. c.Assert(err, IsNil)
  4008. // objectName1 is not exist
  4009. exist, err := bucket.IsObjectExist(objectName1)
  4010. c.Assert(err, IsNil)
  4011. c.Assert(exist, Equals, false)
  4012. // objectName2 is not exist
  4013. exist, err = bucket.IsObjectExist(objectName2)
  4014. c.Assert(err, IsNil)
  4015. c.Assert(exist, Equals, false)
  4016. ForceDeleteBucket(client, bucketName, c)
  4017. }
  4018. // TestGetObjectRangeBehavior
  4019. func (s *OssBucketSuite) TestGetObjectRangeBehavior(c *C) {
  4020. // create a bucket with default proprety
  4021. client, err := New(endpoint, accessID, accessKey)
  4022. c.Assert(err, IsNil)
  4023. bucketName := bucketNamePrefix + RandLowStr(6)
  4024. err = client.CreateBucket(bucketName)
  4025. c.Assert(err, IsNil)
  4026. bucket, err := client.Bucket(bucketName)
  4027. objectName := objectNamePrefix + RandStr(8)
  4028. objectLen := 1000
  4029. objectValue := RandStr(objectLen)
  4030. // Put
  4031. err = bucket.PutObject(objectName, strings.NewReader(objectValue))
  4032. c.Assert(err, IsNil)
  4033. // Range 1
  4034. options := []Option{
  4035. RangeBehavior("standard"),
  4036. Range(1000, 2000),
  4037. }
  4038. resp, err := bucket.GetObject(objectName, options...)
  4039. c.Assert(resp, IsNil)
  4040. c.Assert(err.(ServiceError).StatusCode, Equals, 416)
  4041. // Range 2
  4042. options = []Option{
  4043. RangeBehavior("standard"),
  4044. Range(0, 2000),
  4045. }
  4046. resp, err = bucket.GetObject(objectName, options...)
  4047. c.Assert(err, IsNil)
  4048. data, err := ioutil.ReadAll(resp)
  4049. resp.Close()
  4050. str := string(data)
  4051. c.Assert(len(str), Equals, 1000)
  4052. c.Assert(resp.(*Response).StatusCode, Equals, 206)
  4053. // Range 3
  4054. options = []Option{
  4055. RangeBehavior("standard"),
  4056. Range(500, 2000),
  4057. }
  4058. resp, err = bucket.GetObject(objectName, options...)
  4059. c.Assert(err, IsNil)
  4060. data, err = ioutil.ReadAll(resp)
  4061. resp.Close()
  4062. str = string(data)
  4063. c.Assert(len(str), Equals, 500)
  4064. c.Assert(resp.(*Response).StatusCode, Equals, 206)
  4065. ForceDeleteBucket(client, bucketName, c)
  4066. }
  4067. // RangeBehavior is an option to set Range value, such as "standard"
  4068. func MyRangeBehavior(value string) Option {
  4069. return SetHeader(HTTPHeaderOssRangeBehavior, value)
  4070. }
  4071. // TestUserSetHeader
  4072. func (s *OssBucketSuite) TestSupportUserSetHeader(c *C) {
  4073. // create a bucket with default proprety
  4074. client, err := New(endpoint, accessID, accessKey)
  4075. c.Assert(err, IsNil)
  4076. bucketName := bucketNamePrefix + RandLowStr(6)
  4077. err = client.CreateBucket(bucketName)
  4078. c.Assert(err, IsNil)
  4079. bucket, err := client.Bucket(bucketName)
  4080. objectName := objectNamePrefix + RandStr(8)
  4081. objectLen := 1000
  4082. objectValue := RandStr(objectLen)
  4083. // Put
  4084. err = bucket.PutObject(objectName, strings.NewReader(objectValue))
  4085. c.Assert(err, IsNil)
  4086. // Range 1
  4087. options := []Option{
  4088. MyRangeBehavior("standard"),
  4089. Range(1000, 2000),
  4090. }
  4091. resp, err := bucket.GetObject(objectName, options...)
  4092. c.Assert(resp, IsNil)
  4093. c.Assert(err.(ServiceError).StatusCode, Equals, 416)
  4094. // Range 2
  4095. options = []Option{
  4096. MyRangeBehavior("standard"),
  4097. Range(0, 2000),
  4098. }
  4099. resp, err = bucket.GetObject(objectName, options...)
  4100. c.Assert(err, IsNil)
  4101. data, err := ioutil.ReadAll(resp)
  4102. resp.Close()
  4103. str := string(data)
  4104. c.Assert(len(str), Equals, 1000)
  4105. c.Assert(resp.(*Response).StatusCode, Equals, 206)
  4106. // Range 3
  4107. options = []Option{
  4108. MyRangeBehavior("standard"),
  4109. Range(500, 2000),
  4110. }
  4111. resp, err = bucket.GetObject(objectName, options...)
  4112. c.Assert(err, IsNil)
  4113. data, err = ioutil.ReadAll(resp)
  4114. resp.Close()
  4115. str = string(data)
  4116. c.Assert(len(str), Equals, 500)
  4117. c.Assert(resp.(*Response).StatusCode, Equals, 206)
  4118. ForceDeleteBucket(client, bucketName, c)
  4119. }
  4120. // user can set param
  4121. func MyVersionId(value string) Option {
  4122. return AddParam("versionId", value)
  4123. }
  4124. func (s *OssBucketSuite) TestSupportUserSetParam(c *C) {
  4125. // create a bucket with default proprety
  4126. client, err := New(endpoint, accessID, accessKey)
  4127. c.Assert(err, IsNil)
  4128. bucketName := bucketNamePrefix + RandLowStr(6)
  4129. err = client.CreateBucket(bucketName)
  4130. c.Assert(err, IsNil)
  4131. bucket, err := client.Bucket(bucketName)
  4132. // put bucket version:enabled
  4133. var versioningConfig VersioningConfig
  4134. versioningConfig.Status = string(VersionEnabled)
  4135. err = client.SetBucketVersioning(bucketName, versioningConfig)
  4136. c.Assert(err, IsNil)
  4137. bucketResult, err := client.GetBucketInfo(bucketName)
  4138. c.Assert(err, IsNil)
  4139. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  4140. // put object v1
  4141. objectName := objectNamePrefix + RandStr(8)
  4142. contextV1 := RandStr(100)
  4143. versionIdV1 := ""
  4144. var respHeader http.Header
  4145. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  4146. c.Assert(err, IsNil)
  4147. versionIdV1 = GetVersionId(respHeader)
  4148. c.Assert(len(versionIdV1) > 0, Equals, true)
  4149. // put object v2
  4150. contextV2 := RandStr(200)
  4151. versionIdV2 := ""
  4152. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  4153. c.Assert(err, IsNil)
  4154. versionIdV2 = GetVersionId(respHeader)
  4155. c.Assert(len(versionIdV2) > 0, Equals, true)
  4156. // check v1 and v2
  4157. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  4158. // get object v1
  4159. body, err := bucket.GetObject(objectName, MyVersionId(versionIdV1))
  4160. c.Assert(err, IsNil)
  4161. str, err := readBody(body)
  4162. c.Assert(err, IsNil)
  4163. body.Close()
  4164. c.Assert(str, Equals, contextV1)
  4165. // get object v2
  4166. body, err = bucket.GetObject(objectName, MyVersionId(versionIdV2))
  4167. c.Assert(err, IsNil)
  4168. str, err = readBody(body)
  4169. c.Assert(err, IsNil)
  4170. body.Close()
  4171. c.Assert(str, Equals, contextV2)
  4172. ForceDeleteBucket(client, bucketName, c)
  4173. }
  4174. func (s *OssBucketSuite) TestPutObjectWithKmsSm4(c *C) {
  4175. // create a bucket with default proprety
  4176. client, err := New(endpoint, accessID, accessKey)
  4177. c.Assert(err, IsNil)
  4178. objectName := objectNamePrefix + RandStr(8)
  4179. objectValue := RandStr(1024)
  4180. bucketName := bucketNamePrefix + RandLowStr(6)
  4181. err = client.CreateBucket(bucketName)
  4182. c.Assert(err, IsNil)
  4183. bucket, err := client.Bucket(bucketName)
  4184. err = bucket.PutObject(objectName, strings.NewReader(objectValue), ServerSideEncryption("KMS"), ServerSideDataEncryption("SM4"))
  4185. headers, err := bucket.GetObjectDetailedMeta(objectName)
  4186. c.Assert(err, IsNil)
  4187. c.Assert(headers.Get(HTTPHeaderOssServerSideEncryption), Equals, "KMS")
  4188. c.Assert(headers.Get(HTTPHeaderOssServerSideDataEncryption), Equals, "SM4")
  4189. c.Assert(err, IsNil)
  4190. ForceDeleteBucket(client, bucketName, c)
  4191. }