bucket_test.go 138 KB

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