123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642 |
- // client test
- // use gocheck, install gocheck to execute "go get gopkg.in/check.v1",
- // see https://labix.org/gocheck
- package oss
- import (
- "encoding/json"
- "encoding/xml"
- "fmt"
- "io/ioutil"
- "log"
- "math/rand"
- "net"
- "net/http"
- "os"
- "reflect"
- "runtime"
- "strconv"
- "strings"
- "testing"
- "time"
- . "gopkg.in/check.v1"
- )
- // Test hooks up gocheck into the "go test" runner.
- func Test(t *testing.T) {
- TestingT(t)
- }
- type OssClientSuite struct{}
- var _ = Suite(&OssClientSuite{})
- var (
- // Endpoint/ID/Key
- endpoint = os.Getenv("OSS_TEST_ENDPOINT")
- accessID = os.Getenv("OSS_TEST_ACCESS_KEY_ID")
- accessKey = os.Getenv("OSS_TEST_ACCESS_KEY_SECRET")
- accountID = os.Getenv("OSS_TEST_ACCOUNT_ID")
- // Proxy
- proxyHost = os.Getenv("OSS_TEST_PROXY_HOST")
- proxyUser = os.Getenv("OSS_TEST_PROXY_USER")
- proxyPasswd = os.Getenv("OSS_TEST_PROXY_PASSWORD")
- // STS
- stsaccessID = os.Getenv("OSS_TEST_STS_ID")
- stsaccessKey = os.Getenv("OSS_TEST_STS_KEY")
- stsARN = os.Getenv("OSS_TEST_STS_ARN")
- // Credential
- credentialAccessID = os.Getenv("OSS_CREDENTIAL_KEY_ID")
- credentialAccessKey = os.Getenv("OSS_CREDENTIAL_KEY_SECRET")
- credentialUID = os.Getenv("OSS_CREDENTIAL_UID")
- )
- var (
- // prefix of bucket name for bucket ops test
- bucketNamePrefix = "go-sdk-test-bucket-"
- // bucket name for object ops test
- bucketName = bucketNamePrefix + RandLowStr(6)
- archiveBucketName = bucketNamePrefix + "arch-" + RandLowStr(6)
- // object name for object ops test
- objectNamePrefix = "go-sdk-test-object-"
- // sts region is one and only hangzhou
- stsRegion = "cn-hangzhou"
- // Credentials
- credentialBucketName = bucketNamePrefix + RandLowStr(6)
- )
- var (
- logPath = "go_sdk_test_" + time.Now().Format("20060102_150405") + ".log"
- testLogFile, _ = os.OpenFile(logPath, os.O_RDWR|os.O_CREATE, 0664)
- testLogger = log.New(testLogFile, "", log.Ldate|log.Ltime|log.Lshortfile)
- letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
- timeoutInOperation = 3 * time.Second
- )
- func RandStr(n int) string {
- b := make([]rune, n)
- randMarker := rand.New(rand.NewSource(time.Now().UnixNano()))
- for i := range b {
- b[i] = letters[randMarker.Intn(len(letters))]
- }
- return string(b)
- }
- func CreateFile(fileName, content string, c *C) {
- fout, err := os.Create(fileName)
- defer fout.Close()
- c.Assert(err, IsNil)
- _, err = fout.WriteString(content)
- c.Assert(err, IsNil)
- }
- func RandLowStr(n int) string {
- return strings.ToLower(RandStr(n))
- }
- func ForceDeleteBucket(client *Client, bucketName string, c *C) {
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- // Delete Object
- 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 Object Versions and DeleteMarks
- keyMarker := KeyMarker("")
- versionIdMarker := VersionIdMarker("")
- options := []Option{keyMarker, versionIdMarker}
- for {
- lor, err := bucket.ListObjectVersions(options...)
- if err != nil {
- break
- }
- for _, object := range lor.ObjectDeleteMarkers {
- err = bucket.DeleteObject(object.Key, VersionId(object.VersionId))
- c.Assert(err, IsNil)
- }
- for _, object := range lor.ObjectVersions {
- err = bucket.DeleteObject(object.Key, VersionId(object.VersionId))
- c.Assert(err, IsNil)
- }
- keyMarker = KeyMarker(lor.NextKeyMarker)
- versionIdMarker := VersionIdMarker(lor.NextVersionIdMarker)
- options = []Option{keyMarker, versionIdMarker}
- if !lor.IsTruncated {
- break
- }
- }
- // Delete Part
- keyMarker = KeyMarker("")
- uploadIDMarker := UploadIDMarker("")
- for {
- lmur, err := bucket.ListMultipartUploads(keyMarker, uploadIDMarker)
- c.Assert(err, IsNil)
- for _, upload := range lmur.Uploads {
- var imur = InitiateMultipartUploadResult{Bucket: bucketName,
- Key: upload.Key, UploadID: upload.UploadID}
- err = bucket.AbortMultipartUpload(imur)
- c.Assert(err, IsNil)
- }
- keyMarker = KeyMarker(lmur.NextKeyMarker)
- uploadIDMarker = UploadIDMarker(lmur.NextUploadIDMarker)
- if !lmur.IsTruncated {
- break
- }
- }
- // delete live channel
- strMarker := ""
- for {
- result, err := bucket.ListLiveChannel(Marker(strMarker))
- c.Assert(err, IsNil)
- for _, channel := range result.LiveChannel {
- err := bucket.DeleteLiveChannel(channel.Name)
- c.Assert(err, IsNil)
- }
- if result.IsTruncated {
- strMarker = result.NextMarker
- } else {
- break
- }
- }
- // Delete Bucket
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- // SetUpSuite runs once when the suite starts running
- func (s *OssClientSuite) SetUpSuite(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- lbr, err := client.ListBuckets(Prefix(bucketNamePrefix), MaxKeys(1000))
- c.Assert(err, IsNil)
- for _, bucket := range lbr.Buckets {
- ForceDeleteBucket(client, bucket.Name, c)
- }
- testLogger.Println("test client started")
- }
- // TearDownSuite runs before each test or benchmark starts running
- func (s *OssClientSuite) TearDownSuite(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- lbr, err := client.ListBuckets(Prefix(bucketNamePrefix), MaxKeys(1000))
- c.Assert(err, IsNil)
- for _, bucket := range lbr.Buckets {
- s.deleteBucket(client, bucket.Name, c)
- }
- testLogger.Println("test client completed")
- }
- func (s *OssClientSuite) deleteBucket(client *Client, bucketName string, c *C) {
- ForceDeleteBucket(client, bucketName, c)
- }
- // SetUpTest runs after each test or benchmark runs
- func (s *OssClientSuite) SetUpTest(c *C) {
- }
- // TearDownTest runs once after all tests or benchmarks have finished running
- func (s *OssClientSuite) TearDownTest(c *C) {
- }
- // TestCreateBucket
- func (s *OssClientSuite) TestCreateBucket(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Create
- client.DeleteBucket(bucketNameTest)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- //sleep 3 seconds after create bucket
- time.Sleep(timeoutInOperation)
- // verify bucket is exist
- found, err := client.IsBucketExist(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(found, Equals, true)
- res, err := client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // CreateBucket creates with ACLPublicRead
- err = client.CreateBucket(bucketNameTest, ACL(ACLPublicRead))
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPublicRead))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // ACLPublicReadWrite
- err = client.CreateBucket(bucketNameTest, ACL(ACLPublicReadWrite))
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPublicReadWrite))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // ACLPrivate
- err = client.CreateBucket(bucketNameTest, ACL(ACLPrivate))
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- // Delete
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- // Create bucket with configuration and test GetBucketInfo
- for _, storage := range []StorageClassType{StorageStandard, StorageIA, StorageArchive, StorageColdArchive} {
- bucketNameTest := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketNameTest, StorageClass(storage), ACL(ACLPublicRead))
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err := client.GetBucketInfo(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.BucketInfo.Name, Equals, bucketNameTest)
- c.Assert(res.BucketInfo.StorageClass, Equals, string(storage))
- c.Assert(res.BucketInfo.ACL, Equals, string(ACLPublicRead))
- // Delete
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // Error put bucket with configuration
- err = client.CreateBucket("ERRORBUCKETNAME", StorageClass(StorageArchive))
- c.Assert(err, NotNil)
- // Create bucket with configuration and test ListBuckets
- for _, storage := range []StorageClassType{StorageStandard, StorageIA, StorageArchive, StorageColdArchive} {
- bucketNameTest := bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketNameTest, StorageClass(storage))
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err := client.GetBucketInfo(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.BucketInfo.Name, Equals, bucketNameTest)
- c.Assert(res.BucketInfo.StorageClass, Equals, string(storage))
- // Delete
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- }
- func (s *OssClientSuite) TestCreateBucketRedundancyType(c *C) {
- bucketNameTest := bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // CreateBucket creates without property
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- client.DeleteBucket(bucketNameTest)
- time.Sleep(timeoutInOperation)
- // CreateBucket creates with RedundancyZRS
- err = client.CreateBucket(bucketNameTest, RedundancyType(RedundancyZRS))
- c.Assert(err, IsNil)
- res, err := client.GetBucketInfo(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.BucketInfo.RedundancyType, Equals, string(RedundancyZRS))
- client.DeleteBucket(bucketNameTest)
- time.Sleep(timeoutInOperation)
- // CreateBucket creates with RedundancyLRS
- err = client.CreateBucket(bucketNameTest, RedundancyType(RedundancyLRS))
- c.Assert(err, IsNil)
- res, err = client.GetBucketInfo(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.BucketInfo.RedundancyType, Equals, string(RedundancyLRS))
- c.Assert(res.BucketInfo.StorageClass, Equals, string(StorageStandard))
- client.DeleteBucket(bucketNameTest)
- time.Sleep(timeoutInOperation)
- // CreateBucket creates with ACLPublicRead RedundancyZRS
- err = client.CreateBucket(bucketNameTest, ACL(ACLPublicRead), RedundancyType(RedundancyZRS))
- c.Assert(err, IsNil)
- res, err = client.GetBucketInfo(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.BucketInfo.RedundancyType, Equals, string(RedundancyZRS))
- c.Assert(res.BucketInfo.ACL, Equals, string(ACLPublicRead))
- client.DeleteBucket(bucketNameTest)
- }
- // TestCreateBucketNegative
- func (s *OssClientSuite) TestCreateBucketNegative(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Bucket name invalid
- err = client.CreateBucket("xx")
- c.Assert(err, NotNil)
- err = client.CreateBucket("XXXX")
- c.Assert(err, NotNil)
- testLogger.Println(err)
- err = client.CreateBucket("_bucket")
- c.Assert(err, NotNil)
- testLogger.Println(err)
- // ACL invalid
- err = client.CreateBucket(bucketNamePrefix+RandLowStr(6), ACL("InvaldAcl"))
- c.Assert(err, NotNil)
- testLogger.Println(err)
- }
- // TestDeleteBucket
- func (s *OssClientSuite) TestDeleteBucket(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Create
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Check
- found, err := client.IsBucketExist(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(found, Equals, true)
- // Delete
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Check
- found, err = client.IsBucketExist(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(found, Equals, false)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, NotNil)
- }
- // TestDeleteBucketNegative
- func (s *OssClientSuite) TestDeleteBucketNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Bucket name invalid
- err = client.DeleteBucket("xx")
- c.Assert(err, NotNil)
- err = client.DeleteBucket("XXXX")
- c.Assert(err, NotNil)
- err = client.DeleteBucket("_bucket")
- c.Assert(err, NotNil)
- // Delete no exist bucket
- err = client.DeleteBucket("notexist")
- c.Assert(err, NotNil)
- // No permission to delete, this ak/sk for js sdk
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- accessID := "<accessKeyId>"
- accessKey := "<accessKeySecret>"
- clientOtherUser, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = clientOtherUser.DeleteBucket(bucketNameTest)
- c.Assert(err, NotNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestListBucket
- func (s *OssClientSuite) TestListBucket(c *C) {
- var prefix = bucketNamePrefix + RandLowStr(6)
- var bucketNameLbOne = prefix + "tlb1"
- var bucketNameLbTwo = prefix + "tlb2"
- var bucketNameLbThree = prefix + "tlb3"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // CreateBucket
- err = client.CreateBucket(bucketNameLbOne)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameLbTwo)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameLbThree)
- c.Assert(err, IsNil)
- // ListBuckets, specified prefix
- var respHeader http.Header
- lbr, err := client.ListBuckets(Prefix(prefix), MaxKeys(2), GetResponseHeader(&respHeader))
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- c.Assert(err, IsNil)
- c.Assert(len(lbr.Buckets), Equals, 2)
- // ListBuckets, specified max keys
- lbr, err = client.ListBuckets(MaxKeys(2))
- c.Assert(err, IsNil)
- c.Assert(len(lbr.Buckets), Equals, 2)
- // ListBuckets, specified max keys
- lbr, err = client.ListBuckets(Marker(bucketNameLbOne), MaxKeys(1))
- c.Assert(err, IsNil)
- c.Assert(len(lbr.Buckets), Equals, 1)
- // ListBuckets, specified max keys
- lbr, err = client.ListBuckets(Marker(bucketNameLbOne))
- c.Assert(err, IsNil)
- c.Assert(len(lbr.Buckets) >= 2, Equals, true)
- // DeleteBucket
- err = client.DeleteBucket(bucketNameLbOne)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameLbTwo)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameLbThree)
- c.Assert(err, IsNil)
- }
- // TestListBucket
- func (s *OssClientSuite) TestIsBucketExist(c *C) {
- var prefix = bucketNamePrefix + RandLowStr(6)
- var bucketNameLbOne = prefix + "tibe1"
- var bucketNameLbTwo = prefix + "tibe11"
- var bucketNameLbThree = prefix + "tibe111"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // CreateBucket
- err = client.CreateBucket(bucketNameLbOne)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameLbTwo)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameLbThree)
- c.Assert(err, IsNil)
- // Exist
- exist, err := client.IsBucketExist(bucketNameLbTwo)
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- exist, err = client.IsBucketExist(bucketNameLbThree)
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- exist, err = client.IsBucketExist(bucketNameLbOne)
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, true)
- // Not exist
- exist, err = client.IsBucketExist(prefix + "tibe")
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, false)
- exist, err = client.IsBucketExist(prefix + "tibe1111")
- c.Assert(err, IsNil)
- c.Assert(exist, Equals, false)
- // Negative
- exist, err = client.IsBucketExist("BucketNameInvalid")
- c.Assert(err, NotNil)
- // DeleteBucket
- err = client.DeleteBucket(bucketNameLbOne)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameLbTwo)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameLbThree)
- c.Assert(err, IsNil)
- }
- // TestSetBucketAcl
- func (s *OssClientSuite) TestSetBucketAcl(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Private
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- res, err := client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- // Set ACL_PUBLIC_R
- err = client.SetBucketACL(bucketNameTest, ACLPublicRead)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPublicRead))
- // Set ACL_PUBLIC_RW
- err = client.SetBucketACL(bucketNameTest, ACLPublicReadWrite)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPublicReadWrite))
- // Set ACL_PUBLIC_RW
- err = client.SetBucketACL(bucketNameTest, ACLPrivate)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketAclNegative
- func (s *OssClientSuite) TestBucketAclNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.SetBucketACL(bucketNameTest, "InvalidACL")
- c.Assert(err, NotNil)
- testLogger.Println(err)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestGetBucketAcl
- func (s *OssClientSuite) TestGetBucketAcl(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Private
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err := client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // PublicRead
- err = client.CreateBucket(bucketNameTest, ACL(ACLPublicRead))
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPublicRead))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // PublicReadWrite
- err = client.CreateBucket(bucketNameTest, ACL(ACLPublicReadWrite))
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPublicReadWrite))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestGetBucketAcl
- func (s *OssClientSuite) TestGetBucketLocation(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Private
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- loc, err := client.GetBucketLocation(bucketNameTest)
- c.Assert(strings.HasPrefix(loc, "oss-"), Equals, true)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestGetBucketLocationNegative
- func (s *OssClientSuite) TestGetBucketLocationNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Not exist
- _, err = client.GetBucketLocation(bucketNameTest)
- c.Assert(err, NotNil)
- // Not exist
- _, err = client.GetBucketLocation("InvalidBucketName_")
- c.Assert(err, NotNil)
- }
- // TestSetBucketLifecycle
- func (s *OssClientSuite) TestSetBucketLifecycle(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var rule1 = BuildLifecycleRuleByDate("rule1", "one", true, 2015, 11, 11)
- var rule2 = BuildLifecycleRuleByDays("rule2", "two", true, 3)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- // Set single rule
- var rules = []LifecycleRule{rule1}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- // Double set rule
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- res, err := client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(res.Rules), Equals, 1)
- c.Assert(res.Rules[0].ID, Equals, "rule1")
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- // Set two rules
- rules = []LifecycleRule{rule1, rule2}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- // Eliminate effect of cache
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(res.Rules), Equals, 2)
- c.Assert(res.Rules[0].ID, Equals, "rule1")
- c.Assert(res.Rules[1].ID, Equals, "rule2")
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketLifecycleNew
- func (s *OssClientSuite) TestSetBucketLifecycleNew(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- //invalid status of lifecyclerule
- expiration := LifecycleExpiration{
- Days: 30,
- }
- rule := LifecycleRule{
- ID: "rule1",
- Prefix: "one",
- Status: "Invalid",
- Expiration: &expiration,
- }
- rules := []LifecycleRule{rule}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, NotNil)
- //invalid value of CreatedBeforeDate
- expiration = LifecycleExpiration{
- CreatedBeforeDate: RandStr(10),
- }
- rule = LifecycleRule{
- ID: "rule1",
- Prefix: "one",
- Status: "Enabled",
- Expiration: &expiration,
- }
- rules = []LifecycleRule{rule}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, NotNil)
- //invalid value of Days
- abortMPU := LifecycleAbortMultipartUpload{
- Days: -30,
- }
- rule = LifecycleRule{
- ID: "rule1",
- Prefix: "one",
- Status: "Enabled",
- AbortMultipartUpload: &abortMPU,
- }
- rules = []LifecycleRule{rule}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, NotNil)
- expiration = LifecycleExpiration{
- CreatedBeforeDate: "2015-11-11T00:00:00.000Z",
- }
- rule1 := LifecycleRule{
- ID: "rule1",
- Prefix: "one",
- Status: "Enabled",
- Expiration: &expiration,
- }
- abortMPU = LifecycleAbortMultipartUpload{
- Days: 30,
- }
- rule2 := LifecycleRule{
- ID: "rule2",
- Prefix: "two",
- Status: "Enabled",
- Expiration: &expiration,
- AbortMultipartUpload: &abortMPU,
- }
- transition1 := LifecycleTransition{
- Days: 3,
- StorageClass: StorageIA,
- }
- transition2 := LifecycleTransition{
- Days: 30,
- StorageClass: StorageArchive,
- }
- transitions := []LifecycleTransition{transition1, transition2}
- rule3 := LifecycleRule{
- ID: "rule3",
- Prefix: "three",
- Status: "Enabled",
- AbortMultipartUpload: &abortMPU,
- Transitions: transitions,
- }
- // Set single rule
- rules = []LifecycleRule{rule1}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- res, err := client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(res.Rules), Equals, 1)
- c.Assert(res.Rules[0].ID, Equals, "rule1")
- c.Assert(res.Rules[0].Expiration, NotNil)
- c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- // Set two rule: rule1 and rule2
- rules = []LifecycleRule{rule1, rule2}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- res, err = client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(res.Rules), Equals, 2)
- c.Assert(res.Rules[0].ID, Equals, "rule1")
- c.Assert(res.Rules[0].Expiration, NotNil)
- c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
- c.Assert(res.Rules[1].ID, Equals, "rule2")
- c.Assert(res.Rules[1].Expiration, NotNil)
- c.Assert(res.Rules[1].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
- c.Assert(res.Rules[1].AbortMultipartUpload, NotNil)
- c.Assert(res.Rules[1].AbortMultipartUpload.Days, Equals, 30)
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- // Set two rule: rule2 and rule3
- rules = []LifecycleRule{rule2, rule3}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- res, err = client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(res.Rules), Equals, 2)
- c.Assert(res.Rules[0].ID, Equals, "rule2")
- c.Assert(res.Rules[0].Expiration, NotNil)
- c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
- c.Assert(res.Rules[0].AbortMultipartUpload, NotNil)
- c.Assert(res.Rules[0].AbortMultipartUpload.Days, Equals, 30)
- c.Assert(res.Rules[1].ID, Equals, "rule3")
- c.Assert(res.Rules[1].AbortMultipartUpload, NotNil)
- c.Assert(res.Rules[1].AbortMultipartUpload.Days, Equals, 30)
- c.Assert(len(res.Rules[1].Transitions), Equals, 2)
- c.Assert(res.Rules[1].Transitions[0].StorageClass, Equals, StorageIA)
- c.Assert(res.Rules[1].Transitions[0].Days, Equals, 3)
- c.Assert(res.Rules[1].Transitions[1].StorageClass, Equals, StorageArchive)
- c.Assert(res.Rules[1].Transitions[1].Days, Equals, 30)
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- // Set two rule: rule1 and rule3
- rules = []LifecycleRule{rule1, rule3}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- res, err = client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(res.Rules), Equals, 2)
- c.Assert(res.Rules[0].ID, Equals, "rule1")
- c.Assert(res.Rules[0].Expiration, NotNil)
- c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
- c.Assert(res.Rules[1].ID, Equals, "rule3")
- c.Assert(res.Rules[1].AbortMultipartUpload, NotNil)
- c.Assert(res.Rules[1].AbortMultipartUpload.Days, Equals, 30)
- c.Assert(len(res.Rules[1].Transitions), Equals, 2)
- c.Assert(res.Rules[1].Transitions[0].StorageClass, Equals, StorageIA)
- c.Assert(res.Rules[1].Transitions[0].Days, Equals, 3)
- c.Assert(res.Rules[1].Transitions[1].StorageClass, Equals, StorageArchive)
- c.Assert(res.Rules[1].Transitions[1].Days, Equals, 30)
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- // Set three rules
- rules = []LifecycleRule{rule1, rule2, rule3}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- res, err = client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(res.Rules), Equals, 3)
- c.Assert(res.Rules[0].ID, Equals, "rule1")
- c.Assert(res.Rules[0].Expiration, NotNil)
- c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
- c.Assert(res.Rules[1].ID, Equals, "rule2")
- c.Assert(res.Rules[1].Expiration, NotNil)
- c.Assert(res.Rules[1].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
- c.Assert(res.Rules[1].AbortMultipartUpload, NotNil)
- c.Assert(res.Rules[1].AbortMultipartUpload.Days, Equals, 30)
- c.Assert(res.Rules[2].ID, Equals, "rule3")
- c.Assert(res.Rules[2].AbortMultipartUpload, NotNil)
- c.Assert(res.Rules[2].AbortMultipartUpload.Days, Equals, 30)
- c.Assert(len(res.Rules[2].Transitions), Equals, 2)
- c.Assert(res.Rules[2].Transitions[0].StorageClass, Equals, StorageIA)
- c.Assert(res.Rules[2].Transitions[0].Days, Equals, 3)
- c.Assert(res.Rules[2].Transitions[1].StorageClass, Equals, StorageArchive)
- c.Assert(res.Rules[2].Transitions[1].Days, Equals, 30)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketLifecycleAboutVersionObject
- func (s *OssClientSuite) TestSetBucketLifecycleAboutVersionObject(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- deleteMark := true
- expiration := LifecycleExpiration{
- ExpiredObjectDeleteMarker: &deleteMark,
- }
- versionExpiration := LifecycleVersionExpiration{
- NoncurrentDays: 20,
- }
- versionTransition := LifecycleVersionTransition{
- NoncurrentDays: 10,
- StorageClass: "IA",
- }
- rule := LifecycleRule{
- Status: "Enabled",
- Expiration: &expiration,
- NonVersionExpiration: &versionExpiration,
- NonVersionTransition: &versionTransition,
- }
- rules := []LifecycleRule{rule}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- res, err := client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.Rules[0].Expiration, NotNil)
- c.Assert(res.Rules[0].Expiration.Days, Equals, 0)
- c.Assert(res.Rules[0].Expiration.Date, Equals, "")
- c.Assert(*(res.Rules[0].Expiration.ExpiredObjectDeleteMarker), Equals, true)
- c.Assert(res.Rules[0].NonVersionExpiration.NoncurrentDays, Equals, 20)
- c.Assert(res.Rules[0].NonVersionTransition.NoncurrentDays, Equals, 10)
- c.Assert(res.Rules[0].NonVersionTransition.StorageClass, Equals, StorageClassType("IA"))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketLifecycleAboutVersionObject
- func (s *OssClientSuite) TestSetBucketLifecycleAboutVersionObjectError(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- deleteMark := true
- expiration := LifecycleExpiration{
- ExpiredObjectDeleteMarker: &deleteMark,
- }
- versionExpiration := LifecycleVersionExpiration{
- NoncurrentDays: 20,
- }
- versionTransition := LifecycleVersionTransition{
- NoncurrentDays: 10,
- StorageClass: "IA",
- }
- // NonVersionTransition and NonVersionTransitions can not both have value
- rule := LifecycleRule{
- Status: "Enabled",
- Expiration: &expiration,
- NonVersionExpiration: &versionExpiration,
- NonVersionTransition: &versionTransition,
- NonVersionTransitions: []LifecycleVersionTransition{versionTransition},
- }
- rules := []LifecycleRule{rule}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, NotNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketLifecycleAboutVersionObject
- func (s *OssClientSuite) TestSetBucketLifecycleAboutVersionObjectNew(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- deleteMark := true
- expiration := LifecycleExpiration{
- ExpiredObjectDeleteMarker: &deleteMark,
- }
- versionExpiration := LifecycleVersionExpiration{
- NoncurrentDays: 20,
- }
- versionTransition1 := LifecycleVersionTransition{
- NoncurrentDays: 10,
- StorageClass: "IA",
- }
- versionTransition2 := LifecycleVersionTransition{
- NoncurrentDays: 20,
- StorageClass: "ColdArchive",
- }
- rule := LifecycleRule{
- Status: "Enabled",
- Expiration: &expiration,
- NonVersionExpiration: &versionExpiration,
- NonVersionTransitions: []LifecycleVersionTransition{versionTransition1, versionTransition2},
- }
- rules := []LifecycleRule{rule}
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- res, err := client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.Rules[0].Expiration, NotNil)
- c.Assert(res.Rules[0].Expiration.Days, Equals, 0)
- c.Assert(res.Rules[0].Expiration.Date, Equals, "")
- c.Assert(*(res.Rules[0].Expiration.ExpiredObjectDeleteMarker), Equals, true)
- c.Assert(res.Rules[0].NonVersionExpiration.NoncurrentDays, Equals, 20)
- c.Assert(res.Rules[0].NonVersionTransition.NoncurrentDays, Equals, 10)
- c.Assert(res.Rules[0].NonVersionTransition.StorageClass, Equals, StorageClassType("IA"))
- c.Assert(len(res.Rules[0].NonVersionTransitions),Equals, 2)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestDeleteBucketLifecycle
- func (s *OssClientSuite) TestDeleteBucketLifecycle(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var rule1 = BuildLifecycleRuleByDate("rule1", "one", true, 2015, 11, 11)
- var rule2 = BuildLifecycleRuleByDays("rule2", "two", true, 3)
- var rules = []LifecycleRule{rule1, rule2}
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- //time.Sleep(timeoutInOperation)
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, IsNil)
- //time.Sleep(timeoutInOperation)
- res, err := client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(res.Rules), Equals, 2)
- // Delete
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- //time.Sleep(timeoutInOperation)
- res, err = client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, NotNil)
- // Eliminate effect of cache
- //time.Sleep(timeoutInOperation)
- // Delete when not set
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketLifecycleNegative
- func (s *OssClientSuite) TestBucketLifecycleNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var rules = []LifecycleRule{}
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- // Set with no rule
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, NotNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- // Not exist
- err = client.SetBucketLifecycle(bucketNameTest, rules)
- c.Assert(err, NotNil)
- // Not exist
- _, err = client.GetBucketLifecycle(bucketNameTest)
- c.Assert(err, NotNil)
- // Not exist
- err = client.DeleteBucketLifecycle(bucketNameTest)
- c.Assert(err, NotNil)
- }
- // TestSetBucketReferer
- func (s *OssClientSuite) TestSetBucketReferer(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var referers = []string{"http://www.aliyun.com", "https://www.aliyun.com"}
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err := client.GetBucketReferer(bucketNameTest)
- c.Assert(res.AllowEmptyReferer, Equals, true)
- c.Assert(len(res.RefererList), Equals, 0)
- // Set referers
- err = client.SetBucketReferer(bucketNameTest, referers, false)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketReferer(bucketNameTest)
- c.Assert(res.AllowEmptyReferer, Equals, false)
- c.Assert(len(res.RefererList), Equals, 2)
- c.Assert(res.RefererList[0], Equals, "http://www.aliyun.com")
- c.Assert(res.RefererList[1], Equals, "https://www.aliyun.com")
- // Reset referer, referers empty
- referers = []string{""}
- err = client.SetBucketReferer(bucketNameTest, referers, true)
- c.Assert(err, IsNil)
- referers = []string{}
- err = client.SetBucketReferer(bucketNameTest, referers, true)
- c.Assert(err, IsNil)
- res, err = client.GetBucketReferer(bucketNameTest)
- c.Assert(res.AllowEmptyReferer, Equals, true)
- c.Assert(len(res.RefererList), Equals, 0)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketRefererNegative
- func (s *OssClientSuite) TestBucketRefererNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var referers = []string{""}
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Not exist
- _, err = client.GetBucketReferer(bucketNameTest)
- c.Assert(err, NotNil)
- testLogger.Println(err)
- // Not exist
- err = client.SetBucketReferer(bucketNameTest, referers, true)
- c.Assert(err, NotNil)
- testLogger.Println(err)
- }
- // TestSetBucketLogging
- func (s *OssClientSuite) TestSetBucketLogging(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var bucketNameTarget = bucketNameTest + "-target"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTarget)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Set logging
- err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", true)
- c.Assert(err, IsNil)
- // Reset
- err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", false)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err := client.GetBucketLogging(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.LoggingEnabled.TargetBucket, Equals, "")
- c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "")
- err = client.DeleteBucketLogging(bucketNameTest)
- c.Assert(err, IsNil)
- // Set to self
- err = client.SetBucketLogging(bucketNameTest, bucketNameTest, "prefix", true)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTarget)
- c.Assert(err, IsNil)
- }
- // TestDeleteBucketLogging
- func (s *OssClientSuite) TestDeleteBucketLogging(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var bucketNameTarget = bucketNameTest + "-target"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTarget)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Get when not set
- res, err := client.GetBucketLogging(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.LoggingEnabled.TargetBucket, Equals, "")
- c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "")
- // Set
- err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", true)
- c.Assert(err, IsNil)
- // Get
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketLogging(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.LoggingEnabled.TargetBucket, Equals, bucketNameTarget)
- c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "prefix")
- // Set
- err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", false)
- c.Assert(err, IsNil)
- // Get
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketLogging(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.LoggingEnabled.TargetBucket, Equals, "")
- c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "")
- // Delete
- err = client.DeleteBucketLogging(bucketNameTest)
- c.Assert(err, IsNil)
- // Get after delete
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketLogging(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.LoggingEnabled.TargetBucket, Equals, "")
- c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "")
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTarget)
- c.Assert(err, IsNil)
- }
- // TestSetBucketLoggingNegative
- func (s *OssClientSuite) TestSetBucketLoggingNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var bucketNameTarget = bucketNameTest + "-target"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Not exist
- _, err = client.GetBucketLogging(bucketNameTest)
- c.Assert(err, NotNil)
- // Not exist
- err = client.SetBucketLogging(bucketNameTest, "targetbucket", "prefix", true)
- c.Assert(err, NotNil)
- // Not exist
- err = client.DeleteBucketLogging(bucketNameTest)
- c.Assert(err, NotNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Target bucket not exist
- err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", true)
- c.Assert(err, NotNil)
- // Parameter invalid
- err = client.SetBucketLogging(bucketNameTest, "XXXX", "prefix", true)
- c.Assert(err, NotNil)
- err = client.SetBucketLogging(bucketNameTest, "xx", "prefix", true)
- c.Assert(err, NotNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketWebsite
- func (s *OssClientSuite) TestSetBucketWebsite(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var indexWebsite = "myindex.html"
- var errorWebsite = "myerror.html"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- // Set
- err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
- c.Assert(err, IsNil)
- // Double set
- err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
- c.Assert(err, IsNil)
- res, err := client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
- c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
- // Reset
- err = client.SetBucketWebsite(bucketNameTest, "your"+indexWebsite, "your"+errorWebsite)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.IndexDocument.Suffix, Equals, "your"+indexWebsite)
- c.Assert(res.ErrorDocument.Key, Equals, "your"+errorWebsite)
- err = client.DeleteBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- // Set after delete
- err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
- c.Assert(err, IsNil)
- // Eliminate effect of cache
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
- c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestDeleteBucketWebsite
- func (s *OssClientSuite) TestDeleteBucketWebsite(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var indexWebsite = "myindex.html"
- var errorWebsite = "myerror.html"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Get
- res, err := client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, NotNil)
- // Detele without set
- err = client.DeleteBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- // Set
- err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
- c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
- // Detele
- time.Sleep(timeoutInOperation)
- err = client.DeleteBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, NotNil)
- // Detele after delete
- err = client.DeleteBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketWebsiteNegative
- func (s *OssClientSuite) TestSetBucketWebsiteNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var indexWebsite = "myindex.html"
- var errorWebsite = "myerror.html"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- // Not exist
- _, err = client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, NotNil)
- err = client.DeleteBucketWebsite(bucketNameTest)
- c.Assert(err, NotNil)
- err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
- c.Assert(err, NotNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- // Set
- time.Sleep(timeoutInOperation)
- err = client.SetBucketWebsite(bucketNameTest, "myindex", "myerror")
- c.Assert(err, IsNil)
- res, err := client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.IndexDocument.Suffix, Equals, "myindex")
- c.Assert(res.ErrorDocument.Key, Equals, "myerror")
- // Detele
- err = client.DeleteBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- _, err = client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, NotNil)
- // Detele after delete
- err = client.DeleteBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketWebsiteDetail
- func (s *OssClientSuite) TestSetBucketWebsiteDetail(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var indexWebsite = "myindex.html"
- var errorWebsite = "myerror.html"
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- btrue := true
- bfalse := false
- // Define one routing rule
- ruleOk := RoutingRule{
- RuleNumber: 1,
- Condition: Condition{
- KeyPrefixEquals: "",
- HTTPErrorCodeReturnedEquals: 404,
- },
- Redirect: Redirect{
- RedirectType: "Mirror",
- // PassQueryString: &btrue, // set default value
- MirrorURL: "http://www.test.com/",
- // MirrorPassQueryString:&btrue, // set default value
- // MirrorFollowRedirect:&bfalse, // set default value
- // MirrorCheckMd5:&bfalse, // set default value
- MirrorHeaders: MirrorHeaders{
- // PassAll:&bfalse, // set default value
- Pass: []string{"myheader-key1", "myheader-key2"},
- Remove: []string{"myheader-key3", "myheader-key4"},
- Set: []MirrorHeaderSet{
- MirrorHeaderSet{
- Key: "myheader-key5",
- Value: "myheader-value5",
- },
- },
- },
- },
- }
- // Define array routing rule
- ruleArrOk := []RoutingRule{
- RoutingRule{
- RuleNumber: 2,
- Condition: Condition{
- KeyPrefixEquals: "abc/",
- HTTPErrorCodeReturnedEquals: 404,
- IncludeHeader: []IncludeHeader{
- IncludeHeader{
- Key: "host",
- Equals: "test.oss-cn-beijing-internal.aliyuncs.com",
- },
- },
- },
- Redirect: Redirect{
- RedirectType: "AliCDN",
- Protocol: "http",
- HostName: "www.test.com",
- PassQueryString: &bfalse,
- ReplaceKeyWith: "prefix/${key}.suffix",
- HttpRedirectCode: 301,
- },
- },
- RoutingRule{
- RuleNumber: 3,
- Condition: Condition{
- KeyPrefixEquals: "",
- HTTPErrorCodeReturnedEquals: 404,
- },
- Redirect: Redirect{
- RedirectType: "Mirror",
- PassQueryString: &btrue,
- MirrorURL: "http://www.test.com/",
- MirrorPassQueryString: &btrue,
- MirrorFollowRedirect: &bfalse,
- MirrorCheckMd5: &bfalse,
- MirrorHeaders: MirrorHeaders{
- PassAll: &btrue,
- Pass: []string{"myheader-key1", "myheader-key2"},
- Remove: []string{"myheader-key3", "myheader-key4"},
- Set: []MirrorHeaderSet{
- MirrorHeaderSet{
- Key: "myheader-key5",
- Value: "myheader-value5",
- },
- },
- },
- },
- },
- }
- // Set one routing rule
- wxmlOne := WebsiteXML{}
- wxmlOne.RoutingRules = append(wxmlOne.RoutingRules, ruleOk)
- var responseHeader http.Header
- err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlOne, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- res, err := client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.RoutingRules[0].Redirect.RedirectType, Equals, "Mirror")
- c.Assert(*res.RoutingRules[0].Redirect.PassQueryString, Equals, false)
- c.Assert(*res.RoutingRules[0].Redirect.MirrorPassQueryString, Equals, false)
- c.Assert(*res.RoutingRules[0].Redirect.MirrorFollowRedirect, Equals, true)
- c.Assert(*res.RoutingRules[0].Redirect.MirrorCheckMd5, Equals, false)
- c.Assert(*res.RoutingRules[0].Redirect.MirrorHeaders.PassAll, Equals, false)
- // Set one routing rule and IndexDocument, IndexDocument
- wxml := WebsiteXML{
- IndexDocument: IndexDocument{Suffix: indexWebsite},
- ErrorDocument: ErrorDocument{Key: errorWebsite},
- }
- wxml.RoutingRules = append(wxml.RoutingRules, ruleOk)
- err = client.SetBucketWebsiteDetail(bucketNameTest, wxml, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- res, err = client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
- c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
- c.Assert(res.RoutingRules[0].Redirect.RedirectType, Equals, "Mirror")
- // Set array routing rule
- wxml.RoutingRules = append(wxml.RoutingRules, ruleArrOk...)
- err = client.SetBucketWebsiteDetail(bucketNameTest, wxml, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- res, err = client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
- c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
- c.Assert(len(res.RoutingRules), Equals, 3)
- c.Assert(res.RoutingRules[1].Redirect.RedirectType, Equals, "AliCDN")
- c.Assert(*res.RoutingRules[2].Redirect.MirrorPassQueryString, Equals, true)
- c.Assert(*res.RoutingRules[2].Redirect.MirrorFollowRedirect, Equals, false)
- // Define one error routing rule
- ruleErr := RoutingRule{
- RuleNumber: 1,
- Redirect: Redirect{
- RedirectType: "Mirror",
- PassQueryString: &btrue,
- },
- }
- // Define array error routing rule
- rulesErrArr := []RoutingRule{
- RoutingRule{
- RuleNumber: 1,
- Redirect: Redirect{
- RedirectType: "Mirror",
- PassQueryString: &btrue,
- },
- },
- RoutingRule{
- RuleNumber: 2,
- Redirect: Redirect{
- RedirectType: "Mirror",
- PassQueryString: &btrue,
- },
- },
- }
- ruleIntErr := RoutingRule{
- // RuleNumber:0, // set NULL value
- Condition: Condition{
- KeyPrefixEquals: "",
- HTTPErrorCodeReturnedEquals: 404,
- },
- Redirect: Redirect{
- RedirectType: "Mirror",
- // PassQueryString: &btrue, // set default value
- MirrorURL: "http://www.test.com/",
- // MirrorPassQueryString:&btrue, // set default value
- // MirrorFollowRedirect:&bfalse, // set default value
- // MirrorCheckMd5:&bfalse, // set default value
- MirrorHeaders: MirrorHeaders{
- // PassAll:&bfalse, // set default value
- Pass: []string{"myheader-key1", "myheader-key2"},
- Remove: []string{"myheader-key3", "myheader-key4"},
- Set: []MirrorHeaderSet{
- MirrorHeaderSet{
- Key: "myheader-key5",
- Value: "myheader-value5",
- },
- },
- },
- },
- }
- // Set one int type error rule
- wxmlIntErr := WebsiteXML{}
- wxmlIntErr.RoutingRules = append(wxmlIntErr.RoutingRules, ruleIntErr)
- err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlIntErr)
- c.Assert(err, NotNil)
- // Set one error rule
- wxmlErr := WebsiteXML{}
- wxmlErr.RoutingRules = append(wxmlErr.RoutingRules, ruleErr)
- err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlErr)
- c.Assert(err, NotNil)
- // Set one error rule and one correct rule
- wxmlErr.RoutingRules = append(wxmlErr.RoutingRules, ruleOk)
- err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlErr)
- c.Assert(err, NotNil)
- wxmlErrRuleArr := WebsiteXML{}
- wxmlErrRuleArr.RoutingRules = append(wxmlErrRuleArr.RoutingRules, rulesErrArr...)
- // Set array error routing rule
- err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlErrRuleArr)
- c.Assert(err, NotNil)
- err = client.DeleteBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketWebsiteXml
- func (s *OssClientSuite) TestSetBucketWebsiteXml(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Define one routing rule
- ruleOk := RoutingRule{
- RuleNumber: 1,
- Condition: Condition{
- KeyPrefixEquals: "",
- HTTPErrorCodeReturnedEquals: 404,
- },
- Redirect: Redirect{
- RedirectType: "Mirror",
- // PassQueryString: &btrue, // set default value
- MirrorURL: "http://www.test.com/",
- // MirrorPassQueryString:&btrue, // set default value
- // MirrorFollowRedirect:&bfalse, // set default value
- // MirrorCheckMd5:&bfalse, // set default value
- MirrorHeaders: MirrorHeaders{
- // PassAll:&bfalse, // set default value
- Pass: []string{"myheader-key1", "myheader-key2"},
- Remove: []string{"myheader-key3", "myheader-key4"},
- Set: []MirrorHeaderSet{
- MirrorHeaderSet{
- Key: "myheader-key5",
- Value: "myheader-value5",
- },
- },
- },
- },
- }
- // Set one routing rule
- wxmlOne := WebsiteXML{}
- wxmlOne.RoutingRules = append(wxmlOne.RoutingRules, ruleOk)
- bs, err := xml.Marshal(wxmlOne)
- c.Assert(err, IsNil)
- var responseHeader http.Header
- err = client.SetBucketWebsiteXml(bucketNameTest, string(bs), GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- res, err := client.GetBucketWebsite(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.RoutingRules[0].Redirect.RedirectType, Equals, "Mirror")
- c.Assert(*res.RoutingRules[0].Redirect.PassQueryString, Equals, false)
- c.Assert(*res.RoutingRules[0].Redirect.MirrorPassQueryString, Equals, false)
- c.Assert(*res.RoutingRules[0].Redirect.MirrorFollowRedirect, Equals, true)
- c.Assert(*res.RoutingRules[0].Redirect.MirrorCheckMd5, Equals, false)
- c.Assert(*res.RoutingRules[0].Redirect.MirrorHeaders.PassAll, Equals, false)
- }
- // TestSetBucketCORS
- func (s *OssClientSuite) TestSetBucketCORS(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var rule1 = CORSRule{
- AllowedOrigin: []string{"*"},
- AllowedMethod: []string{"PUT", "GET", "POST"},
- AllowedHeader: []string{},
- ExposeHeader: []string{},
- MaxAgeSeconds: 100,
- }
- var rule2 = CORSRule{
- AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
- AllowedMethod: []string{"GET"},
- AllowedHeader: []string{"Authorization"},
- ExposeHeader: []string{"x-oss-test", "x-oss-test1"},
- MaxAgeSeconds: 200,
- }
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Set
- err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule1})
- c.Assert(err, IsNil)
- gbcr, err := client.GetBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(gbcr.CORSRules), Equals, 1)
- c.Assert(len(gbcr.CORSRules[0].AllowedOrigin), Equals, 1)
- c.Assert(len(gbcr.CORSRules[0].AllowedMethod), Equals, 3)
- c.Assert(len(gbcr.CORSRules[0].AllowedHeader), Equals, 0)
- c.Assert(len(gbcr.CORSRules[0].ExposeHeader), Equals, 0)
- c.Assert(gbcr.CORSRules[0].MaxAgeSeconds, Equals, 100)
- // Double set
- err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule1})
- c.Assert(err, IsNil)
- gbcr, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(gbcr.CORSRules), Equals, 1)
- c.Assert(len(gbcr.CORSRules[0].AllowedOrigin), Equals, 1)
- c.Assert(len(gbcr.CORSRules[0].AllowedMethod), Equals, 3)
- c.Assert(len(gbcr.CORSRules[0].AllowedHeader), Equals, 0)
- c.Assert(len(gbcr.CORSRules[0].ExposeHeader), Equals, 0)
- c.Assert(gbcr.CORSRules[0].MaxAgeSeconds, Equals, 100)
- // Set rule2
- err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule2})
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- gbcr, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(gbcr.CORSRules), Equals, 1)
- c.Assert(len(gbcr.CORSRules[0].AllowedOrigin), Equals, 2)
- c.Assert(len(gbcr.CORSRules[0].AllowedMethod), Equals, 1)
- c.Assert(len(gbcr.CORSRules[0].AllowedHeader), Equals, 1)
- c.Assert(len(gbcr.CORSRules[0].ExposeHeader), Equals, 2)
- c.Assert(gbcr.CORSRules[0].MaxAgeSeconds, Equals, 200)
- // Reset
- err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule1, rule2})
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- gbcr, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(gbcr.CORSRules), Equals, 2)
- // Set after delete
- err = client.DeleteBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule1, rule2})
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- gbcr, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(len(gbcr.CORSRules), Equals, 2)
- err = client.DeleteBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestDeleteBucketCORS
- func (s *OssClientSuite) TestDeleteBucketCORS(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var rule = CORSRule{
- AllowedOrigin: []string{"*"},
- AllowedMethod: []string{"PUT", "GET", "POST"},
- AllowedHeader: []string{},
- ExposeHeader: []string{},
- MaxAgeSeconds: 100,
- }
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // Delete not set
- err = client.DeleteBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- // Set
- err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule})
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- _, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- // Detele
- err = client.DeleteBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- _, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, NotNil)
- // Detele after deleting
- err = client.DeleteBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestSetBucketCORSNegative
- func (s *OssClientSuite) TestSetBucketCORSNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var rule = CORSRule{
- AllowedOrigin: []string{"*"},
- AllowedMethod: []string{"PUT", "GET", "POST"},
- AllowedHeader: []string{},
- ExposeHeader: []string{},
- MaxAgeSeconds: 100,
- }
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- // Not exist
- _, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, NotNil)
- err = client.DeleteBucketCORS(bucketNameTest)
- c.Assert(err, NotNil)
- err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule})
- c.Assert(err, NotNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- _, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, NotNil)
- // Set
- err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule})
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- _, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- // Delete
- err = client.DeleteBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- _, err = client.GetBucketCORS(bucketNameTest)
- c.Assert(err, NotNil)
- // Delete after deleting
- err = client.DeleteBucketCORS(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestGetBucketInfo
- func (s *OssClientSuite) TestGetBucketInfo(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- res, err := client.GetBucketInfo(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.BucketInfo.Name, Equals, bucketNameTest)
- c.Assert(strings.HasPrefix(res.BucketInfo.Location, "oss-"), Equals, true)
- c.Assert(res.BucketInfo.ACL, Equals, "private")
- c.Assert(strings.HasSuffix(res.BucketInfo.ExtranetEndpoint, ".com"), Equals, true)
- c.Assert(strings.HasSuffix(res.BucketInfo.IntranetEndpoint, ".com"), Equals, true)
- c.Assert(res.BucketInfo.CreationDate, NotNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestGetBucketInfoNegative
- func (s *OssClientSuite) TestGetBucketInfoNegative(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Not exist
- _, err = client.GetBucketInfo(bucketNameTest)
- c.Assert(err, NotNil)
- // Bucket name invalid
- _, err = client.GetBucketInfo("InvalidBucketName_")
- c.Assert(err, NotNil)
- }
- // TestEndpointFormat
- func (s *OssClientSuite) TestEndpointFormat(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- // http://host
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err := client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- // http://host:port
- client, err = New(endpoint+":80", accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- time.Sleep(timeoutInOperation)
- res, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestCname
- func (s *OssClientSuite) _TestCname(c *C) {
- var bucketNameTest = "<my-bucket-cname>"
- client, err := New("<endpoint>", "<accessKeyId>", "<accessKeySecret>", UseCname(true))
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- _, err = client.ListBuckets()
- c.Assert(err, NotNil)
- res, err := client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- }
- // TestCnameNegative
- func (s *OssClientSuite) _TestCnameNegative(c *C) {
- var bucketNameTest = "<my-bucket-cname>"
- client, err := New("<endpoint>", "<accessKeyId>", "<accessKeySecret>", UseCname(true))
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, NotNil)
- _, err = client.ListBuckets()
- c.Assert(err, NotNil)
- _, err = client.GetBucketACL(bucketNameTest)
- c.Assert(err, NotNil)
- }
- // _TestHTTPS
- func (s *OssClientSuite) _TestHTTPS(c *C) {
- var bucketNameTest = "<my-bucket-https>"
- client, err := New("<endpoint>", "<accessKeyId>", "<accessKeySecret>")
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- res, err := client.GetBucketACL(bucketNameTest)
- c.Assert(err, IsNil)
- c.Assert(res.ACL, Equals, string(ACLPrivate))
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestClientOption
- func (s *OssClientSuite) TestClientOption(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey, UseCname(true),
- Timeout(11, 12), SecurityToken("token"), Proxy(proxyHost))
- c.Assert(err, IsNil)
- // CreateBucket timeout
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, NotNil)
- c.Assert(client.Conn.config.HTTPTimeout.ConnectTimeout, Equals, time.Second*11)
- c.Assert(client.Conn.config.HTTPTimeout.ReadWriteTimeout, Equals, time.Second*12)
- c.Assert(client.Conn.config.HTTPTimeout.HeaderTimeout, Equals, time.Second*12)
- c.Assert(client.Conn.config.HTTPTimeout.IdleConnTimeout, Equals, time.Second*12)
- c.Assert(client.Conn.config.HTTPTimeout.LongTimeout, Equals, time.Second*12*10)
- c.Assert(client.Conn.config.SecurityToken, Equals, "token")
- c.Assert(client.Conn.config.IsCname, Equals, true)
- c.Assert(client.Conn.config.IsUseProxy, Equals, true)
- c.Assert(client.Config.ProxyHost, Equals, proxyHost)
- client, err = New(endpoint, accessID, accessKey, AuthProxy(proxyHost, proxyUser, proxyPasswd))
- c.Assert(client.Conn.config.IsUseProxy, Equals, true)
- c.Assert(client.Config.ProxyHost, Equals, proxyHost)
- c.Assert(client.Conn.config.IsAuthProxy, Equals, true)
- c.Assert(client.Conn.config.ProxyUser, Equals, proxyUser)
- c.Assert(client.Conn.config.ProxyPassword, Equals, proxyPasswd)
- client, err = New(endpoint, accessID, accessKey, UserAgent("go sdk user agent"))
- c.Assert(client.Conn.config.UserAgent, Equals, "go sdk user agent")
- // Check we can overide the http.Client
- httpClient := new(http.Client)
- client, err = New(endpoint, accessID, accessKey, HTTPClient(httpClient))
- c.Assert(client.HTTPClient, Equals, httpClient)
- c.Assert(client.Conn.client, Equals, httpClient)
- client, err = New(endpoint, accessID, accessKey)
- c.Assert(client.HTTPClient, IsNil)
- }
- // TestProxy
- func (s *OssClientSuite) ProxyTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
- bucketNameTest := bucketNamePrefix + RandLowStr(6)
- objectName := "体育/奥运/首金"
- objectValue := "大江东去,浪淘尽,千古风流人物。 故垒西边,人道是、三国周郎赤壁。"
- client, err := New(endpoint, accessID, accessKey, AuthProxy(proxyHost, proxyUser, proxyPasswd))
- oldType := client.Config.AuthVersion
- oldHeaders := client.Config.AdditionalHeaders
- client.Config.AuthVersion = authVersion
- client.Config.AdditionalHeaders = extraHeaders
- // Create bucket
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- // Get bucket info
- _, err = client.GetBucketInfo(bucketNameTest)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketNameTest)
- // Sign URL
- 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 get object
- 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)
- // Put object
- err = bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Get object
- _, err = bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- // List objects
- _, err = bucket.ListObjects()
- c.Assert(err, IsNil)
- // Delete object
- err = bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Delete bucket
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- client.Config.AuthVersion = oldType
- client.Config.AdditionalHeaders = oldHeaders
- }
- func (s *OssClientSuite) TestProxy(c *C) {
- s.ProxyTestFunc(c, AuthV1, []string{})
- s.ProxyTestFunc(c, AuthV2, []string{})
- s.ProxyTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
- }
- // TestProxy for https endpoint
- func (s *OssClientSuite) TestHttpsEndpointProxy(c *C) {
- bucketNameTest := bucketNamePrefix + RandLowStr(6)
- objectName := objectNamePrefix + RandLowStr(6)
- objectValue := RandLowStr(100)
- httpsEndPoint := ""
- if strings.HasPrefix(endpoint, "http://") {
- httpsEndPoint = strings.Replace(endpoint, "http://", "https://", 1)
- } else if !strings.HasPrefix(endpoint, "https://") {
- httpsEndPoint = "https://" + endpoint
- } else {
- httpsEndPoint = endpoint
- }
- client, err := New(httpsEndPoint, accessID, accessKey, AuthProxy(proxyHost, proxyUser, proxyPasswd))
- // Create bucket
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketNameTest)
- // Put object
- err = bucket.PutObject(objectName, strings.NewReader(objectValue))
- c.Assert(err, IsNil)
- // Get object
- _, err = bucket.GetObject(objectName)
- c.Assert(err, IsNil)
- // List objects
- _, err = bucket.ListObjects()
- c.Assert(err, IsNil)
- // Delete object
- err = bucket.DeleteObject(objectName)
- c.Assert(err, IsNil)
- // Delete bucket
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // Private
- func (s *OssClientSuite) checkBucket(buckets []BucketProperties, bucket string) bool {
- for _, v := range buckets {
- if v.Name == bucket {
- return true
- }
- }
- return false
- }
- func (s *OssClientSuite) getBucket(buckets []BucketProperties, bucket string) (bool, BucketProperties) {
- for _, v := range buckets {
- if v.Name == bucket {
- return true, v
- }
- }
- return false, BucketProperties{}
- }
- func (s *OssClientSuite) TestHttpLogNotSignUrl(c *C) {
- logName := "." + string(os.PathSeparator) + "test-go-sdk-httpdebug.log" + RandStr(5)
- f, err := os.OpenFile(logName, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0660)
- c.Assert(err, IsNil)
- client, err := New(endpoint, accessID, accessKey)
- client.Config.LogLevel = Debug
- client.Config.Logger = log.New(f, "", log.LstdFlags)
- var testBucketName = bucketNamePrefix + RandLowStr(6)
- // CreateBucket
- err = client.CreateBucket(testBucketName)
- f.Close()
- // read log file,get http info
- contents, err := ioutil.ReadFile(logName)
- c.Assert(err, IsNil)
- httpContent := string(contents)
- //fmt.Println(httpContent)
- c.Assert(strings.Contains(httpContent, "signStr"), Equals, true)
- c.Assert(strings.Contains(httpContent, "Method:"), Equals, true)
- // delete test bucket and log
- os.Remove(logName)
- client.DeleteBucket(testBucketName)
- }
- func (s *OssClientSuite) HttpLogSignUrlTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
- logName := "." + string(os.PathSeparator) + "test-go-sdk-httpdebug-signurl.log" + RandStr(5)
- f, err := os.OpenFile(logName, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0660)
- c.Assert(err, IsNil)
- client, err := New(endpoint, accessID, accessKey)
- client.Config.LogLevel = Debug
- client.Config.Logger = log.New(f, "", log.LstdFlags)
- oldType := client.Config.AuthVersion
- oldHeaders := client.Config.AdditionalHeaders
- client.Config.AuthVersion = authVersion
- client.Config.AdditionalHeaders = extraHeaders
- var testBucketName = bucketNamePrefix + RandLowStr(6)
- // CreateBucket
- err = client.CreateBucket(testBucketName)
- f.Close()
- // clear log
- f, err = os.OpenFile(logName, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0660)
- client.Config.Logger = log.New(f, "", log.LstdFlags)
- bucket, _ := client.Bucket(testBucketName)
- objectName := objectNamePrefix + RandStr(8)
- objectValue := RandStr(20)
- // 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)
- }
- // Error put object with URL
- err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue), ContentType("image/tiff"))
- f.Close()
- // read log file,get http info
- contents, err := ioutil.ReadFile(logName)
- c.Assert(err, IsNil)
- httpContent := string(contents)
- //fmt.Println(httpContent)
- c.Assert(strings.Contains(httpContent, "signStr"), Equals, true)
- c.Assert(strings.Contains(httpContent, "Method:"), Equals, true)
- // delete test bucket and log
- os.Remove(logName)
- client.DeleteBucket(testBucketName)
- client.Config.AuthVersion = oldType
- client.Config.AdditionalHeaders = oldHeaders
- }
- func (s *OssClientSuite) TestHttpLogSignUrl(c *C) {
- s.HttpLogSignUrlTestFunc(c, AuthV1, []string{})
- s.HttpLogSignUrlTestFunc(c, AuthV2, []string{})
- s.HttpLogSignUrlTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
- }
- func (s *OssClientSuite) TestSetLimitUploadSpeed(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- err = client.LimitUploadSpeed(100)
- goVersion := runtime.Version()
- pSlice := strings.Split(strings.ToLower(goVersion), ".")
- // compare with go1.7
- if len(pSlice) >= 2 {
- if pSlice[0] > "go1" {
- c.Assert(err, IsNil)
- } else if pSlice[0] == "go1" {
- subVersion, _ := strconv.Atoi(pSlice[1])
- if subVersion >= 7 {
- c.Assert(err, IsNil)
- } else {
- c.Assert(err, NotNil)
- }
- } else {
- c.Assert(err, NotNil)
- }
- }
- }
- func (s *OssClientSuite) TestBucketEncyptionError(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // SetBucketEncryption:AES256 ,"123"
- encryptionRule := ServerEncryptionRule{}
- encryptionRule.SSEDefault.SSEAlgorithm = string(AESAlgorithm)
- encryptionRule.SSEDefault.KMSMasterKeyID = "123"
- var responseHeader http.Header
- err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
- c.Assert(err, NotNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // GetBucketEncryption
- _, err = client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, NotNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // Get default bucket info
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "")
- c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketEncryptionPutAndGetAndDelete(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // SetBucketEncryption:KMS ,""
- encryptionRule := ServerEncryptionRule{}
- encryptionRule.SSEDefault.SSEAlgorithm = string(KMSAlgorithm)
- var responseHeader http.Header
- err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // GetBucketEncryption
- getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // check encryption value
- c.Assert(encryptionRule.SSEDefault.SSEAlgorithm, Equals, getResult.SSEDefault.SSEAlgorithm)
- c.Assert(encryptionRule.SSEDefault.KMSMasterKeyID, Equals, getResult.SSEDefault.KMSMasterKeyID)
- // delete bucket encyption
- err = client.DeleteBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // GetBucketEncryption failure
- _, err = client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, NotNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // Get default bucket info
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "")
- c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketEncryptionWithSm4(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // SetBucketEncryption:SM4 ,""
- encryptionRule := ServerEncryptionRule{}
- encryptionRule.SSEDefault.SSEAlgorithm = string(SM4Algorithm)
- var responseHeader http.Header
- err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // GetBucketEncryption
- getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // check encryption value
- c.Assert(getResult.SSEDefault.SSEAlgorithm, Equals, string(SM4Algorithm))
- c.Assert(getResult.SSEDefault.KMSMasterKeyID, Equals, "")
- c.Assert(getResult.SSEDefault.KMSDataEncryption, Equals, "")
- // Get default bucket info
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, string(SM4Algorithm))
- c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
- c.Assert(bucketResult.BucketInfo.SseRule.KMSDataEncryption, Equals, "")
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketEncryptionWithKmsSm4(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // SetBucketEncryption:SM4 ,""
- encryptionRule := ServerEncryptionRule{}
- encryptionRule.SSEDefault.SSEAlgorithm = string(KMSAlgorithm)
- encryptionRule.SSEDefault.KMSDataEncryption = string(SM4Algorithm)
- var responseHeader http.Header
- err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // GetBucketEncryption
- getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // check encryption value
- c.Assert(getResult.SSEDefault.SSEAlgorithm, Equals, string(KMSAlgorithm))
- c.Assert(getResult.SSEDefault.KMSMasterKeyID, Equals, "")
- c.Assert(getResult.SSEDefault.KMSDataEncryption, Equals, string(SM4Algorithm))
- // Get default bucket info
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, string(KMSAlgorithm))
- c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
- c.Assert(bucketResult.BucketInfo.SseRule.KMSDataEncryption, Equals, string(SM4Algorithm))
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketEncyptionPutObjectSuccess(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // SetBucketEncryption:KMS ,""
- encryptionRule := ServerEncryptionRule{}
- encryptionRule.SSEDefault.SSEAlgorithm = string(KMSAlgorithm)
- var responseHeader http.Header
- err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // GetBucketEncryption
- getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // check encryption value
- c.Assert(encryptionRule.SSEDefault.SSEAlgorithm, Equals, getResult.SSEDefault.SSEAlgorithm)
- c.Assert(encryptionRule.SSEDefault.KMSMasterKeyID, Equals, getResult.SSEDefault.KMSMasterKeyID)
- // Get default bucket info
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "KMS")
- c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketEncyptionPutObjectError(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // SetBucketEncryption:KMS ,""
- encryptionRule := ServerEncryptionRule{}
- encryptionRule.SSEDefault.SSEAlgorithm = string(KMSAlgorithm)
- kmsId := "123"
- encryptionRule.SSEDefault.KMSMasterKeyID = kmsId
- var responseHeader http.Header
- err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // GetBucketEncryption
- getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // check encryption value
- c.Assert(encryptionRule.SSEDefault.SSEAlgorithm, Equals, getResult.SSEDefault.SSEAlgorithm)
- c.Assert(encryptionRule.SSEDefault.KMSMasterKeyID, Equals, getResult.SSEDefault.KMSMasterKeyID)
- // Get default bucket info
- bucketResult, err := client.GetBucketInfo(bucketName)
- c.Assert(err, IsNil)
- c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "KMS")
- c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, kmsId)
- c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
- // put and get object failure
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- // put object failure
- objectName := objectNamePrefix + RandStr(8)
- context := RandStr(100)
- err = bucket.PutObject(objectName, strings.NewReader(context))
- c.Assert(err, NotNil)
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketTaggingOperation(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- var respHeader http.Header
- // Bucket Tagging
- var tagging Tagging
- tagging.Tags = []Tag{Tag{Key: "testkey2", Value: "testvalue2"}}
- err = client.SetBucketTagging(bucketName, tagging, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- getResult, err := client.GetBucketTagging(bucketName)
- c.Assert(err, IsNil)
- c.Assert(getResult.Tags[0].Key, Equals, tagging.Tags[0].Key)
- c.Assert(getResult.Tags[0].Value, Equals, tagging.Tags[0].Value)
- // delete BucketTagging
- err = client.DeleteBucketTagging(bucketName, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- getResult, err = client.GetBucketTagging(bucketName, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- c.Assert(len(getResult.Tags), Equals, 0)
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestListBucketsTagging(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName1 := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName1)
- c.Assert(err, IsNil)
- bucketName2 := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName2)
- c.Assert(err, IsNil)
- // Bucket Tagging
- var tagging Tagging
- tagging.Tags = []Tag{Tag{Key: "testkey", Value: "testvalue"}}
- err = client.SetBucketTagging(bucketName1, tagging)
- c.Assert(err, IsNil)
- // list bucket
- listResult, err := client.ListBuckets(TagKey("testkey"))
- c.Assert(err, IsNil)
- c.Assert(len(listResult.Buckets), Equals, 1)
- c.Assert(listResult.Buckets[0].Name, Equals, bucketName1)
- client.DeleteBucket(bucketName1)
- client.DeleteBucket(bucketName2)
- }
- func (s *OssClientSuite) TestGetBucketStat(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bucket, err := client.Bucket(bucketName)
- c.Assert(err, IsNil)
- // put object
- objectName := objectNamePrefix + RandLowStr(5)
- err = bucket.PutObject(objectName, strings.NewReader(RandStr(10)))
- c.Assert(err, IsNil)
- bucket.DeleteObject(objectName)
- err = bucket.PutObject(objectName, strings.NewReader(RandStr(10)))
- c.Assert(err, IsNil)
- bucket.DeleteObject(objectName)
- _, err = client.GetBucketStat(bucketName)
- c.Assert(err, IsNil)
- client.DeleteBucket(bucketName)
- }
- func (s *OssBucketSuite) TestGetBucketVersioning(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- var respHeader http.Header
- err = client.CreateBucket(bucketName, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // get bucket version success
- versioningResult, err := client.GetBucketVersioning(bucketName, GetResponseHeader(&respHeader))
- c.Assert(versioningResult.Status, Equals, "Enabled")
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- ForceDeleteBucket(client, bucketName, c)
- }
- func (s *OssClientSuite) TestBucketPolicy(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- var responseHeader http.Header
- ret, err := client.GetBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, NotNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- policyInfo := `
- {
- "Version":"1",
- "Statement":[
- {
- "Action":[
- "oss:GetObject",
- "oss:PutObject"
- ],
- "Effect":"Deny",
- "Principal":"[123456790]",
- "Resource":["acs:oss:*:1234567890:*/*"]
- }
- ]
- }`
- err = client.SetBucketPolicy(bucketName, policyInfo, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- ret, err = client.GetBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- testLogger.Println("policy:", ret)
- c.Assert(ret, Equals, policyInfo)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- err = client.DeleteBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- client.DeleteBucket(bucketName)
- }
- func (s *OssClientSuite) TestBucketPolicyNegative(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- var responseHeader http.Header
- _, err = client.GetBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, NotNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // Setting the Version is 2, this is error policy
- errPolicy := `
- {
- "Version":"2",
- "Statement":[
- {
- "Action":[
- "oss:GetObject",
- "oss:PutObject"
- ],
- "Effect":"Deny",
- "Principal":"[123456790]",
- "Resource":["acs:oss:*:1234567890:*/*"]
- }
- ]
- }`
- err = client.SetBucketPolicy(bucketName, errPolicy, GetResponseHeader(&responseHeader))
- c.Assert(err, NotNil)
- testLogger.Println("err:", err)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- err = client.DeleteBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- bucketNameEmpty := bucketNamePrefix + RandLowStr(5)
- client.DeleteBucket(bucketNameEmpty)
- err = client.DeleteBucketPolicy(bucketNameEmpty, GetResponseHeader(&responseHeader))
- c.Assert(err, NotNil)
- requestId = GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- client.DeleteBucket(bucketName)
- }
- func (s *OssClientSuite) TestSetBucketRequestPayment(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- reqPayConf := RequestPaymentConfiguration{
- Payer: "Requester",
- }
- err = client.SetBucketRequestPayment(bucketName, reqPayConf)
- c.Assert(err, IsNil)
- ret, err := client.GetBucketRequestPayment(bucketName)
- c.Assert(err, IsNil)
- c.Assert(ret.Payer, Equals, "Requester")
- client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestSetBucketRequestPaymentNegative(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- reqPayConf := RequestPaymentConfiguration{
- Payer: "Requesterttttt", // this is a error configuration
- }
- err = client.SetBucketRequestPayment(bucketName, reqPayConf)
- c.Assert(err, NotNil)
- ret, err := client.GetBucketRequestPayment(bucketName)
- c.Assert(err, IsNil)
- c.Assert(ret.Payer, Equals, "BucketOwner")
- client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketQos(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- ret, err := client.GetUserQoSInfo()
- c.Assert(err, IsNil)
- testLogger.Println("QosInfo:", ret)
- bucketName := bucketNamePrefix + RandLowStr(5)
- _ = client.DeleteBucket(bucketName)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- _, err = client.GetBucketQosInfo(bucketName)
- c.Assert(err, NotNil)
- // case 1 set BucketQoSConfiguration every member
- five := 5
- four := 4
- totalQps := 200
- qosConf := BucketQoSConfiguration{
- TotalUploadBandwidth: &five,
- IntranetUploadBandwidth: &four,
- ExtranetUploadBandwidth: &four,
- TotalDownloadBandwidth: &four,
- IntranetDownloadBandwidth: &four,
- ExtranetDownloadBandwidth: &four,
- TotalQPS: &totalQps,
- IntranetQPS: &totalQps,
- ExtranetQPS: &totalQps,
- }
- var responseHeader http.Header
- err = client.SetBucketQoSInfo(bucketName, qosConf, GetResponseHeader(&responseHeader))
- c.Assert(err, IsNil)
- requestId := GetRequestId(responseHeader)
- c.Assert(len(requestId) > 0, Equals, true)
- // wait a moment for configuration effect
- time.Sleep(time.Second)
- retQos, err := client.GetBucketQosInfo(bucketName)
- c.Assert(err, IsNil)
- // set qosConf default value
- qosConf.XMLName.Local = "QoSConfiguration"
- c.Assert(struct2string(retQos, c), Equals, struct2string(qosConf, c))
- // case 2 set BucketQoSConfiguration not every member
- qosConfNo := BucketQoSConfiguration{
- TotalUploadBandwidth: &five,
- IntranetUploadBandwidth: &four,
- ExtranetUploadBandwidth: &four,
- TotalDownloadBandwidth: &four,
- IntranetDownloadBandwidth: &four,
- ExtranetDownloadBandwidth: &four,
- TotalQPS: &totalQps,
- }
- err = client.SetBucketQoSInfo(bucketName, qosConfNo)
- c.Assert(err, IsNil)
- // wait a moment for configuration effect
- time.Sleep(time.Second)
- retQos, err = client.GetBucketQosInfo(bucketName)
- c.Assert(err, IsNil)
- // set qosConfNo default value
- qosConfNo.XMLName.Local = "QoSConfiguration"
- defNum := -1
- qosConfNo.IntranetQPS = &defNum
- qosConfNo.ExtranetQPS = &defNum
- c.Assert(struct2string(retQos, c), Equals, struct2string(qosConfNo, c))
- err = client.DeleteBucketQosInfo(bucketName)
- c.Assert(err, IsNil)
- // wait a moment for configuration effect
- time.Sleep(time.Second)
- _, err = client.GetBucketQosInfo(bucketName)
- c.Assert(err, NotNil)
- // this is a error qos configuration
- to := *ret.TotalUploadBandwidth + 2
- qosErrConf := BucketQoSConfiguration{
- TotalUploadBandwidth: &to, // this exceed user TotalUploadBandwidth
- IntranetUploadBandwidth: &four,
- ExtranetUploadBandwidth: &four,
- TotalDownloadBandwidth: &four,
- IntranetDownloadBandwidth: &four,
- ExtranetDownloadBandwidth: &four,
- TotalQPS: &totalQps,
- IntranetQPS: &totalQps,
- ExtranetQPS: &totalQps,
- }
- err = client.SetBucketQoSInfo(bucketName, qosErrConf)
- c.Assert(err, NotNil)
- err = client.DeleteBucketQosInfo(bucketName)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- // struct to string
- func struct2string(obj interface{}, c *C) string {
- t := reflect.TypeOf(obj)
- v := reflect.ValueOf(obj)
- var data = make(map[string]interface{})
- for i := 0; i < t.NumField(); i++ {
- data[t.Field(i).Name] = v.Field(i).Interface()
- }
- str, err := json.Marshal(data)
- c.Assert(err, IsNil)
- return string(str)
- }
- type TestCredentials struct {
- }
- func (testCreInf *TestCredentials) GetAccessKeyID() string {
- return os.Getenv("OSS_TEST_ACCESS_KEY_ID")
- }
- func (testCreInf *TestCredentials) GetAccessKeySecret() string {
- return os.Getenv("OSS_TEST_ACCESS_KEY_SECRET")
- }
- func (testCreInf *TestCredentials) GetSecurityToken() string {
- return ""
- }
- type TestCredentialsProvider struct {
- }
- func (testInfBuild *TestCredentialsProvider) GetCredentials() Credentials {
- return &TestCredentials{}
- }
- func (s *OssClientSuite) TestClientCredentialInfBuild(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- var defaultBuild TestCredentialsProvider
- client, err := New(endpoint, "", "", SetCredentialsProvider(&defaultBuild))
- c.Assert(err, IsNil)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestClientSetLocalIpError(c *C) {
- // create client and bucket
- ipAddr, err := net.ResolveIPAddr("ip", "127.0.0.1")
- c.Assert(err, IsNil)
- localTCPAddr := &(net.TCPAddr{IP: ipAddr.IP})
- client, err := New(endpoint, accessID, accessKey, SetLocalAddr(localTCPAddr))
- c.Assert(err, IsNil)
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, NotNil)
- }
- func (s *OssClientSuite) TestClientSetLocalIpSuccess(c *C) {
- //get local ip
- conn, err := net.Dial("udp", "8.8.8.8:80")
- c.Assert(err, IsNil)
- localAddr := conn.LocalAddr().(*net.UDPAddr)
- localIp := localAddr.IP.String()
- conn.Close()
- ipAddr, err := net.ResolveIPAddr("ip", localIp)
- c.Assert(err, IsNil)
- localTCPAddr := &(net.TCPAddr{IP: ipAddr.IP})
- client, err := New(endpoint, accessID, accessKey, SetLocalAddr(localTCPAddr))
- c.Assert(err, IsNil)
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestCreateBucketInvalidName
- func (s *OssClientSuite) TestCreateBucketInvalidName(c *C) {
- var bucketNameTest = "-" + bucketNamePrefix + RandLowStr(6)
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Create
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, NotNil)
- }
- // TestClientProcessEndpointSuccess
- func (s *OssClientSuite) TestClientProcessEndpointSuccess(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- testEndpoint := endpoint + "/" + "sina.com" + "?" + "para=abc"
- client, err := New(testEndpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Create
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, IsNil)
- // delete
- err = client.DeleteBucket(bucketNameTest)
- c.Assert(err, IsNil)
- }
- // TestClientProcessEndpointSuccess
- func (s *OssClientSuite) TestClientProcessEndpointError(c *C) {
- var bucketNameTest = bucketNamePrefix + RandLowStr(6)
- testEndpoint := "https://127.0.0.1/" + endpoint
- client, err := New(testEndpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- // Create
- err = client.CreateBucket(bucketNameTest)
- c.Assert(err, NotNil)
- }
- // TestClientBucketError
- func (s *OssClientSuite) TestClientBucketError(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := "-" + RandLowStr(5)
- _, err = client.Bucket(bucketName)
- c.Assert(err, NotNil)
- }
- func (s *OssClientSuite) TestSetBucketInventory(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- // encryption config
- var invSseOss InvSseOss
- invSseKms := InvSseKms{
- KmsId: "keyId",
- }
- var invEncryption InvEncryption
- bl := true
- // not any encryption
- invConfig := InventoryConfiguration{
- Id: "report1",
- IsEnabled: &bl,
- Prefix: "filterPrefix/",
- OSSBucketDestination: OSSBucketDestination{
- Format: "CSV",
- AccountId: accountID,
- RoleArn: stsARN,
- Bucket: "acs:oss:::" + bucketName,
- Prefix: "prefix1",
- },
- Frequency: "Daily",
- IncludedObjectVersions: "All",
- OptionalFields: OptionalFields{
- Field: []string{
- "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
- },
- },
- }
- // case 1: not any encryption
- err = client.SetBucketInventory(bucketName, invConfig)
- c.Assert(err, IsNil)
- // case 2: use kms encryption
- invConfig.Id = "report2"
- invEncryption.SseKms = &invSseKms
- invEncryption.SseOss = nil
- invConfig.OSSBucketDestination.Encryption = &invEncryption
- err = client.SetBucketInventory(bucketName, invConfig)
- c.Assert(err, IsNil)
- // case 3: use SseOss encryption
- invConfig.Id = "report3"
- invEncryption.SseKms = nil
- invEncryption.SseOss = &invSseOss
- invConfig.OSSBucketDestination.Encryption = &invEncryption
- err = client.SetBucketInventory(bucketName, invConfig)
- c.Assert(err, IsNil)
- //case 4: use two type encryption
- invConfig.Id = "report4"
- invEncryption.SseKms = &invSseKms
- invEncryption.SseOss = &invSseOss
- invConfig.OSSBucketDestination.Encryption = &invEncryption
- err = client.SetBucketInventory(bucketName, invConfig)
- c.Assert(err, NotNil)
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketInventory(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bl := true
- invConfig := InventoryConfiguration{
- Id: "report1",
- IsEnabled: &bl,
- Prefix: "filterPrefix/",
- OSSBucketDestination: OSSBucketDestination{
- Format: "CSV",
- AccountId: accountID,
- RoleArn: stsARN,
- Bucket: "acs:oss:::" + bucketName,
- Prefix: "prefix1",
- },
- Frequency: "Daily",
- IncludedObjectVersions: "All",
- OptionalFields: OptionalFields{
- Field: []string{
- "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
- },
- },
- }
- // case 1: test SetBucketInventory
- err = client.SetBucketInventory(bucketName, invConfig)
- c.Assert(err, IsNil)
- // case 2: test GetBucketInventory
- out, err := client.GetBucketInventory(bucketName, "report1")
- c.Assert(err, IsNil)
- invConfig.XMLName.Local = "InventoryConfiguration"
- invConfig.OSSBucketDestination.XMLName.Local = "OSSBucketDestination"
- invConfig.OptionalFields.XMLName.Local = "OptionalFields"
- c.Assert(struct2string(invConfig, c), Equals, struct2string(out, c))
- // case 3: test ListBucketInventory
- invConfig2 := InventoryConfiguration{
- Id: "report2",
- IsEnabled: &bl,
- Prefix: "filterPrefix/",
- OSSBucketDestination: OSSBucketDestination{
- Format: "CSV",
- AccountId: accountID,
- RoleArn: stsARN,
- Bucket: "acs:oss:::" + bucketName,
- Prefix: "prefix1",
- },
- Frequency: "Daily",
- IncludedObjectVersions: "All",
- OptionalFields: OptionalFields{
- Field: []string{
- "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
- },
- },
- }
- invConfig2.XMLName.Local = "InventoryConfiguration"
- invConfig2.OSSBucketDestination.XMLName.Local = "OSSBucketDestination"
- invConfig2.OptionalFields.XMLName.Local = "OptionalFields"
- err = client.SetBucketInventory(bucketName, invConfig2)
- c.Assert(err, IsNil)
- listInvConf, err := client.ListBucketInventory(bucketName, "", Marker("report1"), MaxKeys(2))
- c.Assert(err, IsNil)
- var listInvLocal ListInventoryConfigurationsResult
- listInvLocal.InventoryConfiguration = []InventoryConfiguration{
- invConfig,
- invConfig2,
- }
- bo := false
- listInvLocal.IsTruncated = &bo
- listInvLocal.XMLName.Local = "ListInventoryConfigurationsResult"
- c.Assert(struct2string(listInvLocal, c), Equals, struct2string(listInvConf, c))
- for i := 3; i < 109; i++ {
- invConfig2 := InventoryConfiguration{
- Id: "report" + strconv.Itoa(i),
- IsEnabled: &bl,
- Prefix: "filterPrefix/",
- OSSBucketDestination: OSSBucketDestination{
- Format: "CSV",
- AccountId: accountID,
- RoleArn: stsARN,
- Bucket: "acs:oss:::" + bucketName,
- Prefix: "prefix1",
- },
- Frequency: "Daily",
- IncludedObjectVersions: "All",
- OptionalFields: OptionalFields{
- Field: []string{
- "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
- },
- },
- }
- err = client.SetBucketInventory(bucketName, invConfig2)
- c.Assert(err, IsNil)
- }
- token := ""
- for {
- listInvConf1, err := client.ListBucketInventory(bucketName, token)
- c.Assert(err, IsNil)
- token = listInvConf1.NextContinuationToken
- testLogger.Println(listInvConf1.NextContinuationToken, *listInvConf1.IsTruncated, token)
- if *listInvConf1.IsTruncated == false {
- break
- } else {
- c.Assert(listInvConf1.NextContinuationToken, Equals, "report91")
- }
- }
- // case 4: test DeleteBucketInventory
- for i := 1; i < 109; i++ {
- err = client.DeleteBucketInventory(bucketName, "report"+strconv.Itoa(i))
- c.Assert(err, IsNil)
- }
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketInventoryNegative(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- bl := true
- invConfigErr := InventoryConfiguration{
- Id: "report1",
- IsEnabled: &bl,
- Prefix: "filterPrefix/",
- OSSBucketDestination: OSSBucketDestination{
- Format: "CSV",
- AccountId: accountID,
- RoleArn: stsARN,
- Bucket: "test",
- Prefix: "prefix1",
- },
- Frequency: "Daily",
- IncludedObjectVersions: "All",
- OptionalFields: OptionalFields{
- Field: []string{
- "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
- },
- },
- }
- // case 1: test SetBucketInventory
- err = client.SetBucketInventory(bucketName, invConfigErr)
- c.Assert(err, NotNil)
- // case 2: test GetBucketInventory
- _, err = client.GetBucketInventory(bucketName, "report1")
- c.Assert(err, NotNil)
- // case 3: test ListBucketInventory
- _, err = client.ListBucketInventory(bucketName, "", Marker("report1"), MaxKeys(2))
- c.Assert(err, NotNil)
- // case 4: test DeleteBucketInventory
- err = client.DeleteBucketInventory(bucketName, "report1")
- c.Assert(err, IsNil)
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestBucketAsyncTask(c *C) {
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(5)
- err = client.CreateBucket(bucketName)
- c.Assert(err, IsNil)
- objectName := objectNamePrefix + RandLowStr(6)
- // set asyn task,IgnoreSameKey is false
- asynConf := AsyncFetchTaskConfiguration{
- Url: "http://www.baidu.com",
- Object: objectName,
- Host: "",
- ContentMD5: "",
- Callback: "",
- StorageClass: "",
- IgnoreSameKey: false,
- }
- asynResult, err := client.SetBucketAsyncTask(bucketName, asynConf)
- c.Assert(err, IsNil)
- c.Assert(len(asynResult.TaskId) > 0, Equals, true)
- // get asyn task
- asynTask, err := client.GetBucketAsyncTask(bucketName, asynResult.TaskId)
- c.Assert(err, IsNil)
- c.Assert(asynResult.TaskId, Equals, asynTask.TaskId)
- c.Assert(len(asynTask.State) > 0, Equals, true)
- c.Assert(asynConf.Url, Equals, asynTask.TaskInfo.Url)
- c.Assert(asynConf.Object, Equals, asynTask.TaskInfo.Object)
- c.Assert(asynConf.Callback, Equals, asynTask.TaskInfo.Callback)
- c.Assert(asynConf.IgnoreSameKey, Equals, asynTask.TaskInfo.IgnoreSameKey)
- // test again,IgnoreSameKey is true
- asynConf.IgnoreSameKey = true
- asynResult, err = client.SetBucketAsyncTask(bucketName, asynConf)
- c.Assert(err, IsNil)
- c.Assert(len(asynResult.TaskId) > 0, Equals, true)
- asynTask, err = client.GetBucketAsyncTask(bucketName, asynResult.TaskId)
- c.Assert(asynConf.IgnoreSameKey, Equals, asynTask.TaskInfo.IgnoreSameKey)
- err = client.DeleteBucket(bucketName)
- c.Assert(err, IsNil)
- }
- func (s *OssClientSuite) TestClientOptionHeader(c *C) {
- // create a bucket with default proprety
- client, err := New(endpoint, accessID, accessKey)
- c.Assert(err, IsNil)
- bucketName := bucketNamePrefix + RandLowStr(6)
- var respHeader http.Header
- err = client.CreateBucket(bucketName, GetResponseHeader(&respHeader))
- c.Assert(err, IsNil)
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- // put bucket version:enabled
- var versioningConfig VersioningConfig
- versioningConfig.Status = string(VersionEnabled)
- err = client.SetBucketVersioning(bucketName, versioningConfig)
- c.Assert(err, IsNil)
- // get bucket version success,use payer
- options := []Option{RequestPayer(BucketOwner), GetResponseHeader(&respHeader)}
- versioningResult, err := client.GetBucketVersioning(bucketName, options...)
- c.Assert(versioningResult.Status, Equals, "Enabled")
- c.Assert(GetRequestId(respHeader) != "", Equals, true)
- //list buckets,use payer
- _, err = client.ListBuckets(options...)
- c.Assert(err, IsNil)
- ForceDeleteBucket(client, bucketName, c)
- }
- // compare with go1.7
- func compareVersion(goVersion string) bool {
- nowVersion := runtime.Version()
- nowVersion = strings.Replace(nowVersion, "go", "", -1)
- pSlice1 := strings.Split(goVersion, ".")
- pSlice2 := strings.Split(nowVersion, ".")
- for k, v := range pSlice2 {
- n2, _ := strconv.Atoi(string(v))
- n1, _ := strconv.Atoi(string(pSlice1[k]))
- if n2 > n1 {
- return true
- }
- if n2 < n1 {
- return false
- }
- }
- return true
- }
- func homeHandler(w http.ResponseWriter, r *http.Request) {
- http.Redirect(w, r, "/redirectTo", http.StatusFound)
- }
- func targetHandler(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "You have been redirected here!")
- }
- func (s *OssClientSuite) TestClientRedirect(c *C) {
- // must go1.7.0 onward
- if !compareVersion("1.7.0") {
- return
- }
- // get port
- rand.Seed(time.Now().Unix())
- port := 10000 + rand.Intn(10000)
- // start http server
- httpAddr := fmt.Sprintf("127.0.0.1:%d", port)
- mux := http.NewServeMux()
- mux.HandleFunc("/redirectTo", targetHandler)
- mux.HandleFunc("/", homeHandler)
- svr := &http.Server{
- Addr: httpAddr,
- ReadTimeout: 10 * time.Second,
- WriteTimeout: 10 * time.Second,
- MaxHeaderBytes: 1 << 20,
- Handler: mux,
- }
- go func() {
- svr.ListenAndServe()
- }()
- url := "http://" + httpAddr
- // create client 1,redirect disable
- client1, err := New(endpoint, accessID, accessKey, RedirectEnabled(false))
- resp, err := client1.Conn.client.Get(url)
- c.Assert(err, IsNil)
- c.Assert(resp.StatusCode, Equals, http.StatusFound)
- resp.Body.Close()
- // create client2, redirect enabled
- client2, err := New(endpoint, accessID, accessKey, RedirectEnabled(true))
- resp, err = client2.Conn.client.Get(url)
- c.Assert(err, IsNil)
- c.Assert(resp.StatusCode, Equals, 200)
- data, err := ioutil.ReadAll(resp.Body)
- c.Assert(string(data), Equals, "You have been redirected here!")
- resp.Body.Close()
- }
|