123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184 |
- package oss
- import (
- "bytes"
- "encoding/base64"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "math/rand"
- "net/http"
- "net/url"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "time"
- "github.com/baiyubin/aliyun-sts-go-sdk/sts"
- . "gopkg.in/check.v1"
- )
- type OssBucketSuite struct {
- client *Client
- bucket *Bucket
- archiveBucket *Bucket
- }
- var _ = Suite(&OssBucketSuite{})
- var (
- pastDate = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
- futureDate = time.Date(2049, time.January, 10, 23, 0, 0, 0, time.UTC)
- )
- // SetUpSuite runs once when the suite starts running.
- func (s *OssBucketSuite) SetUpSuite(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- s.client = client
- s.client.CreateBucket(bucketName)
- err = s.client.CreateBucket(archiveBucketName, StorageClass(StorageArchive))
- c.Assert(err, IsNil)
- bucket, err := s.client.Bucket(bucketName)
- c.Assert(err, IsNil)
- s.bucket = bucket
- archiveBucket, err := s.client.Bucket(archiveBucketName)
- c.Assert(err, IsNil)
- s.archiveBucket = archiveBucket
- testLogger.Println("test bucket started")
- }
- // TearDownSuite runs before each test or benchmark starts running.
- func (s *OssBucketSuite) TearDownSuite(c *C) {
- for _, bucket := range []*Bucket{s.bucket, s.archiveBucket} {
- // Delete multipart
- keyMarker := KeyMarker("")
- uploadIDMarker := UploadIDMarker("")
- for {
- lmu, err := bucket.ListMultipartUploads(keyMarker, uploadIDMarker)
- c.Assert(err, IsNil)
- for _, upload := range lmu.Uploads {
- imur := InitiateMultipartUploadResult{Bucket: bucketName, Key: upload.Key, UploadID: upload.UploadID}
- err = bucket.AbortMultipartUpload(imur)
- c.Assert(err, IsNil)
- }
- keyMarker = KeyMarker(lmu.NextKeyMarker)
- uploadIDMarker = UploadIDMarker(lmu.NextUploadIDMarker)
- if !lmu.IsTruncated {
- break
- }
- }
- // Delete objects
- marker := Marker("")
- for {
- lor, err := bucket.ListObjects(marker)
- c.Assert(err, IsNil)
- for _, object := range lor.Objects {
- err = bucket.DeleteObject(object.Key)
- c.Assert(err, IsNil)
- }
- marker = Marker(lor.NextMarker)
- if !lor.IsTruncated {
- break
- }
- }
- // Delete bucket
- err := s.client.DeleteBucket(bucket.BucketName)
- c.Assert(err, IsNil)
- }
- testLogger.Println("test bucket completed")
- }
- // SetUpTest runs after each test or benchmark runs.
- func (s *OssBucketSuite) SetUpTest(c *C) {
- err := removeTempFiles("../oss", ".jpg")
- c.Assert(err, IsNil)
- }
- // TearDownTest runs once after all tests or benchmarks have finished running.
- func (s *OssBucketSuite) TearDownTest(c *C) {
- err := removeTempFiles("../oss", ".jpg")
- c.Assert(err, IsNil)
- err = removeTempFiles("../oss", ".txt")
- c.Assert(err, IsNil)
- err = removeTempFiles("../oss", ".temp")
- c.Assert(err, IsNil)
- err = removeTempFiles("../oss", ".txt1")
- c.Assert(err, IsNil)
- err = removeTempFiles("../oss", ".txt2")
- c.Assert(err, IsNil)
- }
- // TestPutObject
- func (s *OssBucketSuite) TestPutObjectOnly(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "大江东去,浪淘尽,千古风流人物。 故垒西边,人道是、三国周郎赤壁。 乱石穿空,惊涛拍岸,卷起千堆雪。 江山如画,一时多少豪杰。" +
- "遥想公谨当年,小乔初嫁了,雄姿英发。 羽扇纶巾,谈笑间、樯橹灰飞烟灭。故国神游,多情应笑我,早生华发,人生如梦,一尊还酹江月。"
- // Put string
- var respHeader http.Header
- err := s.bucket.PutObject(objectName, strings.NewReader(objectValue), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- // Check
- body, err := s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- acl, err := s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("aclRes:", acl)
- c.Assert(acl.ACL, Equals, "default")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Put bytes
- err = s.bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Put file
- err = CreateFileAndWrite(objectName+".txt", []byte(objectValue))
- c.Assert(err, IsNil)
- fd, err := os.Open(objectName + ".txt")
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName, fd)
- c.Assert(err, IsNil)
- os.Remove(objectName + ".txt")
- // Check
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Put with properties
- objectName = objectNamePrefix + RandStr(8)
- options := []Option{
- Expires(futureDate),
- ObjectACL(ACLPublicRead),
- Meta("myprop", "mypropval"),
- }
- err = s.bucket.PutObject(objectName, strings.NewReader(objectValue), options...)
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- acl, err = s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectACL:", acl)
- c.Assert(acl.ACL, Equals, string(ACLPublicRead))
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectDetailedMeta:", meta)
- c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- func (s *OssBucketSuite) SignURLTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := RandStr(20)
- filePath := RandLowStr(10)
- content := "复写object"
- CreateFile(filePath, content, c)
- notExistfilePath := RandLowStr(10)
- os.Remove(notExistfilePath)
- oldType := s.bucket.Client.Config.AuthVersion
- oldHeaders := s.bucket.Client.Config.AdditionalHeaders
- s.bucket.Client.Config.AuthVersion = authVersion
- s.bucket.Client.Config.AdditionalHeaders = extraHeaders
- // Sign URL for put
- str, err := s.bucket.SignURL(objectName, HTTPPut, 60)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Error put object with URL
- err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue), ContentType("image/tiff"))
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
- err = s.bucket.PutObjectFromFileWithURL(str, filePath, ContentType("image/tiff"))
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
- // Put object with URL
- err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- acl, err := s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, "default")
- // Get object meta
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get(HTTPHeaderContentType), Equals, "application/octet-stream")
- c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "")
- // Sign URL for function GetObjectWithURL
- str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Get object with URL
- body, err := s.bucket.GetObjectWithURL(str)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Sign URL for function PutObjectWithURL
- options := []Option{
- ObjectACL(ACLPublicRead),
- Meta("myprop", "mypropval"),
- ContentType("image/tiff"),
- ResponseContentEncoding("deflate"),
- }
- str, err = s.bucket.SignURL(objectName, HTTPPut, 60, options...)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Put object with URL from file
- // Without option, error
- err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
- err = s.bucket.PutObjectFromFileWithURL(str, filePath)
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
- // With option, error file
- err = s.bucket.PutObjectFromFileWithURL(str, notExistfilePath, options...)
- c.Assert(err, NotNil)
- // With option
- err = s.bucket.PutObjectFromFileWithURL(str, filePath, options...)
- c.Assert(err, IsNil)
- // Get object meta
- meta, err = s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
- c.Assert(meta.Get(HTTPHeaderContentType), Equals, "image/tiff")
- acl, err = s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, string(ACLPublicRead))
- // Sign URL for function GetObjectToFileWithURL
- str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
- c.Assert(err, IsNil)
- // Get object to file with URL
- newFile := RandStr(10)
- err = s.bucket.GetObjectToFileWithURL(str, newFile)
- c.Assert(err, IsNil)
- eq, err := compareFiles(filePath, newFile)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- os.Remove(newFile)
- // Get object to file error
- err = s.bucket.GetObjectToFileWithURL(str, newFile, options...)
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
- _, err = os.Stat(newFile)
- c.Assert(err, NotNil)
- // Get object error
- body, err = s.bucket.GetObjectWithURL(str, options...)
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
- c.Assert(body, IsNil)
- // Sign URL for function GetObjectToFileWithURL
- options = []Option{
- Expires(futureDate),
- ObjectACL(ACLPublicRead),
- Meta("myprop", "mypropval"),
- ContentType("image/tiff"),
- ResponseContentEncoding("deflate"),
- }
- str, err = s.bucket.SignURL(objectName, HTTPGet, 60, options...)
- c.Assert(err, IsNil)
- // Get object to file with URL and options
- err = s.bucket.GetObjectToFileWithURL(str, newFile, options...)
- c.Assert(err, IsNil)
- eq, err = compareFiles(filePath, newFile)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- os.Remove(newFile)
- // Get object to file error
- err = s.bucket.GetObjectToFileWithURL(str, newFile)
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
- _, err = os.Stat(newFile)
- c.Assert(err, NotNil)
- // Get object error
- body, err = s.bucket.GetObjectWithURL(str)
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
- c.Assert(body, IsNil)
- err = s.bucket.PutObjectFromFile(objectName, "../sample/The Go Programming Language.html")
- c.Assert(err, IsNil)
- str, err = s.bucket.SignURL(objectName, HTTPGet, 3600, AcceptEncoding("gzip"))
- c.Assert(err, IsNil)
- s.bucket.GetObjectToFileWithURL(str, newFile)
- c.Assert(err, IsNil)
- os.Remove(filePath)
- os.Remove(newFile)
- // Sign URL error
- str, err = s.bucket.SignURL(objectName, HTTPGet, -1)
- c.Assert(err, NotNil)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Invalid URL parse
- str = RandStr(20)
- err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, NotNil)
- err = s.bucket.GetObjectToFileWithURL(str, newFile)
- c.Assert(err, NotNil)
- s.bucket.Client.Config.AuthVersion = oldType
- s.bucket.Client.Config.AdditionalHeaders = oldHeaders
- }
- func (s *OssBucketSuite) TestSignURL(c *C) {
- s.SignURLTestFunc(c, AuthV1, []string{})
- s.SignURLTestFunc(c, AuthV2, []string{})
- s.SignURLTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
- }
- func (s *OssBucketSuite) SignURLWithEscapedKeyTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
- // Key with '/'
- objectName := "zyimg/86/e8/653b5dc97bb0022051a84c632bc4"
- objectValue := "弃我去者,昨日之日不可留;乱我心者,今日之日多烦忧。长风万里送秋雁,对此可以酣高楼。蓬莱文章建安骨,中间小谢又清发。" +
- "俱怀逸兴壮思飞,欲上青天揽明月。抽刀断水水更流,举杯销愁愁更愁。人生在世不称意,明朝散发弄扁舟。"
- oldType := s.bucket.Client.Config.AuthVersion
- oldHeaders := s.bucket.Client.Config.AdditionalHeaders
- s.bucket.Client.Config.AuthVersion = authVersion
- s.bucket.Client.Config.AdditionalHeaders = extraHeaders
- // Sign URL for function PutObjectWithURL
- str, err := s.bucket.SignURL(objectName, HTTPPut, 60)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Put object with URL
- err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Sign URL for function GetObjectWithURL
- str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Get object with URL
- body, err := s.bucket.GetObjectWithURL(str)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Key with escaped chars
- objectName = "<>[]()`?.,!@#$%^&'/*-_=+~:;"
- // Sign URL for funciton PutObjectWithURL
- str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Put object with URL
- err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Sign URL for function GetObjectWithURL
- str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Get object with URL
- body, err = s.bucket.GetObjectWithURL(str)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Key with Chinese chars
- objectName = "风吹柳花满店香,吴姬压酒劝客尝。金陵子弟来相送,欲行不行各尽觞。请君试问东流水,别意与之谁短长。"
- // Sign URL for function PutObjectWithURL
- str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Put object with URL
- err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Sign URL for get function GetObjectWithURL
- str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
- c.Assert(err, IsNil)
- if s.bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Get object with URL
- body, err = s.bucket.GetObjectWithURL(str)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Key
- objectName = "test/此情无计可消除/才下眉头/却上 心头/。,;:‘’“”?()『』【】《》!@#¥%……&×/test+ =-_*&^%$#@!`~[]{}()<>|\\/?.,;.txt"
- // Sign URL for function PutObjectWithURL
- str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
- c.Assert(err, IsNil)
- // Put object with URL
- err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Sign URL for function GetObjectWithURL
- str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
- c.Assert(err, IsNil)
- // Get object with URL
- body, err = s.bucket.GetObjectWithURL(str)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Put object
- err = s.bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
- c.Assert(err, IsNil)
- // Get object
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Delete object
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- s.bucket.Client.Config.AuthVersion = oldType
- s.bucket.Client.Config.AdditionalHeaders = oldHeaders
- }
- func (s *OssBucketSuite) TestSignURLWithEscapedKey(c *C) {
- s.SignURLWithEscapedKeyTestFunc(c, AuthV1, []string{})
- s.SignURLWithEscapedKeyTestFunc(c, AuthV2, []string{})
- s.SignURLWithEscapedKeyTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
- }
- func (s *OssBucketSuite) SignURLWithEscapedKeyAndPorxyTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
- // Key with '/'
- objectName := "zyimg/86/e8/653b5dc97bb0022051a84c632bc4"
- objectValue := "弃我去者,昨日之日不可留;乱我心者,今日之日多烦忧。长风万里送秋雁,对此可以酣高楼。蓬莱文章建安骨,中间小谢又清发。" +
- "俱怀逸兴壮思飞,欲上青天揽明月。抽刀断水水更流,举杯销愁愁更愁。人生在世不称意,明朝散发弄扁舟。"
- options := []ClientOption{
- AuthProxy(proxyHost, proxyUser, proxyPasswd),
- AuthVersion(authVersion),
- AdditionalHeaders(extraHeaders),
- }
- client, err := New(endpoint, accessID, accessKey, options...)
- bucket, err := client.Bucket(bucketName)
- // Sign URL for put
- str, err := bucket.SignURL(objectName, HTTPPut, 60)
- c.Assert(err, IsNil)
- if bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Put object with URL
- err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Sign URL for function GetObjectWithURL
- str, err = bucket.SignURL(objectName, HTTPGet, 60)
- c.Assert(err, IsNil)
- if bucket.Client.Config.AuthVersion == AuthV1 {
- c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
- } else {
- c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
- c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
- }
- // Get object with URL
- body, err := bucket.GetObjectWithURL(str)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Key with Chinese chars
- objectName = "test/此情无计可消除/才下眉头/却上 心头/。,;:‘’“”?()『』【】《》!@#¥%……&×/test+ =-_*&^%$#@!`~[]{}()<>|\\/?.,;.txt"
- // Sign URL for function PutObjectWithURL
- str, err = bucket.SignURL(objectName, HTTPPut, 60)
- c.Assert(err, IsNil)
- // Put object with URL
- err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Sign URL for function GetObjectWithURL
- str, err = bucket.SignURL(objectName, HTTPGet, 60)
- c.Assert(err, IsNil)
- // Get object with URL
- body, err = bucket.GetObjectWithURL(str)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Put object
- err = bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
- c.Assert(err, IsNil)
- // Get object
- body, err = bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Delete object
- err = bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- func (s *OssBucketSuite) TestSignURLWithEscapedKeyAndPorxy(c *C) {
- s.SignURLWithEscapedKeyAndPorxyTestFunc(c, AuthV1, []string{})
- s.SignURLWithEscapedKeyAndPorxyTestFunc(c, AuthV2, []string{})
- s.SignURLWithEscapedKeyAndPorxyTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
- }
- func (s *OssBucketSuite) TestQueryStringAuthV2(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // set oss v2 signatrue
- client.Config.AuthVersion = AuthV2
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // build QueryString
- QueryKey1 := "abc"
- QueryKey2 := "|abc"
- c.Assert(strings.Compare(QueryKey1, QueryKey2) < 0, Equals, true)
- c.Assert(strings.Compare(url.QueryEscape(QueryKey1), url.QueryEscape(QueryKey2)) > 0, Equals, true)
- options := []Option{}
- params := map[string]interface{}{}
- params[QueryKey1] = "queryValue1"
- params[QueryKey2] = "queryValue2"
- objectKey := objectNamePrefix + RandStr(8)
- resp, _ := bucket.do("HEAD", objectKey, params, options, nil, nil)
- // object not exist,no signature error
- c.Assert(resp.StatusCode, Equals, 404)
- ForceDeleteBucket(client, bucketName, c)
- }
- // TestPutObjectType
- func (s *OssBucketSuite) TestPutObjectType(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "乱石穿空,惊涛拍岸,卷起千堆雪。 江山如画,一时多少豪杰。"
- // Put
- err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Check
- body, err := s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get("Content-Type"), Equals, "application/octet-stream")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Put
- err = s.bucket.PutObject(objectName+".txt", strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- meta, err = s.bucket.GetObjectDetailedMeta(objectName + ".txt")
- c.Assert(err, IsNil)
- c.Assert(strings.Contains(meta.Get("Content-Type"), "text/plain"), Equals, true)
- err = s.bucket.DeleteObject(objectName + ".txt")
- c.Assert(err, IsNil)
- // Put
- err = s.bucket.PutObject(objectName+".apk", strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- meta, err = s.bucket.GetObjectDetailedMeta(objectName + ".apk")
- c.Assert(err, IsNil)
- c.Assert(meta.Get("Content-Type"), Equals, "application/vnd.android.package-archive")
- err = s.bucket.DeleteObject(objectName + ".txt")
- c.Assert(err, IsNil)
- }
- // TestPutObject
- func (s *OssBucketSuite) TestPutObjectKeyChars(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "白日依山尽,黄河入海流。欲穷千里目,更上一层楼。"
- // Put
- objectKey := objectName + "十步杀一人,千里不留行。事了拂衣去,深藏身与名"
- err := s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Check
- body, err := s.bucket.GetObject(objectKey)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectKey)
- c.Assert(err, IsNil)
- // Put
- objectKey = objectName + "ごきげん如何ですかおれの顔をよく拝んでおけ"
- err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectKey)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectKey)
- c.Assert(err, IsNil)
- // Put
- objectKey = objectName + "~!@#$%^&*()_-+=|\\[]{}<>,./?"
- err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectKey)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectKey)
- c.Assert(err, IsNil)
- // Put
- objectKey = "go/中国 日本 +-#&=*"
- err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectKey)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectKey)
- c.Assert(err, IsNil)
- }
- // TestPutObjectNegative
- func (s *OssBucketSuite) TestPutObjectNegative(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "大江东去,浪淘尽,千古风流人物。 "
- // Put
- objectName = objectNamePrefix + RandStr(8)
- err := s.bucket.PutObject(objectName, strings.NewReader(objectValue),
- Meta("meta-my", "myprop"))
- c.Assert(err, IsNil)
- // Check meta
- body, err := s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get("X-Oss-Meta-My"), Not(Equals), "myprop")
- c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Invalid option
- err = s.bucket.PutObject(objectName, strings.NewReader(objectValue),
- IfModifiedSince(pastDate))
- c.Assert(err, NotNil)
- err = s.bucket.PutObjectFromFile(objectName, "bucket.go", IfModifiedSince(pastDate))
- c.Assert(err, NotNil)
- err = s.bucket.PutObjectFromFile(objectName, "/tmp/xxx")
- c.Assert(err, NotNil)
- }
- // TestPutObjectFromFile
- func (s *OssBucketSuite) TestPutObjectFromFile(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- localFile := "../sample/BingWallpaper-2015-11-07.jpg"
- newFile := "newpic11.jpg"
- // Put
- err := s.bucket.PutObjectFromFile(objectName, localFile)
- c.Assert(err, IsNil)
- // Check
- err = s.bucket.GetObjectToFile(objectName, newFile)
- c.Assert(err, IsNil)
- eq, err := compareFiles(localFile, newFile)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- acl, err := s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("aclRes:", acl)
- c.Assert(acl.ACL, Equals, "default")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Put with properties
- options := []Option{
- Expires(futureDate),
- ObjectACL(ACLPublicRead),
- Meta("myprop", "mypropval"),
- }
- os.Remove(newFile)
- err = s.bucket.PutObjectFromFile(objectName, localFile, options...)
- c.Assert(err, IsNil)
- // Check
- err = s.bucket.GetObjectToFile(objectName, newFile)
- c.Assert(err, IsNil)
- eq, err = compareFiles(localFile, newFile)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- acl, err = s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectACL:", acl)
- c.Assert(acl.ACL, Equals, string(ACLPublicRead))
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectDetailedMeta:", meta)
- c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- os.Remove(newFile)
- }
- // TestPutObjectFromFile
- func (s *OssBucketSuite) TestPutObjectFromFileType(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- localFile := "../sample/BingWallpaper-2015-11-07.jpg"
- newFile := RandStr(8) + ".jpg"
- // Put
- err := s.bucket.PutObjectFromFile(objectName, localFile)
- c.Assert(err, IsNil)
- // Check
- err = s.bucket.GetObjectToFile(objectName, newFile)
- c.Assert(err, IsNil)
- eq, err := compareFiles(localFile, newFile)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get("Content-Type"), Equals, "image/jpeg")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- os.Remove(newFile)
- }
- // TestGetObject
- func (s *OssBucketSuite) TestGetObjectNormal(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "长忆观潮,满郭人争江上望。来疑沧海尽成空,万面鼓声中。弄潮儿向涛头立,手把红旗旗不湿。别来几向梦中看,梦觉尚心寒。"
- // Put
- err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Check
- body, err := s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- data, err := ioutil.ReadAll(body)
- body.Close()
- str := string(data)
- c.Assert(str, Equals, objectValue)
- testLogger.Println("GetObjec:", str)
- // Range
- var subObjectValue = string(([]byte(objectValue))[15:36])
- body, err = s.bucket.GetObject(objectName, Range(15, 35))
- c.Assert(err, IsNil)
- data, err = ioutil.ReadAll(body)
- body.Close()
- str = string(data)
- c.Assert(str, Equals, subObjectValue)
- testLogger.Println("GetObject:", str, ",", subObjectValue)
- // If-Modified-Since
- _, err = s.bucket.GetObject(objectName, IfModifiedSince(futureDate))
- c.Assert(err, NotNil)
- // If-Unmodified-Since
- body, err = s.bucket.GetObject(objectName, IfUnmodifiedSince(futureDate))
- c.Assert(err, IsNil)
- data, err = ioutil.ReadAll(body)
- body.Close()
- c.Assert(string(data), Equals, objectValue)
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- // If-Match
- body, err = s.bucket.GetObject(objectName, IfMatch(meta.Get("Etag")))
- c.Assert(err, IsNil)
- data, err = ioutil.ReadAll(body)
- body.Close()
- c.Assert(string(data), Equals, objectValue)
- // If-None-Match
- _, err = s.bucket.GetObject(objectName, IfNoneMatch(meta.Get("Etag")))
- c.Assert(err, NotNil)
- // process
- err = s.bucket.PutObjectFromFile(objectName, "../sample/BingWallpaper-2015-11-07.jpg")
- c.Assert(err, IsNil)
- _, err = s.bucket.GetObject(objectName, Process("image/format,png"))
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- // TestGetObjectNegative
- func (s *OssBucketSuite) TestGetObjectToWriterNegative(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "长忆观潮,满郭人争江上望。"
- // Object not exist
- _, err := s.bucket.GetObject("NotExist")
- c.Assert(err, NotNil)
- // Constraint invalid
- err = s.bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Out of range
- _, err = s.bucket.GetObject(objectName, Range(15, 1000))
- c.Assert(err, IsNil)
- // Not exist
- err = s.bucket.GetObjectToFile(objectName, "/root1/123abc9874")
- c.Assert(err, NotNil)
- // Invalid option
- _, err = s.bucket.GetObject(objectName, ACL(ACLPublicRead))
- c.Assert(err, IsNil)
- err = s.bucket.GetObjectToFile(objectName, "newpic15.jpg", ACL(ACLPublicRead))
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- // TestGetObjectToFile
- func (s *OssBucketSuite) TestGetObjectToFile(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "江南好,风景旧曾谙;日出江花红胜火,春来江水绿如蓝。能不忆江南?江南忆,最忆是杭州;山寺月中寻桂子,郡亭枕上看潮头。何日更重游!"
- newFile := RandStr(8) + ".jpg"
- // Put
- var val = []byte(objectValue)
- err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Check
- err = s.bucket.GetObjectToFile(objectName, newFile)
- c.Assert(err, IsNil)
- eq, err := compareFileData(newFile, val)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- os.Remove(newFile)
- // Range
- err = s.bucket.GetObjectToFile(objectName, newFile, Range(15, 35))
- c.Assert(err, IsNil)
- eq, err = compareFileData(newFile, val[15:36])
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- os.Remove(newFile)
- err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("15-35"))
- c.Assert(err, IsNil)
- eq, err = compareFileData(newFile, val[15:36])
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- os.Remove(newFile)
- err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("15-"))
- c.Assert(err, IsNil)
- eq, err = compareFileData(newFile, val[15:])
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- os.Remove(newFile)
- err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("-10"))
- c.Assert(err, IsNil)
- eq, err = compareFileData(newFile, val[(len(val)-10):len(val)])
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- os.Remove(newFile)
- // If-Modified-Since
- err = s.bucket.GetObjectToFile(objectName, newFile, IfModifiedSince(futureDate))
- c.Assert(err, NotNil)
- // If-Unmodified-Since
- err = s.bucket.GetObjectToFile(objectName, newFile, IfUnmodifiedSince(futureDate))
- c.Assert(err, IsNil)
- eq, err = compareFileData(newFile, val)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- os.Remove(newFile)
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectDetailedMeta:", meta)
- // If-Match
- err = s.bucket.GetObjectToFile(objectName, newFile, IfMatch(meta.Get("Etag")))
- c.Assert(err, IsNil)
- eq, err = compareFileData(newFile, val)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- // If-None-Match
- err = s.bucket.GetObjectToFile(objectName, newFile, IfNoneMatch(meta.Get("Etag")))
- c.Assert(err, NotNil)
- // Accept-Encoding:gzip
- err = s.bucket.PutObjectFromFile(objectName, "../sample/The Go Programming Language.html")
- c.Assert(err, IsNil)
- err = s.bucket.GetObjectToFile(objectName, newFile, AcceptEncoding("gzip"))
- c.Assert(err, IsNil)
- os.Remove(newFile)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- // TestListObjects
- func (s *OssBucketSuite) TestListObjects(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- // List empty bucket
- lor, err := s.bucket.ListObjects()
- c.Assert(err, IsNil)
- left := len(lor.Objects)
- // Put three objects
- err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName+"3", strings.NewReader(""))
- c.Assert(err, IsNil)
- // List
- lor, err = s.bucket.ListObjects()
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, left+3)
- // List with prefix
- lor, err = s.bucket.ListObjects(Prefix(objectName + "2"))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 1)
- lor, err = s.bucket.ListObjects(Prefix(objectName + "22"))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 0)
- // List with max keys
- lor, err = s.bucket.ListObjects(Prefix(objectName), MaxKeys(2))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 2)
- // List with marker
- lor, err = s.bucket.ListObjects(Marker(objectName+"1"), MaxKeys(1))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 1)
- err = s.bucket.DeleteObject(objectName + "1")
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(objectName + "2")
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(objectName + "3")
- c.Assert(err, IsNil)
- }
- // TestListObjects
- func (s *OssBucketSuite) TestListObjectsEncodingType(c *C) {
- prefix := objectNamePrefix + "床前明月光,疑是地上霜。举头望明月,低头思故乡。"
- for i := 0; i < 10; i++ {
- err := s.bucket.PutObject(prefix+strconv.Itoa(i), strings.NewReader(""))
- c.Assert(err, IsNil)
- }
- lor, err := s.bucket.ListObjects(Prefix(objectNamePrefix + "床前明月光,"))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 10)
- lor, err = s.bucket.ListObjects(Marker(objectNamePrefix + "床前明月光,疑是地上霜。举头望明月,低头思故乡。"))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 10)
- lor, err = s.bucket.ListObjects(Prefix(objectNamePrefix + "床前明月光"))
- c.Assert(err, IsNil)
- for i, obj := range lor.Objects {
- c.Assert(obj.Key, Equals, prefix+strconv.Itoa(i))
- }
- for i := 0; i < 10; i++ {
- err = s.bucket.DeleteObject(prefix + strconv.Itoa(i))
- c.Assert(err, IsNil)
- }
- // Special characters
- objectName := objectNamePrefix + "` ~ ! @ # $ % ^ & * () - _ + =[] {} \\ | < > , . ? / 0"
- err = s.bucket.PutObject(objectName, strings.NewReader("明月几时有,把酒问青天"))
- c.Assert(err, IsNil)
- lor, err = s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 1)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- objectName = objectNamePrefix + "中国 日本 +-#&=*"
- err = s.bucket.PutObject(objectName, strings.NewReader("明月几时有,把酒问青天"))
- c.Assert(err, IsNil)
- lor, err = s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 1)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- // TestIsBucketExist
- func (s *OssBucketSuite) TestIsObjectExist(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- // Put three objects
- err := s.bucket.PutObject(objectName+"1", strings.NewReader(""))
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName+"11", strings.NewReader(""))
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName+"111", strings.NewReader(""))
- c.Assert(err, IsNil)
- // Exist
- exist, err := s.bucket.IsObjectExist(objectName + "11")
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- exist, err = s.bucket.IsObjectExist(objectName + "1")
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- exist, err = s.bucket.IsObjectExist(objectName + "111")
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- // Not exist
- exist, err = s.bucket.IsObjectExist(objectName + "1111")
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, false)
- exist, err = s.bucket.IsObjectExist(objectName)
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, false)
- err = s.bucket.DeleteObject(objectName + "1")
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(objectName + "11")
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(objectName + "111")
- c.Assert(err, IsNil)
- }
- // TestDeleteObject
- func (s *OssBucketSuite) TestDeleteObject(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- err := s.bucket.PutObject(objectName, strings.NewReader(""))
- c.Assert(err, IsNil)
- lor, err := s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 1)
- // Delete
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Duplicate delete
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- lor, err = s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 0)
- }
- // TestDeleteObjects
- func (s *OssBucketSuite) TestDeleteObjectsNormal(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- // Delete objects
- err := s.bucket.PutObject(objectName, strings.NewReader(""))
- c.Assert(err, IsNil)
- res, err := s.bucket.DeleteObjects([]string{objectName})
- c.Assert(err, IsNil)
- c.Assert(len(res.DeletedObjects), Equals, 1)
- lor, err := s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 0)
- // Delete objects
- err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
- c.Assert(err, IsNil)
- res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"})
- c.Assert(err, IsNil)
- c.Assert(len(res.DeletedObjects), Equals, 2)
- lor, err = s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 0)
- // Delete 0
- _, err = s.bucket.DeleteObjects([]string{})
- c.Assert(err, NotNil)
- // DeleteObjectsQuiet
- err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
- c.Assert(err, IsNil)
- res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"},
- DeleteObjectsQuiet(false))
- c.Assert(err, IsNil)
- c.Assert(len(res.DeletedObjects), Equals, 2)
- lor, err = s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 0)
- // DeleteObjectsQuiet
- err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
- c.Assert(err, IsNil)
- res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"},
- DeleteObjectsQuiet(true))
- c.Assert(err, IsNil)
- c.Assert(len(res.DeletedObjects), Equals, 0)
- lor, err = s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, 0)
- // EncodingType
- err = s.bucket.PutObject("中国人", strings.NewReader(""))
- c.Assert(err, IsNil)
- res, err = s.bucket.DeleteObjects([]string{"中国人"})
- c.Assert(err, IsNil)
- c.Assert(len(res.DeletedObjects), Equals, 1)
- c.Assert(res.DeletedObjects[0], Equals, "中国人")
- // EncodingType
- err = s.bucket.PutObject("中国人", strings.NewReader(""))
- c.Assert(err, IsNil)
- res, err = s.bucket.DeleteObjects([]string{"中国人"}, DeleteObjectsQuiet(false))
- c.Assert(err, IsNil)
- c.Assert(len(res.DeletedObjects), Equals, 1)
- c.Assert(res.DeletedObjects[0], Equals, "中国人")
- // EncodingType
- err = s.bucket.PutObject("中国人", strings.NewReader(""))
- c.Assert(err, IsNil)
- res, err = s.bucket.DeleteObjects([]string{"中国人"}, DeleteObjectsQuiet(true))
- c.Assert(err, IsNil)
- c.Assert(len(res.DeletedObjects), Equals, 0)
- // Special characters
- key := "A ' < > \" & ~ ` ! @ # $ % ^ & * ( ) [] {} - _ + = / | \\ ? . , : ; A"
- err = s.bucket.PutObject(key, strings.NewReader("value"))
- c.Assert(err, IsNil)
- _, err = s.bucket.DeleteObjects([]string{key})
- c.Assert(err, IsNil)
- ress, err := s.bucket.ListObjects(Prefix(key))
- c.Assert(err, IsNil)
- c.Assert(len(ress.Objects), Equals, 0)
- // Not exist
- _, err = s.bucket.DeleteObjects([]string{"NotExistObject"})
- c.Assert(err, IsNil)
- }
- // TestSetObjectMeta
- func (s *OssBucketSuite) TestSetObjectMeta(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- err := s.bucket.PutObject(objectName, strings.NewReader(""))
- c.Assert(err, IsNil)
- err = s.bucket.SetObjectMeta(objectName,
- Expires(futureDate),
- Meta("myprop", "mypropval"))
- c.Assert(err, IsNil)
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("Meta:", meta)
- c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
- c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
- acl, err := s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, "default")
- // Invalid option
- err = s.bucket.SetObjectMeta(objectName, AcceptEncoding("url"))
- c.Assert(err, IsNil)
- // Invalid option value
- err = s.bucket.SetObjectMeta(objectName, ServerSideEncryption("invalid"))
- c.Assert(err, NotNil)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Not exist
- err = s.bucket.SetObjectMeta(objectName, Expires(futureDate))
- c.Assert(err, NotNil)
- }
- // TestGetObjectMeta
- func (s *OssBucketSuite) TestGetObjectMeta(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- // Put
- err := s.bucket.PutObject(objectName, strings.NewReader(""))
- c.Assert(err, IsNil)
- meta, err := s.bucket.GetObjectMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(len(meta) > 0, Equals, true)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- _, err = s.bucket.GetObjectMeta("NotExistObject")
- c.Assert(err, NotNil)
- }
- // TestGetObjectDetailedMeta
- func (s *OssBucketSuite) TestGetObjectDetailedMeta(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- // Put
- err := s.bucket.PutObject(objectName, strings.NewReader(""),
- Expires(futureDate), Meta("myprop", "mypropval"))
- c.Assert(err, IsNil)
- // Check
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectDetailedMeta:", meta)
- c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
- c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
- c.Assert(meta.Get("Content-Length"), Equals, "0")
- c.Assert(len(meta.Get("Date")) > 0, Equals, true)
- c.Assert(len(meta.Get("X-Oss-Request-Id")) > 0, Equals, true)
- c.Assert(len(meta.Get("Last-Modified")) > 0, Equals, true)
- // IfModifiedSince/IfModifiedSince
- _, err = s.bucket.GetObjectDetailedMeta(objectName, IfModifiedSince(futureDate))
- c.Assert(err, NotNil)
- meta, err = s.bucket.GetObjectDetailedMeta(objectName, IfUnmodifiedSince(futureDate))
- c.Assert(err, IsNil)
- c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
- c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
- // IfMatch/IfNoneMatch
- _, err = s.bucket.GetObjectDetailedMeta(objectName, IfNoneMatch(meta.Get("Etag")))
- c.Assert(err, NotNil)
- meta, err = s.bucket.GetObjectDetailedMeta(objectName, IfMatch(meta.Get("Etag")))
- c.Assert(err, IsNil)
- c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
- c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- _, err = s.bucket.GetObjectDetailedMeta("NotExistObject")
- c.Assert(err, NotNil)
- }
- // TestSetAndGetObjectAcl
- func (s *OssBucketSuite) TestSetAndGetObjectAcl(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- err := s.bucket.PutObject(objectName, strings.NewReader(""))
- c.Assert(err, IsNil)
- // Default
- acl, err := s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, "default")
- // Set ACL_PUBLIC_RW
- err = s.bucket.SetObjectACL(objectName, ACLPublicReadWrite)
- c.Assert(err, IsNil)
- acl, err = s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
- // Set ACL_PRIVATE
- err = s.bucket.SetObjectACL(objectName, ACLPrivate)
- c.Assert(err, IsNil)
- acl, err = s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, string(ACLPrivate))
- // Set ACL_PUBLIC_R
- err = s.bucket.SetObjectACL(objectName, ACLPublicRead)
- c.Assert(err, IsNil)
- acl, err = s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, string(ACLPublicRead))
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- // TestSetAndGetObjectAclNegative
- func (s *OssBucketSuite) TestSetAndGetObjectAclNegative(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- // Object not exist
- err := s.bucket.SetObjectACL(objectName, ACLPublicRead)
- c.Assert(err, NotNil)
- }
- // TestCopyObject
- func (s *OssBucketSuite) TestCopyObject(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "男儿何不带吴钩,收取关山五十州。请君暂上凌烟阁,若个书生万户侯?"
- err := s.bucket.PutObject(objectName, strings.NewReader(objectValue),
- ACL(ACLPublicRead), Meta("my", "myprop"))
- c.Assert(err, IsNil)
- // Copy
- var objectNameDest = objectName + "dest"
- _, err = s.bucket.CopyObject(objectName, objectNameDest)
- c.Assert(err, IsNil)
- // Check
- lor, err := s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- testLogger.Println("objects:", lor.Objects)
- c.Assert(len(lor.Objects), Equals, 2)
- body, err := s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectNameDest)
- c.Assert(err, IsNil)
- // Copy with constraints x-oss-copy-source-if-modified-since
- _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfModifiedSince(futureDate))
- c.Assert(err, NotNil)
- testLogger.Println("CopyObject:", err)
- // Copy with constraints x-oss-copy-source-if-unmodified-since
- _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfUnmodifiedSince(futureDate))
- c.Assert(err, IsNil)
- // Check
- lor, err = s.bucket.ListObjects(Prefix(objectName))
- c.Assert(err, IsNil)
- testLogger.Println("objects:", lor.Objects)
- c.Assert(len(lor.Objects), Equals, 2)
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectNameDest)
- c.Assert(err, IsNil)
- // Copy with constraints x-oss-copy-source-if-match
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectDetailedMeta:", meta)
- _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfMatch(meta.Get("Etag")))
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectNameDest)
- c.Assert(err, IsNil)
- // Copy with constraints x-oss-copy-source-if-none-match
- _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfNoneMatch(meta.Get("Etag")))
- c.Assert(err, NotNil)
- // Copy with constraints x-oss-metadata-directive
- _, err = s.bucket.CopyObject(objectName, objectNameDest, Meta("my", "mydestprop"),
- MetadataDirective(MetaCopy))
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- destMeta, err := s.bucket.GetObjectDetailedMeta(objectNameDest)
- c.Assert(err, IsNil)
- c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
- acl, err := s.bucket.GetObjectACL(objectNameDest)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, "default")
- err = s.bucket.DeleteObject(objectNameDest)
- c.Assert(err, IsNil)
- // Copy with constraints x-oss-metadata-directive and self defined dest object meta
- options := []Option{
- ObjectACL(ACLPublicReadWrite),
- Meta("my", "mydestprop"),
- MetadataDirective(MetaReplace),
- }
- _, err = s.bucket.CopyObject(objectName, objectNameDest, options...)
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- destMeta, err = s.bucket.GetObjectDetailedMeta(objectNameDest)
- c.Assert(err, IsNil)
- c.Assert(destMeta.Get("X-Oss-Meta-My"), Equals, "mydestprop")
- acl, err = s.bucket.GetObjectACL(objectNameDest)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
- err = s.bucket.DeleteObject(objectNameDest)
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- // TestCopyObjectToOrFrom
- func (s *OssBucketSuite) TestCopyObjectToOrFrom(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "男儿何不带吴钩,收取关山五十州。请君暂上凌烟阁,若个书生万户侯?"
- destBucketName := bucketName + "-dest"
- objectNameDest := objectName + "-dest"
- err := s.client.CreateBucket(destBucketName)
- c.Assert(err, IsNil)
- destBucket, err := s.client.Bucket(destBucketName)
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Copy from
- _, err = destBucket.CopyObjectFrom(bucketName, objectName, objectNameDest)
- c.Assert(err, IsNil)
- // Check
- body, err := destBucket.GetObject(objectNameDest)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Copy to
- _, err = destBucket.CopyObjectTo(bucketName, objectName, objectNameDest)
- c.Assert(err, IsNil)
- // Check
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Clean
- err = destBucket.DeleteObject(objectNameDest)
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- err = s.client.DeleteBucket(destBucketName)
- c.Assert(err, IsNil)
- }
- // TestCopyObjectToOrFromNegative
- func (s *OssBucketSuite) TestCopyObjectToOrFromNegative(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- destBucket := bucketName + "-dest"
- objectNameDest := objectName + "-dest"
- // Object not exist
- _, err := s.bucket.CopyObjectTo(bucketName, objectName, objectNameDest)
- c.Assert(err, NotNil)
- // Bucket not exist
- _, err = s.bucket.CopyObjectFrom(destBucket, objectNameDest, objectName)
- c.Assert(err, NotNil)
- }
- // TestAppendObject
- func (s *OssBucketSuite) TestAppendObject(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。"
- var val = []byte(objectValue)
- var localFile = RandStr(8) + ".txt"
- var nextPos int64
- var midPos = 1 + rand.Intn(len(val)-1)
- var err = CreateFileAndWrite(localFile+"1", val[0:midPos])
- c.Assert(err, IsNil)
- err = CreateFileAndWrite(localFile+"2", val[midPos:])
- c.Assert(err, IsNil)
- // String append
- nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,"), nextPos)
- c.Assert(err, IsNil)
- nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("却道海棠依旧。知否?知否?应是绿肥红瘦。"), nextPos)
- c.Assert(err, IsNil)
- body, err := s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Byte append
- nextPos = 0
- nextPos, err = s.bucket.AppendObject(objectName, bytes.NewReader(val[0:midPos]), nextPos)
- c.Assert(err, IsNil)
- nextPos, err = s.bucket.AppendObject(objectName, bytes.NewReader(val[midPos:]), nextPos)
- c.Assert(err, IsNil)
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // File append
- options := []Option{
- ObjectACL(ACLPublicReadWrite),
- Meta("my", "myprop"),
- }
- fd, err := os.Open(localFile + "1")
- c.Assert(err, IsNil)
- defer fd.Close()
- nextPos = 0
- nextPos, err = s.bucket.AppendObject(objectName, fd, nextPos, options...)
- c.Assert(err, IsNil)
- meta, err := s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectDetailedMeta:", meta, ",", nextPos)
- c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Appendable")
- c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
- c.Assert(meta.Get("x-oss-Meta-Mine"), Equals, "")
- c.Assert(meta.Get("X-Oss-Next-Append-Position"), Equals, strconv.FormatInt(nextPos, 10))
- acl, err := s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectACL:", acl)
- c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
- // Second append
- options = []Option{
- ObjectACL(ACLPublicRead),
- Meta("my", "myproptwo"),
- Meta("mine", "mypropmine"),
- }
- fd, err = os.Open(localFile + "2")
- c.Assert(err, IsNil)
- defer fd.Close()
- nextPos, err = s.bucket.AppendObject(objectName, fd, nextPos, options...)
- c.Assert(err, IsNil)
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- meta, err = s.bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- testLogger.Println("GetObjectDetailedMeta xxx:", meta)
- c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Appendable")
- c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
- c.Assert(meta.Get("x-Oss-Meta-Mine"), Equals, "")
- c.Assert(meta.Get("X-Oss-Next-Append-Position"), Equals, strconv.FormatInt(nextPos, 10))
- acl, err = s.bucket.GetObjectACL(objectName)
- c.Assert(err, IsNil)
- c.Assert(acl.ACL, Equals, string(ACLPublicRead))
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- // TestAppendObjectNegative
- func (s *OssBucketSuite) TestAppendObjectNegative(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- nextPos := int64(0)
- nextPos, err := s.bucket.AppendObject(objectName, strings.NewReader("ObjectValue"), nextPos)
- c.Assert(err, IsNil)
- nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("ObjectValue"), 0)
- c.Assert(err, NotNil)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- // TestContentType
- func (s *OssBucketSuite) TestAddContentType(c *C) {
- opts := AddContentType(nil, "abc.txt")
- typ, err := FindOption(opts, HTTPHeaderContentType, "")
- c.Assert(err, IsNil)
- c.Assert(strings.Contains(typ.(string), "text/plain"), Equals, true)
- opts = AddContentType(nil)
- typ, err = FindOption(opts, HTTPHeaderContentType, "")
- c.Assert(err, IsNil)
- c.Assert(len(opts), Equals, 1)
- c.Assert(strings.Contains(typ.(string), "application/octet-stream"), Equals, true)
- opts = AddContentType(nil, "abc.txt", "abc.pdf")
- typ, err = FindOption(opts, HTTPHeaderContentType, "")
- c.Assert(err, IsNil)
- c.Assert(strings.Contains(typ.(string), "text/plain"), Equals, true)
- opts = AddContentType(nil, "abc", "abc.txt", "abc.pdf")
- typ, err = FindOption(opts, HTTPHeaderContentType, "")
- c.Assert(err, IsNil)
- c.Assert(strings.Contains(typ.(string), "text/plain"), Equals, true)
- opts = AddContentType(nil, "abc", "abc", "edf")
- typ, err = FindOption(opts, HTTPHeaderContentType, "")
- c.Assert(err, IsNil)
- c.Assert(strings.Contains(typ.(string), "application/octet-stream"), Equals, true)
- opts = AddContentType([]Option{Meta("meta", "my")}, "abc", "abc.txt", "abc.pdf")
- typ, err = FindOption(opts, HTTPHeaderContentType, "")
- c.Assert(err, IsNil)
- c.Assert(len(opts), Equals, 2)
- c.Assert(strings.Contains(typ.(string), "text/plain"), Equals, true)
- }
- func (s *OssBucketSuite) TestGetConfig(c *C) {
- client, err := New(endpoint, accessID, accessKey, UseCname(true),
- Timeout(11, 12), SecurityToken("token"), EnableMD5(false))
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucket.GetConfig().HTTPTimeout.ConnectTimeout, Equals, time.Second*11)
- c.Assert(bucket.GetConfig().HTTPTimeout.ReadWriteTimeout, Equals, time.Second*12)
- c.Assert(bucket.GetConfig().HTTPTimeout.HeaderTimeout, Equals, time.Second*12)
- c.Assert(bucket.GetConfig().HTTPTimeout.IdleConnTimeout, Equals, time.Second*12)
- c.Assert(bucket.GetConfig().HTTPTimeout.LongTimeout, Equals, time.Second*12*10)
- c.Assert(bucket.GetConfig().SecurityToken, Equals, "token")
- c.Assert(bucket.GetConfig().IsCname, Equals, true)
- c.Assert(bucket.GetConfig().IsEnableMD5, Equals, false)
- }
- func (s *OssBucketSuite) TestSTSToken(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- objectValue := "红藕香残玉簟秋。轻解罗裳,独上兰舟。云中谁寄锦书来?雁字回时,月满西楼。"
- stsClient := sts.NewClient(stsaccessID, stsaccessKey, stsARN, "oss_test_sess")
- resp, err := stsClient.AssumeRole(1800)
- c.Assert(err, IsNil)
- client, err := New(endpoint, resp.Credentials.AccessKeyId, resp.Credentials.AccessKeySecret,
- SecurityToken(resp.Credentials.SecurityToken))
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- // Put
- err = bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Get
- body, err := bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // List
- lor, err := bucket.ListObjects()
- c.Assert(err, IsNil)
- testLogger.Println("Objects:", lor.Objects)
- // Put with URL
- signedURL, err := bucket.SignURL(objectName, HTTPPut, 3600)
- c.Assert(err, IsNil)
- err = bucket.PutObjectWithURL(signedURL, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Get with URL
- signedURL, err = bucket.SignURL(objectName, HTTPGet, 3600)
- c.Assert(err, IsNil)
- body, err = bucket.GetObjectWithURL(signedURL)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, objectValue)
- // Delete
- err = bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- func (s *OssBucketSuite) TestSTSTonekNegative(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- localFile := objectName + ".jpg"
- client, err := New(endpoint, accessID, accessKey, SecurityToken("Invalid"))
- c.Assert(err, IsNil)
- _, err = client.ListBuckets()
- c.Assert(err, NotNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- err = bucket.PutObject(objectName, strings.NewReader(""))
- c.Assert(err, NotNil)
- err = bucket.PutObjectFromFile(objectName, "")
- c.Assert(err, NotNil)
- _, err = bucket.GetObject(objectName)
- c.Assert(err, NotNil)
- err = bucket.GetObjectToFile(objectName, "")
- c.Assert(err, NotNil)
- _, err = bucket.ListObjects()
- c.Assert(err, NotNil)
- err = bucket.SetObjectACL(objectName, ACLPublicRead)
- c.Assert(err, NotNil)
- _, err = bucket.GetObjectACL(objectName)
- c.Assert(err, NotNil)
- err = bucket.UploadFile(objectName, localFile, MinPartSize)
- c.Assert(err, NotNil)
- err = bucket.DownloadFile(objectName, localFile, MinPartSize)
- c.Assert(err, NotNil)
- _, err = bucket.IsObjectExist(objectName)
- c.Assert(err, NotNil)
- _, err = bucket.ListMultipartUploads()
- c.Assert(err, NotNil)
- err = bucket.DeleteObject(objectName)
- c.Assert(err, NotNil)
- _, err = bucket.DeleteObjects([]string{objectName})
- c.Assert(err, NotNil)
- err = client.DeleteBucket(bucketName)
- c.Assert(err, NotNil)
- }
- func (s *OssBucketSuite) TestUploadBigFile(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- bigFile := "D:\\tmp\\bigfile.zip"
- newFile := "D:\\tmp\\newbigfile.zip"
- exist, err := isFileExist(bigFile)
- c.Assert(err, IsNil)
- if !exist {
- return
- }
- // Put
- start := GetNowSec()
- err = s.bucket.PutObjectFromFile(objectName, bigFile)
- c.Assert(err, IsNil)
- end := GetNowSec()
- testLogger.Println("Put big file:", bigFile, "use sec:", end-start)
- // Check
- start = GetNowSec()
- err = s.bucket.GetObjectToFile(objectName, newFile)
- c.Assert(err, IsNil)
- end = GetNowSec()
- testLogger.Println("Get big file:", bigFile, "use sec:", end-start)
- start = GetNowSec()
- eq, err := compareFiles(bigFile, newFile)
- c.Assert(err, IsNil)
- c.Assert(eq, Equals, true)
- end = GetNowSec()
- testLogger.Println("Compare big file:", bigFile, "use sec:", end-start)
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- }
- func (s *OssBucketSuite) TestSymlink(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- targetObjectName := objectName + "target"
- err := s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(targetObjectName)
- c.Assert(err, IsNil)
- meta, err := s.bucket.GetSymlink(objectName)
- c.Assert(err, NotNil)
- // Put symlink
- err = s.bucket.PutSymlink(objectName, targetObjectName)
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(targetObjectName, strings.NewReader("target"))
- c.Assert(err, IsNil)
- err = s.bucket.PutSymlink(objectName, targetObjectName)
- c.Assert(err, IsNil)
- meta, err = s.bucket.GetSymlink(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get(HTTPHeaderOssSymlinkTarget), Equals, targetObjectName)
- // List object
- lor, err := s.bucket.ListObjects()
- c.Assert(err, IsNil)
- exist, v := s.getObject(lor.Objects, objectName)
- c.Assert(exist, Equals, true)
- c.Assert(v.Type, Equals, "Symlink")
- body, err := s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, "target")
- meta, err = s.bucket.GetSymlink(targetObjectName)
- c.Assert(err, NotNil)
- err = s.bucket.PutObject(objectName, strings.NewReader("src"))
- c.Assert(err, IsNil)
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, "src")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(targetObjectName)
- c.Assert(err, IsNil)
- // Put symlink again
- objectName = objectNamePrefix + RandStr(8)
- targetObjectName = objectName + "-target"
- err = s.bucket.PutSymlink(objectName, targetObjectName)
- c.Assert(err, IsNil)
- err = s.bucket.PutObject(targetObjectName, strings.NewReader("target1"))
- c.Assert(err, IsNil)
- meta, err = s.bucket.GetSymlink(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get(HTTPHeaderOssSymlinkTarget), Equals, targetObjectName)
- body, err = s.bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, "target1")
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObject(targetObjectName)
- c.Assert(err, IsNil)
- }
- // TestRestoreObject
- func (s *OssBucketSuite) TestRestoreObject(c *C) {
- objectName := objectNamePrefix + RandStr(8)
- // List objects
- lor, err := s.archiveBucket.ListObjects()
- c.Assert(err, IsNil)
- left := len(lor.Objects)
- // Put object
- err = s.archiveBucket.PutObject(objectName, strings.NewReader(""))
- c.Assert(err, IsNil)
- // List
- lor, err = s.archiveBucket.ListObjects()
- c.Assert(err, IsNil)
- c.Assert(len(lor.Objects), Equals, left+1)
- for _, object := range lor.Objects {
- c.Assert(object.StorageClass, Equals, string(StorageArchive))
- c.Assert(object.Type, Equals, "Normal")
- }
- // Head object
- meta, err := s.archiveBucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- _, ok := meta["X-Oss-Restore"]
- c.Assert(ok, Equals, false)
- c.Assert(meta.Get("X-Oss-Storage-Class"), Equals, "Archive")
- // Error restore object
- err = s.archiveBucket.RestoreObject("notexistobject")
- c.Assert(err, NotNil)
- // Restore object
- err = s.archiveBucket.RestoreObject(objectName)
- c.Assert(err, IsNil)
- // Head object
- meta, err = s.archiveBucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get("X-Oss-Restore"), Equals, "ongoing-request=\"true\"")
- c.Assert(meta.Get("X-Oss-Storage-Class"), Equals, "Archive")
- }
- // TestRestoreObjectWithXml
- func (s *OssBucketSuite) TestRestoreObjectWithConfig(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName, StorageClass(StorageColdArchive))
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- objectName := objectNamePrefix + RandStr(8)
- // Put object
- err = bucket.PutObject(objectName, strings.NewReader("123456789"), ObjectStorageClass(StorageColdArchive))
- c.Assert(err, IsNil)
- var restoreConfig RestoreConfiguration
- restoreConfig.Days = 2
- err = bucket.RestoreObjectDetail(objectName, restoreConfig)
- c.Assert(err, IsNil)
- objectName = objectNamePrefix + RandStr(8)
- err = bucket.PutObject(objectName, strings.NewReader("123456789"), ObjectStorageClass(StorageColdArchive))
- c.Assert(err, IsNil)
- restoreConfig.Tier = string(RestoreBulk)
- err = bucket.RestoreObjectDetail(objectName, restoreConfig)
- c.Assert(err, IsNil)
- objectName = objectNamePrefix + RandStr(8)
- err = bucket.PutObject(objectName, strings.NewReader("123456789"), ObjectStorageClass(StorageColdArchive))
- c.Assert(err, IsNil)
- restoreConfig.Days = 0
- err = bucket.RestoreObjectDetail(objectName, restoreConfig)
- c.Assert(err, IsNil)
- ForceDeleteBucket(client, bucketName, c)
- }
- // TestProcessObject
- func (s *OssBucketSuite) TestProcessObject(c *C) {
- objectName := objectNamePrefix + RandStr(8) + ".jpg"
- err := s.bucket.PutObjectFromFile(objectName, "../sample/BingWallpaper-2015-11-07.jpg")
- c.Assert(err, IsNil)
- // If bucket-name not specified, it is saved to the current bucket by default.
- destObjName := objectNamePrefix + RandStr(8) + "-dest.jpg"
- process := fmt.Sprintf("image/resize,w_100|sys/saveas,o_%v", base64.URLEncoding.EncodeToString([]byte(destObjName)))
- result, err := s.bucket.ProcessObject(objectName, process)
- c.Assert(err, IsNil)
- exist, _ := s.bucket.IsObjectExist(destObjName)
- c.Assert(exist, Equals, true)
- c.Assert(result.Bucket, Equals, "")
- c.Assert(result.Object, Equals, destObjName)
- destObjName = objectNamePrefix + RandStr(8) + "-dest.jpg"
- 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)))
- result, err = s.bucket.ProcessObject(objectName, process)
- c.Assert(err, IsNil)
- exist, _ = s.bucket.IsObjectExist(destObjName)
- c.Assert(exist, Equals, true)
- c.Assert(result.Bucket, Equals, s.bucket.BucketName)
- c.Assert(result.Object, Equals, destObjName)
- //no support process
- process = fmt.Sprintf("image/resize,w_100|saveas,o_%v,b_%v", base64.URLEncoding.EncodeToString([]byte(destObjName)), base64.URLEncoding.EncodeToString([]byte(s.bucket.BucketName)))
- result, err = s.bucket.ProcessObject(objectName, process)
- c.Assert(err, NotNil)
- }
- // Private
- func CreateFileAndWrite(fileName string, data []byte) error {
- os.Remove(fileName)
- fo, err := os.Create(fileName)
- if err != nil {
- return err
- }
- defer fo.Close()
- bytes, err := fo.Write(data)
- if err != nil {
- return err
- }
- if bytes != len(data) {
- return fmt.Errorf(fmt.Sprintf("write %d bytes not equal data length %d", bytes, len(data)))
- }
- return nil
- }
- // Compare the content between fileL and fileR
- func compareFiles(fileL string, fileR string) (bool, error) {
- finL, err := os.Open(fileL)
- if err != nil {
- return false, err
- }
- defer finL.Close()
- finR, err := os.Open(fileR)
- if err != nil {
- return false, err
- }
- defer finR.Close()
- statL, err := finL.Stat()
- if err != nil {
- return false, err
- }
- statR, err := finR.Stat()
- if err != nil {
- return false, err
- }
- if statL.Size() != statR.Size() {
- return false, nil
- }
- size := statL.Size()
- if size > 102400 {
- size = 102400
- }
- bufL := make([]byte, size)
- bufR := make([]byte, size)
- for {
- n, _ := finL.Read(bufL)
- if 0 == n {
- break
- }
- n, _ = finR.Read(bufR)
- if 0 == n {
- break
- }
- if !bytes.Equal(bufL, bufR) {
- return false, nil
- }
- }
- return true, nil
- }
- // Compare the content of file and data
- func compareFileData(file string, data []byte) (bool, error) {
- fin, err := os.Open(file)
- if err != nil {
- return false, err
- }
- defer fin.Close()
- stat, err := fin.Stat()
- if err != nil {
- return false, err
- }
- if stat.Size() != (int64)(len(data)) {
- return false, nil
- }
- buf := make([]byte, stat.Size())
- n, err := fin.Read(buf)
- if err != nil {
- return false, err
- }
- if stat.Size() != (int64)(n) {
- return false, errors.New("read error")
- }
- if !bytes.Equal(buf, data) {
- return false, nil
- }
- return true, nil
- }
- func walkDir(dirPth, suffix string) ([]string, error) {
- var files = []string{}
- suffix = strings.ToUpper(suffix)
- err := filepath.Walk(dirPth,
- func(filename string, fi os.FileInfo, err error) error {
- if err != nil {
- return err
- }
- if fi.IsDir() {
- return nil
- }
- if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
- files = append(files, filename)
- }
- return nil
- })
- return files, err
- }
- func removeTempFiles(path string, prefix string) error {
- files, err := walkDir(path, prefix)
- if err != nil {
- return nil
- }
- for _, file := range files {
- os.Remove(file)
- }
- return nil
- }
- func isFileExist(filename string) (bool, error) {
- _, err := os.Stat(filename)
- if err != nil && os.IsNotExist(err) {
- return false, nil
- } else if err != nil {
- return false, err
- } else {
- return true, nil
- }
- }
- func readBody(body io.ReadCloser) (string, error) {
- data, err := ioutil.ReadAll(body)
- body.Close()
- if err != nil {
- return "", err
- }
- return string(data), nil
- }
- func (s *OssBucketSuite) getObject(objects []ObjectProperties, object string) (bool, ObjectProperties) {
- for _, v := range objects {
- if v.Key == object {
- return true, v
- }
- }
- return false, ObjectProperties{}
- }
- func (s *OssBucketSuite) detectUploadSpeed(bucket *Bucket, c *C) (upSpeed int) {
- objectName := objectNamePrefix + RandStr(8)
- // 1M byte
- textBuffer := RandStr(1024 * 1024)
- // Put string
- startT := time.Now()
- err := bucket.PutObject(objectName, strings.NewReader(textBuffer))
- endT := time.Now()
- c.Assert(err, IsNil)
- err = bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // byte/s
- upSpeed = len(textBuffer) * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
- return upSpeed
- }
- func (s *OssBucketSuite) TestPutSingleObjectLimitSpeed(c *C) {
- // create client and bucket
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.LimitUploadSpeed(1)
- if err != nil {
- // go version is less than go1.7,not support limit upload speed
- // doesn't run this test
- return
- }
- // set unlimited again
- client.LimitUploadSpeed(0)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- //detect speed:byte/s
- detectSpeed := s.detectUploadSpeed(bucket, c)
- var limitSpeed = 0
- if detectSpeed <= perTokenBandwidthSize*2 {
- limitSpeed = perTokenBandwidthSize
- } else {
- //this situation, the test works better
- limitSpeed = detectSpeed / 2
- }
- // KB/s
- err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
- c.Assert(err, IsNil)
- objectName := objectNamePrefix + RandStr(8)
- // 1M byte
- textBuffer := RandStr(1024 * 1024)
- // Put body
- startT := time.Now()
- err = bucket.PutObject(objectName, strings.NewReader(textBuffer))
- endT := time.Now()
- realSpeed := int64(len(textBuffer)) * 1000 / (endT.UnixNano()/1000/1000 - startT.UnixNano()/1000/1000)
- fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
- c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
- if detectSpeed > perTokenBandwidthSize {
- // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
- c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
- }
- // Get object and compare content
- body, err := bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, textBuffer)
- bucket.DeleteObject(objectName)
- client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- return
- }
- func putObjectRoutin(bucket *Bucket, object string, textBuffer *string, notifyChan chan int) error {
- err := bucket.PutObject(object, strings.NewReader(*textBuffer))
- if err == nil {
- notifyChan <- 1
- } else {
- notifyChan <- 0
- }
- return err
- }
- func (s *OssBucketSuite) TestPutManyObjectLimitSpeed(c *C) {
- // create client and bucket
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.LimitUploadSpeed(1)
- if err != nil {
- // go version is less than go1.7,not support limit upload speed
- // doesn't run this test
- return
- }
- // set unlimited
- client.LimitUploadSpeed(0)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- //detect speed:byte/s
- detectSpeed := s.detectUploadSpeed(bucket, c)
- var limitSpeed = 0
- if detectSpeed <= perTokenBandwidthSize*2 {
- limitSpeed = perTokenBandwidthSize
- } else {
- limitSpeed = detectSpeed / 2
- }
- // KB/s
- err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
- c.Assert(err, IsNil)
- // object1
- objectNameFirst := objectNamePrefix + RandStr(8)
- objectNameSecond := objectNamePrefix + RandStr(8)
- // 1M byte
- textBuffer := RandStr(1024 * 1024)
- objectCount := 2
- notifyChan := make(chan int, objectCount)
- //start routin
- startT := time.Now()
- go putObjectRoutin(bucket, objectNameFirst, &textBuffer, notifyChan)
- go putObjectRoutin(bucket, objectNameSecond, &textBuffer, notifyChan)
- // wait routin end
- sum := int(0)
- for j := 0; j < objectCount; j++ {
- result := <-notifyChan
- sum += result
- }
- endT := time.Now()
- realSpeed := len(textBuffer) * 2 * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
- c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
- if detectSpeed > perTokenBandwidthSize {
- // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
- c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
- }
- c.Assert(sum, Equals, 2)
- // Get object and compare content
- body, err := bucket.GetObject(objectNameFirst)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, textBuffer)
- body, err = bucket.GetObject(objectNameSecond)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, textBuffer)
- // clear bucket and object
- bucket.DeleteObject(objectNameFirst)
- bucket.DeleteObject(objectNameSecond)
- client.DeleteBucket(bucketName)
- fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
- return
- }
- func (s *OssBucketSuite) TestPutMultipartObjectLimitSpeed(c *C) {
- // create client and bucket
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.LimitUploadSpeed(1)
- if err != nil {
- // go version is less than go1.7,not support limit upload speed
- // doesn't run this test
- return
- }
- // set unlimited
- client.LimitUploadSpeed(0)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- //detect speed:byte/s
- detectSpeed := s.detectUploadSpeed(bucket, c)
- var limitSpeed = 0
- if detectSpeed <= perTokenBandwidthSize*2 {
- limitSpeed = perTokenBandwidthSize
- } else {
- //this situation, the test works better
- limitSpeed = detectSpeed / 2
- }
- // KB/s
- err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
- c.Assert(err, IsNil)
- objectName := objectNamePrefix + RandStr(8)
- fileName := "." + string(os.PathSeparator) + objectName
- // 1M byte
- fileSize := 0
- textBuffer := RandStr(1024 * 1024)
- if detectSpeed < perTokenBandwidthSize {
- ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
- f, err := os.Stat(fileName)
- c.Assert(err, IsNil)
- fileSize = int(f.Size())
- c.Assert(fileSize, Equals, len(textBuffer))
- } else {
- loopCount := 5
- f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
- c.Assert(err, IsNil)
- for i := 0; i < loopCount; i++ {
- f.Write([]byte(textBuffer))
- }
- fileInfo, err := f.Stat()
- c.Assert(err, IsNil)
- fileSize = int(fileInfo.Size())
- c.Assert(fileSize, Equals, len(textBuffer)*loopCount)
- f.Close()
- }
- // Put body
- startT := time.Now()
- err = bucket.UploadFile(objectName, fileName, 100*1024, Routines(3), Checkpoint(true, ""))
- endT := time.Now()
- c.Assert(err, IsNil)
- realSpeed := fileSize * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
- c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
- if detectSpeed > perTokenBandwidthSize {
- // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
- c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
- }
- // Get object and compare content
- body, err := bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- fileBody, err := ioutil.ReadFile(fileName)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, string(fileBody))
- // delete bucket、object、file
- bucket.DeleteObject(objectName)
- client.DeleteBucket(bucketName)
- os.Remove(fileName)
- fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
- return
- }
- func (s *OssBucketSuite) TestPutObjectFromFileLimitSpeed(c *C) {
- // create client and bucket
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.LimitUploadSpeed(1)
- if err != nil {
- // go version is less than go1.7,not support limit upload speed
- // doesn't run this test
- return
- }
- // set unlimited
- client.LimitUploadSpeed(0)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- //detect speed:byte/s
- detectSpeed := s.detectUploadSpeed(bucket, c)
- var limitSpeed = 0
- if detectSpeed <= perTokenBandwidthSize*2 {
- limitSpeed = perTokenBandwidthSize
- } else {
- //this situation, the test works better
- limitSpeed = detectSpeed / 2
- }
- // KB/s
- err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
- c.Assert(err, IsNil)
- objectName := objectNamePrefix + RandStr(8)
- fileName := "." + string(os.PathSeparator) + objectName
- // 1M byte
- fileSize := 0
- textBuffer := RandStr(1024 * 1024)
- if detectSpeed < perTokenBandwidthSize {
- ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
- f, err := os.Stat(fileName)
- c.Assert(err, IsNil)
- fileSize = int(f.Size())
- c.Assert(fileSize, Equals, len(textBuffer))
- } else {
- loopCount := 2
- f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
- c.Assert(err, IsNil)
- for i := 0; i < loopCount; i++ {
- f.Write([]byte(textBuffer))
- }
- fileInfo, err := f.Stat()
- c.Assert(err, IsNil)
- fileSize = int(fileInfo.Size())
- c.Assert(fileSize, Equals, len(textBuffer)*loopCount)
- f.Close()
- }
- // Put body
- startT := time.Now()
- err = bucket.PutObjectFromFile(objectName, fileName)
- endT := time.Now()
- c.Assert(err, IsNil)
- realSpeed := fileSize * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
- c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
- if detectSpeed > perTokenBandwidthSize {
- // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
- c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
- }
- // Get object and compare content
- body, err := bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- fileBody, err := ioutil.ReadFile(fileName)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, string(fileBody))
- // delete bucket、file、object
- bucket.DeleteObject(objectName)
- client.DeleteBucket(bucketName)
- os.Remove(fileName)
- fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
- return
- }
- // upload speed limit parameters will not affect download speed
- func (s *OssBucketSuite) TestUploadObjectLimitSpeed(c *C) {
- // create limit client and bucket
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- tokenCount := 1
- err = client.LimitUploadSpeed(tokenCount)
- if err != nil {
- // go version is less than go1.7,not support limit upload speed
- // doesn't run this test
- return
- }
- // set unlimited
- client.LimitUploadSpeed(0)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- //first:upload a object
- textBuffer := RandStr(1024 * 100)
- objectName := objectNamePrefix + RandStr(8)
- err = bucket.PutObject(objectName, strings.NewReader(textBuffer))
- c.Assert(err, IsNil)
- // limit upload speed
- err = client.LimitUploadSpeed(tokenCount)
- c.Assert(err, IsNil)
- // then download the object
- startT := time.Now()
- body, err := bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- endT := time.Now()
- c.Assert(str, Equals, textBuffer)
- // byte/s
- downloadSpeed := len(textBuffer) * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
- // upload speed limit parameters will not affect download speed
- c.Assert(downloadSpeed > 2*tokenCount*perTokenBandwidthSize, Equals, true)
- bucket.DeleteObject(objectName)
- client.DeleteBucket(bucketName)
- }
- // test LimitUploadSpeed failure
- func (s *OssBucketSuite) TestLimitUploadSpeedFail(c *C) {
- // create limit client and bucket
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.LimitUploadSpeed(-1)
- c.Assert(err, NotNil)
- client.Config = nil
- err = client.LimitUploadSpeed(100)
- c.Assert(err, NotNil)
- }
- // upload webp object
- func (s *OssBucketSuite) TestUploadObjectWithWebpFormat(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- // create webp file
- textBuffer := RandStr(1024)
- objectName := objectNamePrefix + RandStr(8)
- fileName := "." + string(os.PathSeparator) + objectName + ".webp"
- ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
- _, err = os.Stat(fileName)
- c.Assert(err, IsNil)
- err = bucket.PutObjectFromFile(objectName, fileName)
- c.Assert(err, IsNil)
- // check object content-type
- props, err := bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(props["Content-Type"][0], Equals, "image/webp")
- os.Remove(fileName)
- bucket.DeleteObject(objectName)
- client.DeleteBucket(bucketName)
- }
- func (s *OssBucketSuite) TestPutObjectTagging(c *C) {
- // put object with tagging
- objectName := objectNamePrefix + RandStr(8)
- tag1 := Tag{
- Key: RandStr(8),
- Value: RandStr(9),
- }
- tag2 := Tag{
- Key: RandStr(10),
- Value: RandStr(11),
- }
- tagging := Tagging{
- Tags: []Tag{tag1, tag2},
- }
- err := s.bucket.PutObject(objectName, strings.NewReader(RandStr(1024)), SetTagging(tagging))
- c.Assert(err, IsNil)
- headers, err := s.bucket.GetObjectDetailedMeta(objectName)
- taggingCount, err := strconv.Atoi(headers["X-Oss-Tagging-Count"][0])
- c.Assert(err, IsNil)
- c.Assert(taggingCount, Equals, 2)
- // copy object with default option
- destObjectName := objectNamePrefix + RandStr(8)
- _, err = s.bucket.CopyObject(objectName, destObjectName)
- c.Assert(err, IsNil)
- headers, err = s.bucket.GetObjectDetailedMeta(destObjectName)
- taggingCount, err = strconv.Atoi(headers["X-Oss-Tagging-Count"][0])
- c.Assert(err, IsNil)
- c.Assert(taggingCount, Equals, 2)
- // delete object tagging
- err = s.bucket.DeleteObjectTagging(objectName)
- c.Assert(err, IsNil)
- // get object tagging again
- taggingResult, err := s.bucket.GetObjectTagging(objectName)
- c.Assert(err, IsNil)
- c.Assert(len(taggingResult.Tags), Equals, 0)
- // put tagging
- tag := Tag{
- Key: RandStr(8),
- Value: RandStr(16),
- }
- tagging.Tags = []Tag{tag}
- err = s.bucket.PutObjectTagging(objectName, tagging)
- c.Assert(err, IsNil)
- taggingResult, err = s.bucket.GetObjectTagging(objectName)
- c.Assert(len(taggingResult.Tags), Equals, 1)
- c.Assert(taggingResult.Tags[0].Key, Equals, tag.Key)
- c.Assert(taggingResult.Tags[0].Value, Equals, tag.Value)
- //put tagging, the length of the key exceeds 128
- tag = Tag{
- Key: RandStr(129),
- Value: RandStr(16),
- }
- tagging.Tags = []Tag{tag}
- err = s.bucket.PutObjectTagging(objectName, tagging)
- c.Assert(err, NotNil)
- //put tagging, the length of the value exceeds 256
- tag = Tag{
- Key: RandStr(8),
- Value: RandStr(257),
- }
- tagging.Tags = []Tag{tag}
- err = s.bucket.PutObjectTagging(objectName, tagging)
- c.Assert(err, NotNil)
- //put tagging, the lens of tags exceed 10
- tagging.Tags = []Tag{}
- for i := 0; i < 11; i++ {
- tag = Tag{
- Key: RandStr(8),
- Value: RandStr(16),
- }
- tagging.Tags = append(tagging.Tags, tag)
- }
- err = s.bucket.PutObjectTagging(objectName, tagging)
- c.Assert(err, NotNil)
- //put tagging, invalid value of tag key
- tag = Tag{
- Key: RandStr(8) + "&",
- Value: RandStr(16),
- }
- tagging.Tags = []Tag{tag}
- err = s.bucket.PutObjectTagging(objectName, tagging)
- c.Assert(err, NotNil)
- //put tagging, invalid value of tag value
- tag = Tag{
- Key: RandStr(8),
- Value: RandStr(16) + "&",
- }
- tagging.Tags = []Tag{tag}
- err = s.bucket.PutObjectTagging(objectName, tagging)
- c.Assert(err, NotNil)
- //put tagging, repeated tag keys
- tag1 = Tag{
- Key: RandStr(8),
- Value: RandStr(16),
- }
- tag2 = Tag{
- Key: tag1.Key,
- Value: RandStr(16),
- }
- tagging.Tags = []Tag{tag1, tag2}
- err = s.bucket.PutObjectTagging(objectName, tagging)
- c.Assert(err, NotNil)
- s.bucket.DeleteObject(destObjectName)
- s.bucket.DeleteObject(objectName)
- }
- func (s *OssBucketSuite) TestGetObjectTagging(c *C) {
- // get object which has 2 tags
- objectName := objectNamePrefix + RandStr(8)
- tag1 := Tag{
- Key: RandStr(8),
- Value: RandStr(9),
- }
- tag2 := Tag{
- Key: RandStr(10),
- Value: RandStr(11),
- }
- taggingInfo := Tagging{
- Tags: []Tag{tag1, tag2},
- }
- err := s.bucket.PutObject(objectName, strings.NewReader(RandStr(1024)), SetTagging(taggingInfo))
- c.Assert(err, IsNil)
- tagging, err := s.bucket.GetObjectTagging(objectName)
- c.Assert(len(tagging.Tags), Equals, 2)
- if tagging.Tags[0].Key == tag1.Key {
- c.Assert(tagging.Tags[0].Value, Equals, tag1.Value)
- c.Assert(tagging.Tags[1].Key, Equals, tag2.Key)
- c.Assert(tagging.Tags[1].Value, Equals, tag2.Value)
- } else {
- c.Assert(tagging.Tags[0].Key, Equals, tag2.Key)
- c.Assert(tagging.Tags[0].Value, Equals, tag2.Value)
- c.Assert(tagging.Tags[1].Key, Equals, tag1.Key)
- c.Assert(tagging.Tags[1].Value, Equals, tag1.Value)
- }
- // get tagging of an object that is not exist
- err = s.bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- tagging, err = s.bucket.GetObjectTagging(objectName)
- c.Assert(err, NotNil)
- c.Assert(len(tagging.Tags), Equals, 0)
- // get object which has no tag
- objectName = objectNamePrefix + RandStr(8)
- err = s.bucket.PutObject(objectName, strings.NewReader(RandStr(1024)))
- c.Assert(err, IsNil)
- tagging, err = s.bucket.GetObjectTagging(objectName)
- c.Assert(err, IsNil)
- c.Assert(len(tagging.Tags), Equals, 0)
- // copy object, with tagging option
- destObjectName := objectName + "-dest"
- tagging.Tags = []Tag{tag1, tag2}
- _, err = s.bucket.CopyObject(objectName, destObjectName, SetTagging(taggingInfo))
- c.Assert(err, IsNil)
- tagging, err = s.bucket.GetObjectTagging(objectName)
- c.Assert(err, IsNil)
- c.Assert(len(tagging.Tags), Equals, 0)
- // copy object, with tagging option, the value of tagging directive is "REPLACE"
- tagging.Tags = []Tag{tag1, tag2}
- _, err = s.bucket.CopyObject(objectName, destObjectName, SetTagging(taggingInfo), TaggingDirective(TaggingReplace))
- c.Assert(err, IsNil)
- tagging, err = s.bucket.GetObjectTagging(destObjectName)
- c.Assert(err, IsNil)
- c.Assert(len(tagging.Tags), Equals, 2)
- if tagging.Tags[0].Key == tag1.Key {
- c.Assert(tagging.Tags[0].Value, Equals, tag1.Value)
- c.Assert(tagging.Tags[1].Key, Equals, tag2.Key)
- c.Assert(tagging.Tags[1].Value, Equals, tag2.Value)
- } else {
- c.Assert(tagging.Tags[0].Key, Equals, tag2.Key)
- c.Assert(tagging.Tags[0].Value, Equals, tag2.Value)
- c.Assert(tagging.Tags[1].Key, Equals, tag1.Key)
- c.Assert(tagging.Tags[1].Value, Equals, tag1.Value)
- }
- s.bucket.DeleteObject(objectName)
- s.bucket.DeleteObject(destObjectName)
- }
- func (s *OssBucketSuite) TestDeleteObjectTagging(c *C) {
- // delete object tagging, the object is not exist
- objectName := objectNamePrefix + RandStr(8)
- err := s.bucket.DeleteObjectTagging(objectName)
- c.Assert(err, NotNil)
- // delete object tagging
- tag := Tag{
- Key: RandStr(8),
- Value: RandStr(16),
- }
- tagging := Tagging{
- Tags: []Tag{tag},
- }
- err = s.bucket.PutObject(objectName, strings.NewReader(RandStr(1024)), SetTagging(tagging))
- c.Assert(err, IsNil)
- err = s.bucket.DeleteObjectTagging(objectName)
- c.Assert(err, IsNil)
- taggingResult, err := s.bucket.GetObjectTagging(objectName)
- c.Assert(err, IsNil)
- c.Assert(len(taggingResult.Tags), Equals, 0)
- //delete object tagging again
- err = s.bucket.DeleteObjectTagging(objectName)
- c.Assert(err, IsNil)
- s.bucket.DeleteObject(objectName)
- }
- func (s *OssBucketSuite) TestUploadFileMimeShtml(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- objectName := objectNamePrefix + RandStr(8)
- fileName := "oss-sdk-test-file-" + RandLowStr(5) + ".shtml"
- CreateFile(fileName, "123", c)
- err = bucket.PutObjectFromFile(objectName, fileName)
- c.Assert(err, IsNil)
- headResult, err := bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- strContentType := headResult.Get("Content-Type")
- c.Assert(strings.Contains(strContentType, "text/html"), Equals, true)
- os.Remove(fileName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningBucketVerison(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // Get default bucket info
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
- c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "")
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
- // put bucket version:enabled
- var respHeader http.Header
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- bucketResult, err = client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put bucket version:Suspended
- versioningConfig.Status = string(VersionSuspended)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err = client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionSuspended))
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningPutAndGetObject(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // get object v1
- body, err := bucket.GetObject(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- body.Close()
- c.Assert(str, Equals, contextV1)
- // get object v2
- body, err = bucket.GetObject(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- body.Close()
- c.Assert(str, Equals, contextV2)
- // get object without version
- body, err = bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- body.Close()
- c.Assert(str, Equals, contextV2)
- err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
- err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningHeadObject(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // head object v1
- headResultV1, err := bucket.GetObjectMeta(objectName, VersionId(versionIdV1))
- objLen, err := strconv.Atoi(headResultV1.Get("Content-Length"))
- c.Assert(objLen, Equals, len(contextV1))
- headResultV1, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV1))
- objLen, err = strconv.Atoi(headResultV1.Get("Content-Length"))
- c.Assert(objLen, Equals, len(contextV1))
- // head object v2
- headResultV2, err := bucket.GetObjectMeta(objectName, VersionId(versionIdV2))
- objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
- c.Assert(objLen, Equals, len(contextV2))
- headResultV2, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV2))
- objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
- c.Assert(objLen, Equals, len(contextV2))
- // head object without version
- // head object v2
- headResult, err := bucket.GetObjectMeta(objectName)
- objLen, err = strconv.Atoi(headResult.Get("Content-Length"))
- c.Assert(objLen, Equals, len(contextV2))
- headResult, err = bucket.GetObjectDetailedMeta(objectName)
- objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
- c.Assert(objLen, Equals, len(contextV2))
- err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
- err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningDeleteLatestVersionObject(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // delete v2 object:permently delete
- options := []Option{VersionId(versionIdV2), GetResponseHeader(&respHeader)}
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, versionIdV2)
- // get v2 object failure
- body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "NoSuchVersion")
- // get v1 object success
- body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- str, err := readBody(body)
- body.Close()
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV1)
- // get default object success:v1
- body, err = bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- body.Close()
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV1)
- err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
- err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningDeleteOldVersionObject(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // delete v1 object:permently delete
- options := []Option{VersionId(versionIdV1), GetResponseHeader(&respHeader)}
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, versionIdV1)
- // get v2 object success
- body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- str, err := readBody(body)
- body.Close()
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV2)
- // get v1 object faliure
- body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "NoSuchVersion")
- // get default object success:v2
- body, err = bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- body.Close()
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV2)
- err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
- err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningDeleteDefaultVersionObject(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // delete default object:mark delete v2
- options := []Option{GetResponseHeader(&respHeader)}
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(err, IsNil)
- markVersionId := GetVersionId(respHeader)
- c.Assert(len(markVersionId) > 0, Equals, true)
- c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
- // get v2 object success
- body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- str, err := readBody(body)
- body.Close()
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV2)
- // get v1 object success
- body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- str, err = readBody(body)
- body.Close()
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV1)
- // get default object failure:marker v2
- body, err = bucket.GetObject(objectName, GetResponseHeader(&respHeader))
- c.Assert(err, NotNil)
- c.Assert(err.(ServiceError).Code, Equals, "NoSuchKey")
- c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
- // delete mark v2
- options = []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, markVersionId)
- // get default object success:v2
- body, err = bucket.GetObject(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- str, err = readBody(body)
- body.Close()
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV2)
- err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
- err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningListObjectVersions(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // delete default object:mark delete v2
- options := []Option{GetResponseHeader(&respHeader)}
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(err, IsNil)
- markVersionId := GetVersionId(respHeader)
- c.Assert(len(markVersionId) > 0, Equals, true)
- c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
- // delete default object again:mark delete v2
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(err, IsNil)
- markVersionIdAgain := GetVersionId(respHeader)
- c.Assert(len(markVersionIdAgain) > 0, Equals, true)
- c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
- c.Assert(markVersionId != markVersionIdAgain, Equals, true)
- // list bucket versions
- listResult, err := bucket.ListObjectVersions()
- c.Assert(err, IsNil)
- c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 2)
- c.Assert(len(listResult.ObjectVersions), Equals, 2)
- mapMarkVersion := map[string]string{}
- mapMarkVersion[listResult.ObjectDeleteMarkers[0].VersionId] = listResult.ObjectDeleteMarkers[0].VersionId
- mapMarkVersion[listResult.ObjectDeleteMarkers[1].VersionId] = listResult.ObjectDeleteMarkers[1].VersionId
- // check delete mark
- _, ok := mapMarkVersion[markVersionId]
- c.Assert(ok == true, Equals, true)
- _, ok = mapMarkVersion[markVersionIdAgain]
- c.Assert(ok == true, Equals, true)
- // check versionId
- mapVersion := map[string]string{}
- mapVersion[listResult.ObjectVersions[0].VersionId] = listResult.ObjectVersions[0].VersionId
- mapVersion[listResult.ObjectVersions[1].VersionId] = listResult.ObjectVersions[1].VersionId
- _, ok = mapVersion[versionIdV1]
- c.Assert(ok == true, Equals, true)
- _, ok = mapVersion[versionIdV2]
- c.Assert(ok == true, Equals, true)
- // delete deleteMark v2
- options = []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, markVersionId)
- // delete deleteMark v2 again
- options = []Option{VersionId(markVersionIdAgain), GetResponseHeader(&respHeader)}
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, markVersionIdAgain)
- // delete versionId
- bucket.DeleteObject(objectName, VersionId(versionIdV1))
- bucket.DeleteObject(objectName, VersionId(versionIdV2))
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningBatchDeleteVersionObjects(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName1 := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- objectName2 := objectNamePrefix + RandStr(8)
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- //batch delete objects
- versionIds := []DeleteObject{DeleteObject{Key: objectName1, VersionId: versionIdV1},
- DeleteObject{Key: objectName2, VersionId: versionIdV2}}
- deleteResult, err := bucket.DeleteObjectVersions(versionIds)
- c.Assert(err, IsNil)
- c.Assert(len(deleteResult.DeletedObjectsDetail), Equals, 2)
- // check delete detail info:key
- deleteMap := map[string]string{}
- deleteMap[deleteResult.DeletedObjectsDetail[0].Key] = deleteResult.DeletedObjectsDetail[0].VersionId
- deleteMap[deleteResult.DeletedObjectsDetail[1].Key] = deleteResult.DeletedObjectsDetail[1].VersionId
- id1, ok := deleteMap[objectName1]
- c.Assert(ok, Equals, true)
- c.Assert(id1, Equals, versionIdV1)
- id2, ok := deleteMap[objectName2]
- c.Assert(ok, Equals, true)
- c.Assert(id2, Equals, versionIdV2)
- // list bucket versions
- listResult, err := bucket.ListObjectVersions()
- c.Assert(err, IsNil)
- c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 0)
- c.Assert(len(listResult.ObjectVersions), Equals, 0)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningBatchDeleteDefaultVersionObjects(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName1 := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- objectName2 := objectNamePrefix + RandStr(8)
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- //batch delete objects
- versionIds := []DeleteObject{DeleteObject{Key: objectName1, VersionId: ""},
- DeleteObject{Key: objectName2, VersionId: ""}}
- deleteResult, err := bucket.DeleteObjectVersions(versionIds)
- c.Assert(err, IsNil)
- // check delete detail info:key
- deleteDetailMap := map[string]DeletedKeyInfo{}
- deleteDetailMap[deleteResult.DeletedObjectsDetail[0].Key] = deleteResult.DeletedObjectsDetail[0]
- deleteDetailMap[deleteResult.DeletedObjectsDetail[1].Key] = deleteResult.DeletedObjectsDetail[1]
- keyInfo1, ok := deleteDetailMap[objectName1]
- c.Assert(ok, Equals, true)
- c.Assert(keyInfo1.Key, Equals, objectName1)
- c.Assert(keyInfo1.VersionId, Equals, "")
- c.Assert(keyInfo1.DeleteMarker, Equals, true)
- c.Assert(keyInfo1.DeleteMarkerVersionId != versionIdV1, Equals, true)
- keyInfo2, ok := deleteDetailMap[objectName2]
- c.Assert(ok, Equals, true)
- c.Assert(keyInfo2.Key, Equals, objectName2)
- c.Assert(keyInfo2.VersionId, Equals, "")
- c.Assert(keyInfo2.DeleteMarker, Equals, true)
- c.Assert(keyInfo2.DeleteMarkerVersionId != versionIdV2, Equals, true)
- // list bucket versions
- listResult, err := bucket.ListObjectVersions()
- c.Assert(err, IsNil)
- c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 2)
- c.Assert(len(listResult.ObjectVersions), Equals, 2)
- // delete version object
- versionIds = []DeleteObject{DeleteObject{Key: objectName1, VersionId: versionIdV1},
- DeleteObject{Key: objectName2, VersionId: versionIdV2}}
- deleteResult, err = bucket.DeleteObjectVersions(versionIds)
- c.Assert(err, IsNil)
- // delete deleteMark object
- versionIds = []DeleteObject{DeleteObject{Key: objectName1, VersionId: keyInfo1.DeleteMarkerVersionId},
- DeleteObject{Key: objectName2, VersionId: keyInfo2.DeleteMarkerVersionId}}
- deleteResult, err = bucket.DeleteObjectVersions(versionIds)
- c.Assert(err, IsNil)
- ForceDeleteBucket(client, bucketName, c)
- }
- // bucket has no versioning flag
- func (s *OssBucketSuite) TestVersioningBatchDeleteNormalObjects(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // not put bucket versioning
- bucket, err := client.Bucket(bucketName)
- // put object v1
- objectName1 := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1), Equals, 0)
- // put object v2
- objectName2 := objectNamePrefix + RandStr(8)
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2), Equals, 0)
- //batch delete objects
- keys := []string{objectName1, objectName2}
- deleteResult, err := bucket.DeleteObjects(keys)
- c.Assert(len(deleteResult.DeletedObjects), Equals, 2)
- // check delete info
- deleteMap := map[string]string{}
- deleteMap[deleteResult.DeletedObjects[0]] = deleteResult.DeletedObjects[0]
- deleteMap[deleteResult.DeletedObjects[1]] = deleteResult.DeletedObjects[1]
- _, ok := deleteMap[objectName1]
- c.Assert(ok, Equals, true)
- _, ok = deleteMap[objectName2]
- c.Assert(ok, Equals, true)
- ForceDeleteBucket(client, bucketName, c)
- c.Assert(err, IsNil)
- }
- func (s *OssBucketSuite) TestVersioningSymlink(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // put object 1
- objectName1 := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object 2
- objectName2 := objectNamePrefix + RandStr(8)
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // put symlink for object 1
- linkName := objectNamePrefix + RandStr(8)
- err = bucket.PutSymlink(linkName, objectName1, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- linkVersionIdV1 := GetVersionId(respHeader)
- // PutSymlink for object 2
- err = bucket.PutSymlink(linkName, objectName2, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- linkVersionIdV2 := GetVersionId(respHeader)
- // check v1 and v2
- c.Assert(linkVersionIdV1 != linkVersionIdV2, Equals, true)
- // GetSymlink for object1
- getResult, err := bucket.GetSymlink(linkName, VersionId(linkVersionIdV1))
- c.Assert(err, IsNil)
- c.Assert(getResult.Get("x-oss-symlink-target"), Equals, objectName1)
- // GetSymlink for object2
- getResult, err = bucket.GetSymlink(linkName, VersionId(linkVersionIdV2))
- c.Assert(err, IsNil)
- c.Assert(getResult.Get("x-oss-symlink-target"), Equals, objectName2)
- bucket.DeleteObject(linkName)
- bucket.DeleteObject(objectName1)
- bucket.DeleteObject(objectName2)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningObjectAcl(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // put Acl for v1
- err = bucket.SetObjectACL(objectName, ACLPublicRead, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- // put Acl for v2
- err = bucket.SetObjectACL(objectName, ACLPublicReadWrite, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- // GetAcl for v1
- getResult, err := bucket.GetObjectACL(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- c.Assert(getResult.ACL, Equals, string(ACLPublicRead))
- // GetAcl for v2
- getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- c.Assert(getResult.ACL, Equals, string(ACLPublicReadWrite))
- // delete default version
- err = bucket.DeleteObject(objectName, GetResponseHeader(&respHeader))
- c.Assert(len(GetVersionId(respHeader)) > 0, Equals, true)
- c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
- // GetAcl for v1 agagin
- getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- c.Assert(getResult.ACL, Equals, string(ACLPublicRead))
- // GetAcl for v2 again
- getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- c.Assert(getResult.ACL, Equals, string(ACLPublicReadWrite))
- // GetAcl for default failure
- getResult, err = bucket.GetObjectACL(objectName)
- c.Assert(err, NotNil)
- bucket.DeleteObject(objectName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningAppendObject(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // append object
- var nextPos int64 = 0
- var respHeader http.Header
- objectName := objectNamePrefix + RandStr(8)
- nextPos, err = bucket.AppendObject(objectName, strings.NewReader("123"), nextPos, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, NullVersion)
- nextPos, err = bucket.AppendObject(objectName, strings.NewReader("456"), nextPos, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, NullVersion)
- // delete object
- err = bucket.DeleteObject(objectName, GetResponseHeader(&respHeader))
- markVersionId := GetVersionId(respHeader)
- // get default object failure
- _, err = bucket.GetObject(objectName)
- c.Assert(err, NotNil)
- // get null version success
- body, err := bucket.GetObject(objectName, VersionId(NullVersion))
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, "123456")
- // append object again:failure
- nextPos, err = bucket.AppendObject(objectName, strings.NewReader("789"), nextPos, GetResponseHeader(&respHeader))
- c.Assert(err, NotNil)
- // delete deletemark
- options := []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
- err = bucket.DeleteObject(objectName, options...)
- c.Assert(markVersionId, Equals, GetVersionId(respHeader))
- // append object again:success
- nextPos, err = bucket.AppendObject(objectName, strings.NewReader("789"), nextPos, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(int(nextPos), Equals, 9)
- bucket.DeleteObject(objectName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningCopyObject(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- destObjectKey := objectNamePrefix + RandStr(8)
- // copyobject default
- _, err = bucket.CopyObject(objectName, destObjectKey, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- srcVersionId := GetCopySrcVersionId(respHeader)
- c.Assert(srcVersionId, Equals, versionIdV2)
- body, err := bucket.GetObject(destObjectKey)
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV2)
- // copyobject v1
- options := []Option{VersionId(versionIdV1), GetResponseHeader(&respHeader)}
- _, err = bucket.CopyObject(objectName, destObjectKey, options...)
- c.Assert(err, IsNil)
- srcVersionId = GetCopySrcVersionId(respHeader)
- c.Assert(srcVersionId, Equals, versionIdV1)
- body, err = bucket.GetObject(destObjectKey)
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- c.Assert(str, Equals, contextV1)
- // delete object
- err = bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // default copyobject again,failuer
- _, err = bucket.CopyObject(objectName, destObjectKey, GetResponseHeader(&respHeader))
- c.Assert(err, NotNil)
- bucket.DeleteObject(objectName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningCompleteMultipartUpload(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- objectName := objectNamePrefix + RandStr(8)
- var fileName = "test-file-" + RandStr(8)
- content := RandStr(500 * 1024)
- CreateFile(fileName, content, c)
- chunks, err := SplitFileByPartNum(fileName, 3)
- c.Assert(err, IsNil)
- options := []Option{
- Expires(futureDate), Meta("my", "myprop"),
- }
- fd, err := os.Open(fileName)
- c.Assert(err, IsNil)
- defer fd.Close()
- imur, err := bucket.InitiateMultipartUpload(objectName, options...)
- c.Assert(err, IsNil)
- var parts []UploadPart
- for _, chunk := range chunks {
- fd.Seek(chunk.Offset, os.SEEK_SET)
- part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number)
- c.Assert(err, IsNil)
- parts = append(parts, part)
- }
- var respHeader http.Header
- _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- //get versionId
- versionIdV1 := GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- meta, err := bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
- c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
- c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Multipart")
- // put object agagin
- err = bucket.PutObject(objectName, strings.NewReader(""), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 := GetVersionId(respHeader)
- c.Assert(versionIdV1 == versionIdV2, Equals, false)
- // get meta v1
- meta, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(content)))
- // get meta v2
- meta, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(0))
- os.Remove(fileName)
- bucket.DeleteObject(objectName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningUploadPartCopy(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // upload mutlipart object with v1
- multiName := objectNamePrefix + RandStr(8)
- var parts []UploadPart
- imur, err := bucket.InitiateMultipartUpload(multiName)
- c.Assert(err, IsNil)
- part, err := bucket.UploadPartCopy(imur, bucketName, objectName, 0, int64(len(contextV1)), 1, VersionId(versionIdV1))
- parts = []UploadPart{part}
- c.Assert(err, IsNil)
- _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- //get versionId
- partVersionIdV1 := GetVersionId(respHeader)
- c.Assert(len(partVersionIdV1) > 0, Equals, true)
- // get meta v1
- meta, err := bucket.GetObjectDetailedMeta(multiName, VersionId(partVersionIdV1))
- c.Assert(err, IsNil)
- c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(contextV1)))
- // upload mutlipart object with v2
- imur, err = bucket.InitiateMultipartUpload(multiName)
- part, err = bucket.UploadPartCopy(imur, bucketName, objectName, 0, int64(len(contextV2)), 1, VersionId(versionIdV2))
- parts = []UploadPart{part}
- _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- //get versionId
- partVersionIdV2 := GetVersionId(respHeader)
- c.Assert(len(partVersionIdV2) > 0, Equals, true)
- // get meta v2
- meta, err = bucket.GetObjectDetailedMeta(multiName, VersionId(partVersionIdV2))
- c.Assert(err, IsNil)
- c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(contextV2)))
- bucket.DeleteObject(objectName)
- bucket.DeleteObject(multiName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningRestoreObject(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName, StorageClass(StorageArchive))
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // RestoreObject v1
- options := []Option{GetResponseHeader(&respHeader), VersionId(versionIdV1)}
- err = bucket.RestoreObject(objectName, options...)
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, versionIdV1)
- // RestoreObject v2
- options = []Option{GetResponseHeader(&respHeader), VersionId(versionIdV2)}
- err = bucket.RestoreObject(objectName, options...)
- c.Assert(err, IsNil)
- c.Assert(GetVersionId(respHeader), Equals, versionIdV2)
- bucket.DeleteObject(objectName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningObjectTagging(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName, StorageClass(StorageArchive))
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // ObjectTagging v1
- var tagging1 Tagging
- tagging1.Tags = []Tag{Tag{Key: "testkey1", Value: "testvalue1"}}
- err = bucket.PutObjectTagging(objectName, tagging1, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- getResult, err := bucket.GetObjectTagging(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- c.Assert(getResult.Tags[0].Key, Equals, tagging1.Tags[0].Key)
- c.Assert(getResult.Tags[0].Value, Equals, tagging1.Tags[0].Value)
- // ObjectTagging v2
- var tagging2 Tagging
- tagging2.Tags = []Tag{Tag{Key: "testkey2", Value: "testvalue2"}}
- err = bucket.PutObjectTagging(objectName, tagging2, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- getResult, err = bucket.GetObjectTagging(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- c.Assert(getResult.Tags[0].Key, Equals, tagging2.Tags[0].Key)
- c.Assert(getResult.Tags[0].Value, Equals, tagging2.Tags[0].Value)
- // delete ObjectTagging v2
- err = bucket.DeleteObjectTagging(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- getResult, err = bucket.GetObjectTagging(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- c.Assert(len(getResult.Tags), Equals, 0)
- bucket.DeleteObject(objectName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestVersioningIsObjectExist(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // check default exist
- exist, err := bucket.IsObjectExist(objectName)
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- // check object v1 exist
- exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- // check object v2 exist
- exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- // rm v2
- err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- // check object v2 not exist
- exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV2))
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, false)
- // rm default
- err = bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // check default exist
- exist, err = bucket.IsObjectExist(objectName)
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, false)
- // check v1 exist
- exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV1))
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestOptionsMethod(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket cors
- var rule = CORSRule{
- AllowedOrigin: []string{"www.aliyun.com"},
- AllowedMethod: []string{"PUT", "GET", "POST"},
- AllowedHeader: []string{"x-oss-meta-author"},
- ExposeHeader: []string{"x-oss-meta-name"},
- MaxAgeSeconds: 100,
- }
- // set cors
- err = client.SetBucketCORS(bucketName, []CORSRule{rule})
- c.Assert(err, IsNil)
- // bucket options success
- options := []Option{}
- originOption := Origin("www.aliyun.com")
- acMethodOption := ACReqMethod("PUT")
- acHeadersOption := ACReqHeaders("x-oss-meta-author")
- options = append(options, originOption)
- options = append(options, acMethodOption)
- options = append(options, acHeadersOption)
- _, err = bucket.OptionsMethod("", options...)
- c.Assert(err, IsNil)
- // options failure
- options = []Option{}
- originOption = Origin("www.aliyun.com")
- acMethodOption = ACReqMethod("PUT")
- acHeadersOption = ACReqHeaders("x-oss-meta-author-1")
- options = append(options, originOption)
- options = append(options, acMethodOption)
- options = append(options, acHeadersOption)
- _, err = bucket.OptionsMethod("", options...)
- c.Assert(err, NotNil)
- // put object
- objectName := objectNamePrefix + RandStr(8)
- context := RandStr(100)
- err = bucket.PutObject(objectName, strings.NewReader(context))
- c.Assert(err, IsNil)
- // object options success
- options = []Option{}
- originOption = Origin("www.aliyun.com")
- acMethodOption = ACReqMethod("PUT")
- acHeadersOption = ACReqHeaders("x-oss-meta-author")
- options = append(options, originOption)
- options = append(options, acMethodOption)
- options = append(options, acHeadersOption)
- _, err = bucket.OptionsMethod("", options...)
- c.Assert(err, IsNil)
- // options failure
- options = []Option{}
- originOption = Origin("www.aliyun.com")
- acMethodOption = ACReqMethod("PUT")
- acHeadersOption = ACReqHeaders("x-oss-meta-author-1")
- options = append(options, originOption)
- options = append(options, acMethodOption)
- options = append(options, acHeadersOption)
- _, err = bucket.OptionsMethod("", options...)
- c.Assert(err, NotNil)
- bucket.DeleteObject(objectName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestBucketTrafficLimitObject1(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- var respHeader http.Header
- var qosDelayTime string
- var traffic int64 = 819220 // 100KB
- maxTraffic := traffic * 120 / 100
- objectName := objectNamePrefix + RandStr(8)
- localFile := "../sample/BingWallpaper-2015-11-07.jpg"
- fd, err := os.Open(localFile)
- c.Assert(err, IsNil)
- defer fd.Close()
- tryGetFileSize := func(f *os.File) int64 {
- fInfo, _ := f.Stat()
- return fInfo.Size()
- }
- contentLength := tryGetFileSize(fd) * 8
- // put object
- start := time.Now().UnixNano() / 1000 / 1000
- err = bucket.PutObject(objectName, fd, TrafficLimitHeader(traffic), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- endingTime := time.Now().UnixNano() / 1000 / 1000
- costT := endingTime - start
- costV := contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
- c.Assert((costV < maxTraffic), Equals, true)
- qosDelayTime = GetQosDelayTime(respHeader)
- c.Assert(len(qosDelayTime) > 0, Equals, true)
- // putobject without TrafficLimit
- //
- // fd, err = os.Open(localFile)
- // c.Assert(err, IsNil)
- // defer fd.Close()
- // start = time.Now().UnixNano() / 1000 / 1000
- // err = bucket.PutObject(objectName, fd)
- // c.Assert(err, IsNil)
- // endingTime = time.Now().UnixNano() / 1000 / 1000
- // costT = endingTime - start
- // costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
- // testLogger.Println(traffic, maxTraffic, contentLength, costT, costV)
- // c.Assert((costV < maxTraffic), Equals, true)
- // get object to file
- newFile := "test-file-" + RandStr(10)
- start = time.Now().UnixNano() / 1000 / 1000
- err = bucket.GetObjectToFile(objectName, newFile, TrafficLimitHeader(traffic))
- c.Assert(err, IsNil)
- endingTime = time.Now().UnixNano() / 1000 / 1000
- costT = endingTime - start
- costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
- c.Assert((costV < maxTraffic), Equals, true)
- os.Remove(newFile)
- // append object
- newFile = "test-file-" + RandStr(10)
- objectKey := objectNamePrefix + RandStr(8)
- var nextPos int64
- fd, err = os.Open(localFile)
- c.Assert(err, IsNil)
- defer fd.Close()
- start = time.Now().UnixNano() / 1000 / 1000
- nextPos, err = bucket.AppendObject(objectKey, strings.NewReader(RandStr(18)), nextPos)
- c.Assert(err, IsNil)
- var respAppendHeader http.Header
- nextPos, err = bucket.AppendObject(objectKey, fd, nextPos, TrafficLimitHeader(traffic), GetResponseHeader(&respAppendHeader))
- c.Assert(err, IsNil)
- endingTime = time.Now().UnixNano() / 1000 / 1000
- costT = endingTime - start
- costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
- c.Assert((costV < maxTraffic), Equals, true)
- qosDelayTime = GetQosDelayTime(respAppendHeader)
- c.Assert(len(qosDelayTime) > 0, Equals, true)
- err = bucket.GetObjectToFile(objectKey, newFile, TrafficLimitHeader(traffic))
- c.Assert(err, IsNil)
- err = bucket.DeleteObject(objectKey)
- c.Assert(err, IsNil)
- os.Remove(newFile)
- // put object with url
- fd, err = os.Open(localFile)
- c.Assert(err, IsNil)
- defer fd.Close()
- strURL, err := bucket.SignURL(objectName, HTTPPut, 60, TrafficLimitParam(traffic))
- start = time.Now().UnixNano() / 1000 / 1000
- err = bucket.PutObjectWithURL(strURL, fd)
- c.Assert(err, IsNil)
- endingTime = time.Now().UnixNano() / 1000 / 1000
- costT = endingTime - start
- costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
- c.Assert((costV < maxTraffic), Equals, true)
- // get object with url
- newFile = "test-file-" + RandStr(10)
- strURL, err = bucket.SignURL(objectName, HTTPGet, 60, TrafficLimitParam(traffic))
- c.Assert(err, IsNil)
- start = time.Now().UnixNano() / 1000 / 1000
- err = bucket.GetObjectToFileWithURL(strURL, newFile)
- c.Assert(err, IsNil)
- endingTime = time.Now().UnixNano() / 1000 / 1000
- costT = endingTime - start
- costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
- c.Assert((costV < maxTraffic), Equals, true)
- os.Remove(newFile)
- // copy object
- destObjectName := objectNamePrefix + RandStr(8)
- _, err = bucket.CopyObject(objectName, destObjectName, TrafficLimitHeader(traffic))
- c.Assert(err, IsNil)
- err = bucket.DeleteObject(destObjectName)
- c.Assert(err, IsNil)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestBucketTrafficLimitUpload(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- var traffic int64 = 819220 // 100KB
- maxTraffic := traffic * 120 / 100
- contentLength := 500 * 1024
- var fileName = "test-file-" + RandStr(8)
- objectName := objectNamePrefix + RandStr(8)
- content := RandStr(contentLength)
- CreateFile(fileName, content, c)
- chunks, err := SplitFileByPartNum(fileName, 3)
- c.Assert(err, IsNil)
- options := []Option{
- Expires(futureDate), Meta("my", "myprop"),
- }
- fd, err := os.Open(fileName)
- c.Assert(err, IsNil)
- defer fd.Close()
- imur, err := bucket.InitiateMultipartUpload(objectName, options...)
- c.Assert(err, IsNil)
- var parts []UploadPart
- start := time.Now().UnixNano() / 1000 / 1000
- for _, chunk := range chunks {
- fd.Seek(chunk.Offset, os.SEEK_SET)
- part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number, TrafficLimitHeader(traffic))
- c.Assert(err, IsNil)
- parts = append(parts, part)
- }
- _, err = bucket.CompleteMultipartUpload(imur, parts)
- c.Assert(err, IsNil)
- endingTime := time.Now().UnixNano() / 1000 / 1000
- costT := endingTime - start
- costV := int64(contentLength) * 8 * 1000 / costT // B * 8 * 1000 / Millisecond = bit/s
- c.Assert((costV < maxTraffic), Equals, true)
- os.Remove(fileName)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestPutObjectWithForbidOverWrite(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- contentLength := 1024
- objectName := objectNamePrefix + RandStr(8)
- content := RandStr(contentLength)
- // first put success
- err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(true))
- c.Assert(err, IsNil)
- // second put failure with ForbidOverWrite true
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(true), GetResponseHeader(&respHeader))
- c.Assert(err, NotNil)
- // third put success with ForbidOverWrite false
- err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(false))
- c.Assert(err, IsNil)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestCopyObjectWithForbidOverWrite(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- contentLength := 1024
- objectName := objectNamePrefix + RandStr(8)
- content := RandStr(contentLength)
- err = bucket.PutObject(objectName, strings.NewReader(content))
- c.Assert(err, IsNil)
- // first copy success
- copyObjectName := objectName + "-copy"
- _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(true))
- c.Assert(err, IsNil)
- // second copy failure with ForbidOverWrite true
- var respHeader http.Header
- _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(true), GetResponseHeader(&respHeader))
- c.Assert(err, NotNil)
- // third copy success with ForbidOverWrite false
- _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(false))
- c.Assert(err, IsNil)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestDeleteObjectsWithSpecialCharacter(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- contentLength := 100
- objectName1 := objectNamePrefix + RandStr(8) + "<-->+&*\r%%"
- objectName2 := objectNamePrefix + RandStr(8) + "\r&*\r%%"
- //objectName2 := objectNamePrefix + RandStr(8) + "%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2Fetc%2Fprofile"
- //objectName2, err = url.QueryUnescape(objectName2)
- c.Assert(err, IsNil)
- content := RandStr(contentLength)
- err = bucket.PutObject(objectName1, strings.NewReader(content))
- c.Assert(err, IsNil)
- err = bucket.PutObject(objectName2, strings.NewReader(content))
- c.Assert(err, IsNil)
- // delete objectName1 objectName2
- objectKeys := []string{objectName1, objectName2}
- _, err = bucket.DeleteObjects(objectKeys)
- c.Assert(err, IsNil)
- // objectName1 is not exist
- exist, err := bucket.IsObjectExist(objectName1)
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, false)
- // objectName2 is not exist
- exist, err = bucket.IsObjectExist(objectName2)
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, false)
- ForceDeleteBucket(client, bucketName, c)
- }
- // TestGetObjectRangeBehavior
- func (s *OssBucketSuite) TestGetObjectRangeBehavior(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- objectName := objectNamePrefix + RandStr(8)
- objectLen := 1000
- objectValue := RandStr(objectLen)
- // Put
- err = bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Range 1
- options := []Option{
- RangeBehavior("standard"),
- Range(1000, 2000),
- }
- resp, err := bucket.GetObject(objectName, options...)
- c.Assert(resp, IsNil)
- c.Assert(err.(ServiceError).StatusCode, Equals, 416)
- // Range 2
- options = []Option{
- RangeBehavior("standard"),
- Range(0, 2000),
- }
- resp, err = bucket.GetObject(objectName, options...)
- c.Assert(err, IsNil)
- data, err := ioutil.ReadAll(resp)
- resp.Close()
- str := string(data)
- c.Assert(len(str), Equals, 1000)
- c.Assert(resp.(*Response).StatusCode, Equals, 206)
- // Range 3
- options = []Option{
- RangeBehavior("standard"),
- Range(500, 2000),
- }
- resp, err = bucket.GetObject(objectName, options...)
- c.Assert(err, IsNil)
- data, err = ioutil.ReadAll(resp)
- resp.Close()
- str = string(data)
- c.Assert(len(str), Equals, 500)
- c.Assert(resp.(*Response).StatusCode, Equals, 206)
- ForceDeleteBucket(client, bucketName, c)
- }
- // RangeBehavior is an option to set Range value, such as "standard"
- func MyRangeBehavior(value string) Option {
- return SetHeader(HTTPHeaderOssRangeBehavior, value)
- }
- // TestUserSetHeader
- func (s *OssBucketSuite) TestSupportUserSetHeader(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- objectName := objectNamePrefix + RandStr(8)
- objectLen := 1000
- objectValue := RandStr(objectLen)
- // Put
- err = bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Range 1
- options := []Option{
- MyRangeBehavior("standard"),
- Range(1000, 2000),
- }
- resp, err := bucket.GetObject(objectName, options...)
- c.Assert(resp, IsNil)
- c.Assert(err.(ServiceError).StatusCode, Equals, 416)
- // Range 2
- options = []Option{
- MyRangeBehavior("standard"),
- Range(0, 2000),
- }
- resp, err = bucket.GetObject(objectName, options...)
- c.Assert(err, IsNil)
- data, err := ioutil.ReadAll(resp)
- resp.Close()
- str := string(data)
- c.Assert(len(str), Equals, 1000)
- c.Assert(resp.(*Response).StatusCode, Equals, 206)
- // Range 3
- options = []Option{
- MyRangeBehavior("standard"),
- Range(500, 2000),
- }
- resp, err = bucket.GetObject(objectName, options...)
- c.Assert(err, IsNil)
- data, err = ioutil.ReadAll(resp)
- resp.Close()
- str = string(data)
- c.Assert(len(str), Equals, 500)
- c.Assert(resp.(*Response).StatusCode, Equals, 206)
- ForceDeleteBucket(client, bucketName, c)
- }
- // user can set param
- func MyVersionId(value string) Option {
- return AddParam("versionId", value)
- }
- func (s *OssBucketSuite) TestSupportUserSetParam(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
- // put object v1
- objectName := objectNamePrefix + RandStr(8)
- contextV1 := RandStr(100)
- versionIdV1 := ""
- var respHeader http.Header
- err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV1 = GetVersionId(respHeader)
- c.Assert(len(versionIdV1) > 0, Equals, true)
- // put object v2
- contextV2 := RandStr(200)
- versionIdV2 := ""
- err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- versionIdV2 = GetVersionId(respHeader)
- c.Assert(len(versionIdV2) > 0, Equals, true)
- // check v1 and v2
- c.Assert(versionIdV1 != versionIdV2, Equals, true)
- // get object v1
- body, err := bucket.GetObject(objectName, MyVersionId(versionIdV1))
- c.Assert(err, IsNil)
- str, err := readBody(body)
- c.Assert(err, IsNil)
- body.Close()
- c.Assert(str, Equals, contextV1)
- // get object v2
- body, err = bucket.GetObject(objectName, MyVersionId(versionIdV2))
- c.Assert(err, IsNil)
- str, err = readBody(body)
- c.Assert(err, IsNil)
- body.Close()
- c.Assert(str, Equals, contextV2)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssBucketSuite) TestPutObjectWithKmsSm4(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- objectName := objectNamePrefix + RandStr(8)
- objectValue := RandStr(1024)
- bucketName := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- err = bucket.PutObject(objectName, strings.NewReader(objectValue), ServerSideEncryption("KMS"), ServerSideDataEncryption("SM4"))
- headers, err := bucket.GetObjectDetailedMeta(objectName)
- c.Assert(err, IsNil)
- c.Assert(headers.Get(HTTPHeaderOssServerSideEncryption), Equals, "KMS")
- c.Assert(headers.Get(HTTPHeaderOssServerSideDataEncryption), Equals, "SM4")
- c.Assert(err, IsNil)
- ForceDeleteBucket(client, bucketName, c)
- }
|