client_test.go 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642
  1. // client test
  2. // use gocheck, install gocheck to execute "go get gopkg.in/check.v1",
  3. // see https://labix.org/gocheck
  4. package oss
  5. import (
  6. "encoding/json"
  7. "encoding/xml"
  8. "fmt"
  9. "io/ioutil"
  10. "log"
  11. "math/rand"
  12. "net"
  13. "net/http"
  14. "os"
  15. "reflect"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "testing"
  20. "time"
  21. . "gopkg.in/check.v1"
  22. )
  23. // Test hooks up gocheck into the "go test" runner.
  24. func Test(t *testing.T) {
  25. TestingT(t)
  26. }
  27. type OssClientSuite struct{}
  28. var _ = Suite(&OssClientSuite{})
  29. var (
  30. // Endpoint/ID/Key
  31. endpoint = os.Getenv("OSS_TEST_ENDPOINT")
  32. accessID = os.Getenv("OSS_TEST_ACCESS_KEY_ID")
  33. accessKey = os.Getenv("OSS_TEST_ACCESS_KEY_SECRET")
  34. accountID = os.Getenv("OSS_TEST_ACCOUNT_ID")
  35. // Proxy
  36. proxyHost = os.Getenv("OSS_TEST_PROXY_HOST")
  37. proxyUser = os.Getenv("OSS_TEST_PROXY_USER")
  38. proxyPasswd = os.Getenv("OSS_TEST_PROXY_PASSWORD")
  39. // STS
  40. stsaccessID = os.Getenv("OSS_TEST_STS_ID")
  41. stsaccessKey = os.Getenv("OSS_TEST_STS_KEY")
  42. stsARN = os.Getenv("OSS_TEST_STS_ARN")
  43. // Credential
  44. credentialAccessID = os.Getenv("OSS_CREDENTIAL_KEY_ID")
  45. credentialAccessKey = os.Getenv("OSS_CREDENTIAL_KEY_SECRET")
  46. credentialUID = os.Getenv("OSS_CREDENTIAL_UID")
  47. )
  48. var (
  49. // prefix of bucket name for bucket ops test
  50. bucketNamePrefix = "go-sdk-test-bucket-"
  51. // bucket name for object ops test
  52. bucketName = bucketNamePrefix + RandLowStr(6)
  53. archiveBucketName = bucketNamePrefix + "arch-" + RandLowStr(6)
  54. // object name for object ops test
  55. objectNamePrefix = "go-sdk-test-object-"
  56. // sts region is one and only hangzhou
  57. stsRegion = "cn-hangzhou"
  58. // Credentials
  59. credentialBucketName = bucketNamePrefix + RandLowStr(6)
  60. )
  61. var (
  62. logPath = "go_sdk_test_" + time.Now().Format("20060102_150405") + ".log"
  63. testLogFile, _ = os.OpenFile(logPath, os.O_RDWR|os.O_CREATE, 0664)
  64. testLogger = log.New(testLogFile, "", log.Ldate|log.Ltime|log.Lshortfile)
  65. letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  66. timeoutInOperation = 3 * time.Second
  67. )
  68. func RandStr(n int) string {
  69. b := make([]rune, n)
  70. randMarker := rand.New(rand.NewSource(time.Now().UnixNano()))
  71. for i := range b {
  72. b[i] = letters[randMarker.Intn(len(letters))]
  73. }
  74. return string(b)
  75. }
  76. func CreateFile(fileName, content string, c *C) {
  77. fout, err := os.Create(fileName)
  78. defer fout.Close()
  79. c.Assert(err, IsNil)
  80. _, err = fout.WriteString(content)
  81. c.Assert(err, IsNil)
  82. }
  83. func RandLowStr(n int) string {
  84. return strings.ToLower(RandStr(n))
  85. }
  86. func ForceDeleteBucket(client *Client, bucketName string, c *C) {
  87. bucket, err := client.Bucket(bucketName)
  88. c.Assert(err, IsNil)
  89. // Delete Object
  90. marker := Marker("")
  91. for {
  92. lor, err := bucket.ListObjects(marker)
  93. c.Assert(err, IsNil)
  94. for _, object := range lor.Objects {
  95. err = bucket.DeleteObject(object.Key)
  96. c.Assert(err, IsNil)
  97. }
  98. marker = Marker(lor.NextMarker)
  99. if !lor.IsTruncated {
  100. break
  101. }
  102. }
  103. // Delete Object Versions and DeleteMarks
  104. keyMarker := KeyMarker("")
  105. versionIdMarker := VersionIdMarker("")
  106. options := []Option{keyMarker, versionIdMarker}
  107. for {
  108. lor, err := bucket.ListObjectVersions(options...)
  109. if err != nil {
  110. break
  111. }
  112. for _, object := range lor.ObjectDeleteMarkers {
  113. err = bucket.DeleteObject(object.Key, VersionId(object.VersionId))
  114. c.Assert(err, IsNil)
  115. }
  116. for _, object := range lor.ObjectVersions {
  117. err = bucket.DeleteObject(object.Key, VersionId(object.VersionId))
  118. c.Assert(err, IsNil)
  119. }
  120. keyMarker = KeyMarker(lor.NextKeyMarker)
  121. versionIdMarker := VersionIdMarker(lor.NextVersionIdMarker)
  122. options = []Option{keyMarker, versionIdMarker}
  123. if !lor.IsTruncated {
  124. break
  125. }
  126. }
  127. // Delete Part
  128. keyMarker = KeyMarker("")
  129. uploadIDMarker := UploadIDMarker("")
  130. for {
  131. lmur, err := bucket.ListMultipartUploads(keyMarker, uploadIDMarker)
  132. c.Assert(err, IsNil)
  133. for _, upload := range lmur.Uploads {
  134. var imur = InitiateMultipartUploadResult{Bucket: bucketName,
  135. Key: upload.Key, UploadID: upload.UploadID}
  136. err = bucket.AbortMultipartUpload(imur)
  137. c.Assert(err, IsNil)
  138. }
  139. keyMarker = KeyMarker(lmur.NextKeyMarker)
  140. uploadIDMarker = UploadIDMarker(lmur.NextUploadIDMarker)
  141. if !lmur.IsTruncated {
  142. break
  143. }
  144. }
  145. // delete live channel
  146. strMarker := ""
  147. for {
  148. result, err := bucket.ListLiveChannel(Marker(strMarker))
  149. c.Assert(err, IsNil)
  150. for _, channel := range result.LiveChannel {
  151. err := bucket.DeleteLiveChannel(channel.Name)
  152. c.Assert(err, IsNil)
  153. }
  154. if result.IsTruncated {
  155. strMarker = result.NextMarker
  156. } else {
  157. break
  158. }
  159. }
  160. // Delete Bucket
  161. err = client.DeleteBucket(bucketName)
  162. c.Assert(err, IsNil)
  163. }
  164. // SetUpSuite runs once when the suite starts running
  165. func (s *OssClientSuite) SetUpSuite(c *C) {
  166. client, err := New(endpoint, accessID, accessKey)
  167. c.Assert(err, IsNil)
  168. lbr, err := client.ListBuckets(Prefix(bucketNamePrefix), MaxKeys(1000))
  169. c.Assert(err, IsNil)
  170. for _, bucket := range lbr.Buckets {
  171. ForceDeleteBucket(client, bucket.Name, c)
  172. }
  173. testLogger.Println("test client started")
  174. }
  175. // TearDownSuite runs before each test or benchmark starts running
  176. func (s *OssClientSuite) TearDownSuite(c *C) {
  177. client, err := New(endpoint, accessID, accessKey)
  178. c.Assert(err, IsNil)
  179. lbr, err := client.ListBuckets(Prefix(bucketNamePrefix), MaxKeys(1000))
  180. c.Assert(err, IsNil)
  181. for _, bucket := range lbr.Buckets {
  182. s.deleteBucket(client, bucket.Name, c)
  183. }
  184. testLogger.Println("test client completed")
  185. }
  186. func (s *OssClientSuite) deleteBucket(client *Client, bucketName string, c *C) {
  187. ForceDeleteBucket(client, bucketName, c)
  188. }
  189. // SetUpTest runs after each test or benchmark runs
  190. func (s *OssClientSuite) SetUpTest(c *C) {
  191. }
  192. // TearDownTest runs once after all tests or benchmarks have finished running
  193. func (s *OssClientSuite) TearDownTest(c *C) {
  194. }
  195. // TestCreateBucket
  196. func (s *OssClientSuite) TestCreateBucket(c *C) {
  197. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  198. client, err := New(endpoint, accessID, accessKey)
  199. c.Assert(err, IsNil)
  200. // Create
  201. client.DeleteBucket(bucketNameTest)
  202. err = client.CreateBucket(bucketNameTest)
  203. c.Assert(err, IsNil)
  204. //sleep 3 seconds after create bucket
  205. time.Sleep(timeoutInOperation)
  206. // verify bucket is exist
  207. found, err := client.IsBucketExist(bucketNameTest)
  208. c.Assert(err, IsNil)
  209. c.Assert(found, Equals, true)
  210. res, err := client.GetBucketACL(bucketNameTest)
  211. c.Assert(err, IsNil)
  212. c.Assert(res.ACL, Equals, string(ACLPrivate))
  213. err = client.DeleteBucket(bucketNameTest)
  214. c.Assert(err, IsNil)
  215. time.Sleep(timeoutInOperation)
  216. // CreateBucket creates with ACLPublicRead
  217. err = client.CreateBucket(bucketNameTest, ACL(ACLPublicRead))
  218. c.Assert(err, IsNil)
  219. time.Sleep(timeoutInOperation)
  220. res, err = client.GetBucketACL(bucketNameTest)
  221. c.Assert(err, IsNil)
  222. c.Assert(res.ACL, Equals, string(ACLPublicRead))
  223. err = client.DeleteBucket(bucketNameTest)
  224. c.Assert(err, IsNil)
  225. time.Sleep(timeoutInOperation)
  226. // ACLPublicReadWrite
  227. err = client.CreateBucket(bucketNameTest, ACL(ACLPublicReadWrite))
  228. c.Assert(err, IsNil)
  229. time.Sleep(timeoutInOperation)
  230. res, err = client.GetBucketACL(bucketNameTest)
  231. c.Assert(err, IsNil)
  232. c.Assert(res.ACL, Equals, string(ACLPublicReadWrite))
  233. err = client.DeleteBucket(bucketNameTest)
  234. c.Assert(err, IsNil)
  235. time.Sleep(timeoutInOperation)
  236. // ACLPrivate
  237. err = client.CreateBucket(bucketNameTest, ACL(ACLPrivate))
  238. c.Assert(err, IsNil)
  239. time.Sleep(timeoutInOperation)
  240. res, err = client.GetBucketACL(bucketNameTest)
  241. c.Assert(err, IsNil)
  242. c.Assert(res.ACL, Equals, string(ACLPrivate))
  243. // Delete
  244. err = client.DeleteBucket(bucketNameTest)
  245. c.Assert(err, IsNil)
  246. // Create bucket with configuration and test GetBucketInfo
  247. for _, storage := range []StorageClassType{StorageStandard, StorageIA, StorageArchive, StorageColdArchive} {
  248. bucketNameTest := bucketNamePrefix + RandLowStr(6)
  249. err = client.CreateBucket(bucketNameTest, StorageClass(storage), ACL(ACLPublicRead))
  250. c.Assert(err, IsNil)
  251. time.Sleep(timeoutInOperation)
  252. res, err := client.GetBucketInfo(bucketNameTest)
  253. c.Assert(err, IsNil)
  254. c.Assert(res.BucketInfo.Name, Equals, bucketNameTest)
  255. c.Assert(res.BucketInfo.StorageClass, Equals, string(storage))
  256. c.Assert(res.BucketInfo.ACL, Equals, string(ACLPublicRead))
  257. // Delete
  258. err = client.DeleteBucket(bucketNameTest)
  259. c.Assert(err, IsNil)
  260. }
  261. // Error put bucket with configuration
  262. err = client.CreateBucket("ERRORBUCKETNAME", StorageClass(StorageArchive))
  263. c.Assert(err, NotNil)
  264. // Create bucket with configuration and test ListBuckets
  265. for _, storage := range []StorageClassType{StorageStandard, StorageIA, StorageArchive, StorageColdArchive} {
  266. bucketNameTest := bucketNamePrefix + RandLowStr(6)
  267. err = client.CreateBucket(bucketNameTest, StorageClass(storage))
  268. c.Assert(err, IsNil)
  269. time.Sleep(timeoutInOperation)
  270. res, err := client.GetBucketInfo(bucketNameTest)
  271. c.Assert(err, IsNil)
  272. c.Assert(res.BucketInfo.Name, Equals, bucketNameTest)
  273. c.Assert(res.BucketInfo.StorageClass, Equals, string(storage))
  274. // Delete
  275. err = client.DeleteBucket(bucketNameTest)
  276. c.Assert(err, IsNil)
  277. }
  278. }
  279. func (s *OssClientSuite) TestCreateBucketRedundancyType(c *C) {
  280. bucketNameTest := bucketNamePrefix + RandLowStr(6)
  281. client, err := New(endpoint, accessID, accessKey)
  282. c.Assert(err, IsNil)
  283. // CreateBucket creates without property
  284. err = client.CreateBucket(bucketNameTest)
  285. c.Assert(err, IsNil)
  286. client.DeleteBucket(bucketNameTest)
  287. time.Sleep(timeoutInOperation)
  288. // CreateBucket creates with RedundancyZRS
  289. err = client.CreateBucket(bucketNameTest, RedundancyType(RedundancyZRS))
  290. c.Assert(err, IsNil)
  291. res, err := client.GetBucketInfo(bucketNameTest)
  292. c.Assert(err, IsNil)
  293. c.Assert(res.BucketInfo.RedundancyType, Equals, string(RedundancyZRS))
  294. client.DeleteBucket(bucketNameTest)
  295. time.Sleep(timeoutInOperation)
  296. // CreateBucket creates with RedundancyLRS
  297. err = client.CreateBucket(bucketNameTest, RedundancyType(RedundancyLRS))
  298. c.Assert(err, IsNil)
  299. res, err = client.GetBucketInfo(bucketNameTest)
  300. c.Assert(err, IsNil)
  301. c.Assert(res.BucketInfo.RedundancyType, Equals, string(RedundancyLRS))
  302. c.Assert(res.BucketInfo.StorageClass, Equals, string(StorageStandard))
  303. client.DeleteBucket(bucketNameTest)
  304. time.Sleep(timeoutInOperation)
  305. // CreateBucket creates with ACLPublicRead RedundancyZRS
  306. err = client.CreateBucket(bucketNameTest, ACL(ACLPublicRead), RedundancyType(RedundancyZRS))
  307. c.Assert(err, IsNil)
  308. res, err = client.GetBucketInfo(bucketNameTest)
  309. c.Assert(err, IsNil)
  310. c.Assert(res.BucketInfo.RedundancyType, Equals, string(RedundancyZRS))
  311. c.Assert(res.BucketInfo.ACL, Equals, string(ACLPublicRead))
  312. client.DeleteBucket(bucketNameTest)
  313. }
  314. // TestCreateBucketNegative
  315. func (s *OssClientSuite) TestCreateBucketNegative(c *C) {
  316. client, err := New(endpoint, accessID, accessKey)
  317. c.Assert(err, IsNil)
  318. // Bucket name invalid
  319. err = client.CreateBucket("xx")
  320. c.Assert(err, NotNil)
  321. err = client.CreateBucket("XXXX")
  322. c.Assert(err, NotNil)
  323. testLogger.Println(err)
  324. err = client.CreateBucket("_bucket")
  325. c.Assert(err, NotNil)
  326. testLogger.Println(err)
  327. // ACL invalid
  328. err = client.CreateBucket(bucketNamePrefix+RandLowStr(6), ACL("InvaldAcl"))
  329. c.Assert(err, NotNil)
  330. testLogger.Println(err)
  331. }
  332. // TestDeleteBucket
  333. func (s *OssClientSuite) TestDeleteBucket(c *C) {
  334. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  335. client, err := New(endpoint, accessID, accessKey)
  336. c.Assert(err, IsNil)
  337. // Create
  338. err = client.CreateBucket(bucketNameTest)
  339. c.Assert(err, IsNil)
  340. time.Sleep(timeoutInOperation)
  341. // Check
  342. found, err := client.IsBucketExist(bucketNameTest)
  343. c.Assert(err, IsNil)
  344. c.Assert(found, Equals, true)
  345. // Delete
  346. err = client.DeleteBucket(bucketNameTest)
  347. c.Assert(err, IsNil)
  348. time.Sleep(timeoutInOperation)
  349. // Check
  350. found, err = client.IsBucketExist(bucketNameTest)
  351. c.Assert(err, IsNil)
  352. c.Assert(found, Equals, false)
  353. err = client.DeleteBucket(bucketNameTest)
  354. c.Assert(err, NotNil)
  355. }
  356. // TestDeleteBucketNegative
  357. func (s *OssClientSuite) TestDeleteBucketNegative(c *C) {
  358. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  359. client, err := New(endpoint, accessID, accessKey)
  360. c.Assert(err, IsNil)
  361. // Bucket name invalid
  362. err = client.DeleteBucket("xx")
  363. c.Assert(err, NotNil)
  364. err = client.DeleteBucket("XXXX")
  365. c.Assert(err, NotNil)
  366. err = client.DeleteBucket("_bucket")
  367. c.Assert(err, NotNil)
  368. // Delete no exist bucket
  369. err = client.DeleteBucket("notexist")
  370. c.Assert(err, NotNil)
  371. // No permission to delete, this ak/sk for js sdk
  372. err = client.CreateBucket(bucketNameTest)
  373. c.Assert(err, IsNil)
  374. accessID := "<accessKeyId>"
  375. accessKey := "<accessKeySecret>"
  376. clientOtherUser, err := New(endpoint, accessID, accessKey)
  377. c.Assert(err, IsNil)
  378. err = clientOtherUser.DeleteBucket(bucketNameTest)
  379. c.Assert(err, NotNil)
  380. err = client.DeleteBucket(bucketNameTest)
  381. c.Assert(err, IsNil)
  382. }
  383. // TestListBucket
  384. func (s *OssClientSuite) TestListBucket(c *C) {
  385. var prefix = bucketNamePrefix + RandLowStr(6)
  386. var bucketNameLbOne = prefix + "tlb1"
  387. var bucketNameLbTwo = prefix + "tlb2"
  388. var bucketNameLbThree = prefix + "tlb3"
  389. client, err := New(endpoint, accessID, accessKey)
  390. c.Assert(err, IsNil)
  391. // CreateBucket
  392. err = client.CreateBucket(bucketNameLbOne)
  393. c.Assert(err, IsNil)
  394. err = client.CreateBucket(bucketNameLbTwo)
  395. c.Assert(err, IsNil)
  396. err = client.CreateBucket(bucketNameLbThree)
  397. c.Assert(err, IsNil)
  398. // ListBuckets, specified prefix
  399. var respHeader http.Header
  400. lbr, err := client.ListBuckets(Prefix(prefix), MaxKeys(2), GetResponseHeader(&respHeader))
  401. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  402. c.Assert(err, IsNil)
  403. c.Assert(len(lbr.Buckets), Equals, 2)
  404. // ListBuckets, specified max keys
  405. lbr, err = client.ListBuckets(MaxKeys(2))
  406. c.Assert(err, IsNil)
  407. c.Assert(len(lbr.Buckets), Equals, 2)
  408. // ListBuckets, specified max keys
  409. lbr, err = client.ListBuckets(Marker(bucketNameLbOne), MaxKeys(1))
  410. c.Assert(err, IsNil)
  411. c.Assert(len(lbr.Buckets), Equals, 1)
  412. // ListBuckets, specified max keys
  413. lbr, err = client.ListBuckets(Marker(bucketNameLbOne))
  414. c.Assert(err, IsNil)
  415. c.Assert(len(lbr.Buckets) >= 2, Equals, true)
  416. // DeleteBucket
  417. err = client.DeleteBucket(bucketNameLbOne)
  418. c.Assert(err, IsNil)
  419. err = client.DeleteBucket(bucketNameLbTwo)
  420. c.Assert(err, IsNil)
  421. err = client.DeleteBucket(bucketNameLbThree)
  422. c.Assert(err, IsNil)
  423. }
  424. // TestListBucket
  425. func (s *OssClientSuite) TestIsBucketExist(c *C) {
  426. var prefix = bucketNamePrefix + RandLowStr(6)
  427. var bucketNameLbOne = prefix + "tibe1"
  428. var bucketNameLbTwo = prefix + "tibe11"
  429. var bucketNameLbThree = prefix + "tibe111"
  430. client, err := New(endpoint, accessID, accessKey)
  431. c.Assert(err, IsNil)
  432. // CreateBucket
  433. err = client.CreateBucket(bucketNameLbOne)
  434. c.Assert(err, IsNil)
  435. err = client.CreateBucket(bucketNameLbTwo)
  436. c.Assert(err, IsNil)
  437. err = client.CreateBucket(bucketNameLbThree)
  438. c.Assert(err, IsNil)
  439. // Exist
  440. exist, err := client.IsBucketExist(bucketNameLbTwo)
  441. c.Assert(err, IsNil)
  442. c.Assert(exist, Equals, true)
  443. exist, err = client.IsBucketExist(bucketNameLbThree)
  444. c.Assert(err, IsNil)
  445. c.Assert(exist, Equals, true)
  446. exist, err = client.IsBucketExist(bucketNameLbOne)
  447. c.Assert(err, IsNil)
  448. c.Assert(exist, Equals, true)
  449. // Not exist
  450. exist, err = client.IsBucketExist(prefix + "tibe")
  451. c.Assert(err, IsNil)
  452. c.Assert(exist, Equals, false)
  453. exist, err = client.IsBucketExist(prefix + "tibe1111")
  454. c.Assert(err, IsNil)
  455. c.Assert(exist, Equals, false)
  456. // Negative
  457. exist, err = client.IsBucketExist("BucketNameInvalid")
  458. c.Assert(err, NotNil)
  459. // DeleteBucket
  460. err = client.DeleteBucket(bucketNameLbOne)
  461. c.Assert(err, IsNil)
  462. err = client.DeleteBucket(bucketNameLbTwo)
  463. c.Assert(err, IsNil)
  464. err = client.DeleteBucket(bucketNameLbThree)
  465. c.Assert(err, IsNil)
  466. }
  467. // TestSetBucketAcl
  468. func (s *OssClientSuite) TestSetBucketAcl(c *C) {
  469. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  470. client, err := New(endpoint, accessID, accessKey)
  471. c.Assert(err, IsNil)
  472. // Private
  473. err = client.CreateBucket(bucketNameTest)
  474. c.Assert(err, IsNil)
  475. res, err := client.GetBucketACL(bucketNameTest)
  476. c.Assert(err, IsNil)
  477. c.Assert(res.ACL, Equals, string(ACLPrivate))
  478. // Set ACL_PUBLIC_R
  479. err = client.SetBucketACL(bucketNameTest, ACLPublicRead)
  480. c.Assert(err, IsNil)
  481. time.Sleep(timeoutInOperation)
  482. res, err = client.GetBucketACL(bucketNameTest)
  483. c.Assert(err, IsNil)
  484. c.Assert(res.ACL, Equals, string(ACLPublicRead))
  485. // Set ACL_PUBLIC_RW
  486. err = client.SetBucketACL(bucketNameTest, ACLPublicReadWrite)
  487. c.Assert(err, IsNil)
  488. time.Sleep(timeoutInOperation)
  489. res, err = client.GetBucketACL(bucketNameTest)
  490. c.Assert(err, IsNil)
  491. c.Assert(res.ACL, Equals, string(ACLPublicReadWrite))
  492. // Set ACL_PUBLIC_RW
  493. err = client.SetBucketACL(bucketNameTest, ACLPrivate)
  494. c.Assert(err, IsNil)
  495. time.Sleep(timeoutInOperation)
  496. res, err = client.GetBucketACL(bucketNameTest)
  497. c.Assert(err, IsNil)
  498. c.Assert(res.ACL, Equals, string(ACLPrivate))
  499. err = client.DeleteBucket(bucketNameTest)
  500. c.Assert(err, IsNil)
  501. }
  502. // TestSetBucketAclNegative
  503. func (s *OssClientSuite) TestBucketAclNegative(c *C) {
  504. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  505. client, err := New(endpoint, accessID, accessKey)
  506. c.Assert(err, IsNil)
  507. err = client.CreateBucket(bucketNameTest)
  508. c.Assert(err, IsNil)
  509. err = client.SetBucketACL(bucketNameTest, "InvalidACL")
  510. c.Assert(err, NotNil)
  511. testLogger.Println(err)
  512. err = client.DeleteBucket(bucketNameTest)
  513. c.Assert(err, IsNil)
  514. }
  515. // TestGetBucketAcl
  516. func (s *OssClientSuite) TestGetBucketAcl(c *C) {
  517. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  518. client, err := New(endpoint, accessID, accessKey)
  519. c.Assert(err, IsNil)
  520. // Private
  521. err = client.CreateBucket(bucketNameTest)
  522. c.Assert(err, IsNil)
  523. time.Sleep(timeoutInOperation)
  524. res, err := client.GetBucketACL(bucketNameTest)
  525. c.Assert(err, IsNil)
  526. c.Assert(res.ACL, Equals, string(ACLPrivate))
  527. err = client.DeleteBucket(bucketNameTest)
  528. c.Assert(err, IsNil)
  529. time.Sleep(timeoutInOperation)
  530. // PublicRead
  531. err = client.CreateBucket(bucketNameTest, ACL(ACLPublicRead))
  532. c.Assert(err, IsNil)
  533. time.Sleep(timeoutInOperation)
  534. res, err = client.GetBucketACL(bucketNameTest)
  535. c.Assert(err, IsNil)
  536. c.Assert(res.ACL, Equals, string(ACLPublicRead))
  537. err = client.DeleteBucket(bucketNameTest)
  538. c.Assert(err, IsNil)
  539. time.Sleep(timeoutInOperation)
  540. // PublicReadWrite
  541. err = client.CreateBucket(bucketNameTest, ACL(ACLPublicReadWrite))
  542. c.Assert(err, IsNil)
  543. time.Sleep(timeoutInOperation)
  544. res, err = client.GetBucketACL(bucketNameTest)
  545. c.Assert(err, IsNil)
  546. c.Assert(res.ACL, Equals, string(ACLPublicReadWrite))
  547. err = client.DeleteBucket(bucketNameTest)
  548. c.Assert(err, IsNil)
  549. }
  550. // TestGetBucketAcl
  551. func (s *OssClientSuite) TestGetBucketLocation(c *C) {
  552. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  553. client, err := New(endpoint, accessID, accessKey)
  554. c.Assert(err, IsNil)
  555. // Private
  556. err = client.CreateBucket(bucketNameTest)
  557. c.Assert(err, IsNil)
  558. loc, err := client.GetBucketLocation(bucketNameTest)
  559. c.Assert(strings.HasPrefix(loc, "oss-"), Equals, true)
  560. err = client.DeleteBucket(bucketNameTest)
  561. c.Assert(err, IsNil)
  562. }
  563. // TestGetBucketLocationNegative
  564. func (s *OssClientSuite) TestGetBucketLocationNegative(c *C) {
  565. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  566. client, err := New(endpoint, accessID, accessKey)
  567. c.Assert(err, IsNil)
  568. // Not exist
  569. _, err = client.GetBucketLocation(bucketNameTest)
  570. c.Assert(err, NotNil)
  571. // Not exist
  572. _, err = client.GetBucketLocation("InvalidBucketName_")
  573. c.Assert(err, NotNil)
  574. }
  575. // TestSetBucketLifecycle
  576. func (s *OssClientSuite) TestSetBucketLifecycle(c *C) {
  577. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  578. var rule1 = BuildLifecycleRuleByDate("rule1", "one", true, 2015, 11, 11)
  579. var rule2 = BuildLifecycleRuleByDays("rule2", "two", true, 3)
  580. client, err := New(endpoint, accessID, accessKey)
  581. c.Assert(err, IsNil)
  582. err = client.CreateBucket(bucketNameTest)
  583. c.Assert(err, IsNil)
  584. // Set single rule
  585. var rules = []LifecycleRule{rule1}
  586. err = client.SetBucketLifecycle(bucketNameTest, rules)
  587. c.Assert(err, IsNil)
  588. // Double set rule
  589. err = client.SetBucketLifecycle(bucketNameTest, rules)
  590. c.Assert(err, IsNil)
  591. res, err := client.GetBucketLifecycle(bucketNameTest)
  592. c.Assert(err, IsNil)
  593. c.Assert(len(res.Rules), Equals, 1)
  594. c.Assert(res.Rules[0].ID, Equals, "rule1")
  595. err = client.DeleteBucketLifecycle(bucketNameTest)
  596. c.Assert(err, IsNil)
  597. // Set two rules
  598. rules = []LifecycleRule{rule1, rule2}
  599. err = client.SetBucketLifecycle(bucketNameTest, rules)
  600. c.Assert(err, IsNil)
  601. // Eliminate effect of cache
  602. time.Sleep(timeoutInOperation)
  603. res, err = client.GetBucketLifecycle(bucketNameTest)
  604. c.Assert(err, IsNil)
  605. c.Assert(len(res.Rules), Equals, 2)
  606. c.Assert(res.Rules[0].ID, Equals, "rule1")
  607. c.Assert(res.Rules[1].ID, Equals, "rule2")
  608. err = client.DeleteBucket(bucketNameTest)
  609. c.Assert(err, IsNil)
  610. }
  611. // TestSetBucketLifecycleNew
  612. func (s *OssClientSuite) TestSetBucketLifecycleNew(c *C) {
  613. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  614. client, err := New(endpoint, accessID, accessKey)
  615. c.Assert(err, IsNil)
  616. err = client.CreateBucket(bucketNameTest)
  617. c.Assert(err, IsNil)
  618. //invalid status of lifecyclerule
  619. expiration := LifecycleExpiration{
  620. Days: 30,
  621. }
  622. rule := LifecycleRule{
  623. ID: "rule1",
  624. Prefix: "one",
  625. Status: "Invalid",
  626. Expiration: &expiration,
  627. }
  628. rules := []LifecycleRule{rule}
  629. err = client.SetBucketLifecycle(bucketNameTest, rules)
  630. c.Assert(err, NotNil)
  631. //invalid value of CreatedBeforeDate
  632. expiration = LifecycleExpiration{
  633. CreatedBeforeDate: RandStr(10),
  634. }
  635. rule = LifecycleRule{
  636. ID: "rule1",
  637. Prefix: "one",
  638. Status: "Enabled",
  639. Expiration: &expiration,
  640. }
  641. rules = []LifecycleRule{rule}
  642. err = client.SetBucketLifecycle(bucketNameTest, rules)
  643. c.Assert(err, NotNil)
  644. //invalid value of Days
  645. abortMPU := LifecycleAbortMultipartUpload{
  646. Days: -30,
  647. }
  648. rule = LifecycleRule{
  649. ID: "rule1",
  650. Prefix: "one",
  651. Status: "Enabled",
  652. AbortMultipartUpload: &abortMPU,
  653. }
  654. rules = []LifecycleRule{rule}
  655. err = client.SetBucketLifecycle(bucketNameTest, rules)
  656. c.Assert(err, NotNil)
  657. expiration = LifecycleExpiration{
  658. CreatedBeforeDate: "2015-11-11T00:00:00.000Z",
  659. }
  660. rule1 := LifecycleRule{
  661. ID: "rule1",
  662. Prefix: "one",
  663. Status: "Enabled",
  664. Expiration: &expiration,
  665. }
  666. abortMPU = LifecycleAbortMultipartUpload{
  667. Days: 30,
  668. }
  669. rule2 := LifecycleRule{
  670. ID: "rule2",
  671. Prefix: "two",
  672. Status: "Enabled",
  673. Expiration: &expiration,
  674. AbortMultipartUpload: &abortMPU,
  675. }
  676. transition1 := LifecycleTransition{
  677. Days: 3,
  678. StorageClass: StorageIA,
  679. }
  680. transition2 := LifecycleTransition{
  681. Days: 30,
  682. StorageClass: StorageArchive,
  683. }
  684. transitions := []LifecycleTransition{transition1, transition2}
  685. rule3 := LifecycleRule{
  686. ID: "rule3",
  687. Prefix: "three",
  688. Status: "Enabled",
  689. AbortMultipartUpload: &abortMPU,
  690. Transitions: transitions,
  691. }
  692. // Set single rule
  693. rules = []LifecycleRule{rule1}
  694. err = client.SetBucketLifecycle(bucketNameTest, rules)
  695. c.Assert(err, IsNil)
  696. res, err := client.GetBucketLifecycle(bucketNameTest)
  697. c.Assert(err, IsNil)
  698. c.Assert(len(res.Rules), Equals, 1)
  699. c.Assert(res.Rules[0].ID, Equals, "rule1")
  700. c.Assert(res.Rules[0].Expiration, NotNil)
  701. c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
  702. err = client.DeleteBucketLifecycle(bucketNameTest)
  703. c.Assert(err, IsNil)
  704. // Set two rule: rule1 and rule2
  705. rules = []LifecycleRule{rule1, rule2}
  706. err = client.SetBucketLifecycle(bucketNameTest, rules)
  707. c.Assert(err, IsNil)
  708. res, err = client.GetBucketLifecycle(bucketNameTest)
  709. c.Assert(err, IsNil)
  710. c.Assert(len(res.Rules), Equals, 2)
  711. c.Assert(res.Rules[0].ID, Equals, "rule1")
  712. c.Assert(res.Rules[0].Expiration, NotNil)
  713. c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
  714. c.Assert(res.Rules[1].ID, Equals, "rule2")
  715. c.Assert(res.Rules[1].Expiration, NotNil)
  716. c.Assert(res.Rules[1].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
  717. c.Assert(res.Rules[1].AbortMultipartUpload, NotNil)
  718. c.Assert(res.Rules[1].AbortMultipartUpload.Days, Equals, 30)
  719. err = client.DeleteBucketLifecycle(bucketNameTest)
  720. c.Assert(err, IsNil)
  721. // Set two rule: rule2 and rule3
  722. rules = []LifecycleRule{rule2, rule3}
  723. err = client.SetBucketLifecycle(bucketNameTest, rules)
  724. c.Assert(err, IsNil)
  725. res, err = client.GetBucketLifecycle(bucketNameTest)
  726. c.Assert(err, IsNil)
  727. c.Assert(len(res.Rules), Equals, 2)
  728. c.Assert(res.Rules[0].ID, Equals, "rule2")
  729. c.Assert(res.Rules[0].Expiration, NotNil)
  730. c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
  731. c.Assert(res.Rules[0].AbortMultipartUpload, NotNil)
  732. c.Assert(res.Rules[0].AbortMultipartUpload.Days, Equals, 30)
  733. c.Assert(res.Rules[1].ID, Equals, "rule3")
  734. c.Assert(res.Rules[1].AbortMultipartUpload, NotNil)
  735. c.Assert(res.Rules[1].AbortMultipartUpload.Days, Equals, 30)
  736. c.Assert(len(res.Rules[1].Transitions), Equals, 2)
  737. c.Assert(res.Rules[1].Transitions[0].StorageClass, Equals, StorageIA)
  738. c.Assert(res.Rules[1].Transitions[0].Days, Equals, 3)
  739. c.Assert(res.Rules[1].Transitions[1].StorageClass, Equals, StorageArchive)
  740. c.Assert(res.Rules[1].Transitions[1].Days, Equals, 30)
  741. err = client.DeleteBucketLifecycle(bucketNameTest)
  742. c.Assert(err, IsNil)
  743. // Set two rule: rule1 and rule3
  744. rules = []LifecycleRule{rule1, rule3}
  745. err = client.SetBucketLifecycle(bucketNameTest, rules)
  746. c.Assert(err, IsNil)
  747. res, err = client.GetBucketLifecycle(bucketNameTest)
  748. c.Assert(err, IsNil)
  749. c.Assert(len(res.Rules), Equals, 2)
  750. c.Assert(res.Rules[0].ID, Equals, "rule1")
  751. c.Assert(res.Rules[0].Expiration, NotNil)
  752. c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
  753. c.Assert(res.Rules[1].ID, Equals, "rule3")
  754. c.Assert(res.Rules[1].AbortMultipartUpload, NotNil)
  755. c.Assert(res.Rules[1].AbortMultipartUpload.Days, Equals, 30)
  756. c.Assert(len(res.Rules[1].Transitions), Equals, 2)
  757. c.Assert(res.Rules[1].Transitions[0].StorageClass, Equals, StorageIA)
  758. c.Assert(res.Rules[1].Transitions[0].Days, Equals, 3)
  759. c.Assert(res.Rules[1].Transitions[1].StorageClass, Equals, StorageArchive)
  760. c.Assert(res.Rules[1].Transitions[1].Days, Equals, 30)
  761. err = client.DeleteBucketLifecycle(bucketNameTest)
  762. c.Assert(err, IsNil)
  763. // Set three rules
  764. rules = []LifecycleRule{rule1, rule2, rule3}
  765. err = client.SetBucketLifecycle(bucketNameTest, rules)
  766. c.Assert(err, IsNil)
  767. res, err = client.GetBucketLifecycle(bucketNameTest)
  768. c.Assert(err, IsNil)
  769. c.Assert(len(res.Rules), Equals, 3)
  770. c.Assert(res.Rules[0].ID, Equals, "rule1")
  771. c.Assert(res.Rules[0].Expiration, NotNil)
  772. c.Assert(res.Rules[0].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
  773. c.Assert(res.Rules[1].ID, Equals, "rule2")
  774. c.Assert(res.Rules[1].Expiration, NotNil)
  775. c.Assert(res.Rules[1].Expiration.CreatedBeforeDate, Equals, "2015-11-11T00:00:00.000Z")
  776. c.Assert(res.Rules[1].AbortMultipartUpload, NotNil)
  777. c.Assert(res.Rules[1].AbortMultipartUpload.Days, Equals, 30)
  778. c.Assert(res.Rules[2].ID, Equals, "rule3")
  779. c.Assert(res.Rules[2].AbortMultipartUpload, NotNil)
  780. c.Assert(res.Rules[2].AbortMultipartUpload.Days, Equals, 30)
  781. c.Assert(len(res.Rules[2].Transitions), Equals, 2)
  782. c.Assert(res.Rules[2].Transitions[0].StorageClass, Equals, StorageIA)
  783. c.Assert(res.Rules[2].Transitions[0].Days, Equals, 3)
  784. c.Assert(res.Rules[2].Transitions[1].StorageClass, Equals, StorageArchive)
  785. c.Assert(res.Rules[2].Transitions[1].Days, Equals, 30)
  786. err = client.DeleteBucket(bucketNameTest)
  787. c.Assert(err, IsNil)
  788. }
  789. // TestSetBucketLifecycleAboutVersionObject
  790. func (s *OssClientSuite) TestSetBucketLifecycleAboutVersionObject(c *C) {
  791. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  792. client, err := New(endpoint, accessID, accessKey)
  793. c.Assert(err, IsNil)
  794. err = client.CreateBucket(bucketNameTest)
  795. c.Assert(err, IsNil)
  796. deleteMark := true
  797. expiration := LifecycleExpiration{
  798. ExpiredObjectDeleteMarker: &deleteMark,
  799. }
  800. versionExpiration := LifecycleVersionExpiration{
  801. NoncurrentDays: 20,
  802. }
  803. versionTransition := LifecycleVersionTransition{
  804. NoncurrentDays: 10,
  805. StorageClass: "IA",
  806. }
  807. rule := LifecycleRule{
  808. Status: "Enabled",
  809. Expiration: &expiration,
  810. NonVersionExpiration: &versionExpiration,
  811. NonVersionTransition: &versionTransition,
  812. }
  813. rules := []LifecycleRule{rule}
  814. err = client.SetBucketLifecycle(bucketNameTest, rules)
  815. c.Assert(err, IsNil)
  816. res, err := client.GetBucketLifecycle(bucketNameTest)
  817. c.Assert(err, IsNil)
  818. c.Assert(res.Rules[0].Expiration, NotNil)
  819. c.Assert(res.Rules[0].Expiration.Days, Equals, 0)
  820. c.Assert(res.Rules[0].Expiration.Date, Equals, "")
  821. c.Assert(*(res.Rules[0].Expiration.ExpiredObjectDeleteMarker), Equals, true)
  822. c.Assert(res.Rules[0].NonVersionExpiration.NoncurrentDays, Equals, 20)
  823. c.Assert(res.Rules[0].NonVersionTransition.NoncurrentDays, Equals, 10)
  824. c.Assert(res.Rules[0].NonVersionTransition.StorageClass, Equals, StorageClassType("IA"))
  825. err = client.DeleteBucket(bucketNameTest)
  826. c.Assert(err, IsNil)
  827. }
  828. // TestSetBucketLifecycleAboutVersionObject
  829. func (s *OssClientSuite) TestSetBucketLifecycleAboutVersionObjectError(c *C) {
  830. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  831. client, err := New(endpoint, accessID, accessKey)
  832. c.Assert(err, IsNil)
  833. err = client.CreateBucket(bucketNameTest)
  834. c.Assert(err, IsNil)
  835. deleteMark := true
  836. expiration := LifecycleExpiration{
  837. ExpiredObjectDeleteMarker: &deleteMark,
  838. }
  839. versionExpiration := LifecycleVersionExpiration{
  840. NoncurrentDays: 20,
  841. }
  842. versionTransition := LifecycleVersionTransition{
  843. NoncurrentDays: 10,
  844. StorageClass: "IA",
  845. }
  846. // NonVersionTransition and NonVersionTransitions can not both have value
  847. rule := LifecycleRule{
  848. Status: "Enabled",
  849. Expiration: &expiration,
  850. NonVersionExpiration: &versionExpiration,
  851. NonVersionTransition: &versionTransition,
  852. NonVersionTransitions: []LifecycleVersionTransition{versionTransition},
  853. }
  854. rules := []LifecycleRule{rule}
  855. err = client.SetBucketLifecycle(bucketNameTest, rules)
  856. c.Assert(err, NotNil)
  857. err = client.DeleteBucket(bucketNameTest)
  858. c.Assert(err, IsNil)
  859. }
  860. // TestSetBucketLifecycleAboutVersionObject
  861. func (s *OssClientSuite) TestSetBucketLifecycleAboutVersionObjectNew(c *C) {
  862. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  863. client, err := New(endpoint, accessID, accessKey)
  864. c.Assert(err, IsNil)
  865. err = client.CreateBucket(bucketNameTest)
  866. c.Assert(err, IsNil)
  867. deleteMark := true
  868. expiration := LifecycleExpiration{
  869. ExpiredObjectDeleteMarker: &deleteMark,
  870. }
  871. versionExpiration := LifecycleVersionExpiration{
  872. NoncurrentDays: 20,
  873. }
  874. versionTransition1 := LifecycleVersionTransition{
  875. NoncurrentDays: 10,
  876. StorageClass: "IA",
  877. }
  878. versionTransition2 := LifecycleVersionTransition{
  879. NoncurrentDays: 20,
  880. StorageClass: "ColdArchive",
  881. }
  882. rule := LifecycleRule{
  883. Status: "Enabled",
  884. Expiration: &expiration,
  885. NonVersionExpiration: &versionExpiration,
  886. NonVersionTransitions: []LifecycleVersionTransition{versionTransition1, versionTransition2},
  887. }
  888. rules := []LifecycleRule{rule}
  889. err = client.SetBucketLifecycle(bucketNameTest, rules)
  890. c.Assert(err, IsNil)
  891. res, err := client.GetBucketLifecycle(bucketNameTest)
  892. c.Assert(err, IsNil)
  893. c.Assert(res.Rules[0].Expiration, NotNil)
  894. c.Assert(res.Rules[0].Expiration.Days, Equals, 0)
  895. c.Assert(res.Rules[0].Expiration.Date, Equals, "")
  896. c.Assert(*(res.Rules[0].Expiration.ExpiredObjectDeleteMarker), Equals, true)
  897. c.Assert(res.Rules[0].NonVersionExpiration.NoncurrentDays, Equals, 20)
  898. c.Assert(res.Rules[0].NonVersionTransition.NoncurrentDays, Equals, 10)
  899. c.Assert(res.Rules[0].NonVersionTransition.StorageClass, Equals, StorageClassType("IA"))
  900. c.Assert(len(res.Rules[0].NonVersionTransitions),Equals, 2)
  901. err = client.DeleteBucket(bucketNameTest)
  902. c.Assert(err, IsNil)
  903. }
  904. // TestDeleteBucketLifecycle
  905. func (s *OssClientSuite) TestDeleteBucketLifecycle(c *C) {
  906. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  907. var rule1 = BuildLifecycleRuleByDate("rule1", "one", true, 2015, 11, 11)
  908. var rule2 = BuildLifecycleRuleByDays("rule2", "two", true, 3)
  909. var rules = []LifecycleRule{rule1, rule2}
  910. client, err := New(endpoint, accessID, accessKey)
  911. c.Assert(err, IsNil)
  912. err = client.CreateBucket(bucketNameTest)
  913. c.Assert(err, IsNil)
  914. //time.Sleep(timeoutInOperation)
  915. err = client.DeleteBucketLifecycle(bucketNameTest)
  916. c.Assert(err, IsNil)
  917. err = client.SetBucketLifecycle(bucketNameTest, rules)
  918. c.Assert(err, IsNil)
  919. //time.Sleep(timeoutInOperation)
  920. res, err := client.GetBucketLifecycle(bucketNameTest)
  921. c.Assert(err, IsNil)
  922. c.Assert(len(res.Rules), Equals, 2)
  923. // Delete
  924. err = client.DeleteBucketLifecycle(bucketNameTest)
  925. c.Assert(err, IsNil)
  926. //time.Sleep(timeoutInOperation)
  927. res, err = client.GetBucketLifecycle(bucketNameTest)
  928. c.Assert(err, NotNil)
  929. // Eliminate effect of cache
  930. //time.Sleep(timeoutInOperation)
  931. // Delete when not set
  932. err = client.DeleteBucketLifecycle(bucketNameTest)
  933. c.Assert(err, IsNil)
  934. err = client.DeleteBucket(bucketNameTest)
  935. c.Assert(err, IsNil)
  936. }
  937. // TestSetBucketLifecycleNegative
  938. func (s *OssClientSuite) TestBucketLifecycleNegative(c *C) {
  939. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  940. var rules = []LifecycleRule{}
  941. client, err := New(endpoint, accessID, accessKey)
  942. c.Assert(err, IsNil)
  943. err = client.CreateBucket(bucketNameTest)
  944. c.Assert(err, IsNil)
  945. // Set with no rule
  946. err = client.SetBucketLifecycle(bucketNameTest, rules)
  947. c.Assert(err, NotNil)
  948. err = client.DeleteBucket(bucketNameTest)
  949. c.Assert(err, IsNil)
  950. // Not exist
  951. err = client.SetBucketLifecycle(bucketNameTest, rules)
  952. c.Assert(err, NotNil)
  953. // Not exist
  954. _, err = client.GetBucketLifecycle(bucketNameTest)
  955. c.Assert(err, NotNil)
  956. // Not exist
  957. err = client.DeleteBucketLifecycle(bucketNameTest)
  958. c.Assert(err, NotNil)
  959. }
  960. // TestSetBucketReferer
  961. func (s *OssClientSuite) TestSetBucketReferer(c *C) {
  962. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  963. var referers = []string{"http://www.aliyun.com", "https://www.aliyun.com"}
  964. client, err := New(endpoint, accessID, accessKey)
  965. c.Assert(err, IsNil)
  966. err = client.CreateBucket(bucketNameTest)
  967. c.Assert(err, IsNil)
  968. time.Sleep(timeoutInOperation)
  969. res, err := client.GetBucketReferer(bucketNameTest)
  970. c.Assert(res.AllowEmptyReferer, Equals, true)
  971. c.Assert(len(res.RefererList), Equals, 0)
  972. // Set referers
  973. err = client.SetBucketReferer(bucketNameTest, referers, false)
  974. c.Assert(err, IsNil)
  975. time.Sleep(timeoutInOperation)
  976. res, err = client.GetBucketReferer(bucketNameTest)
  977. c.Assert(res.AllowEmptyReferer, Equals, false)
  978. c.Assert(len(res.RefererList), Equals, 2)
  979. c.Assert(res.RefererList[0], Equals, "http://www.aliyun.com")
  980. c.Assert(res.RefererList[1], Equals, "https://www.aliyun.com")
  981. // Reset referer, referers empty
  982. referers = []string{""}
  983. err = client.SetBucketReferer(bucketNameTest, referers, true)
  984. c.Assert(err, IsNil)
  985. referers = []string{}
  986. err = client.SetBucketReferer(bucketNameTest, referers, true)
  987. c.Assert(err, IsNil)
  988. res, err = client.GetBucketReferer(bucketNameTest)
  989. c.Assert(res.AllowEmptyReferer, Equals, true)
  990. c.Assert(len(res.RefererList), Equals, 0)
  991. err = client.DeleteBucket(bucketNameTest)
  992. c.Assert(err, IsNil)
  993. }
  994. // TestSetBucketRefererNegative
  995. func (s *OssClientSuite) TestBucketRefererNegative(c *C) {
  996. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  997. var referers = []string{""}
  998. client, err := New(endpoint, accessID, accessKey)
  999. c.Assert(err, IsNil)
  1000. // Not exist
  1001. _, err = client.GetBucketReferer(bucketNameTest)
  1002. c.Assert(err, NotNil)
  1003. testLogger.Println(err)
  1004. // Not exist
  1005. err = client.SetBucketReferer(bucketNameTest, referers, true)
  1006. c.Assert(err, NotNil)
  1007. testLogger.Println(err)
  1008. }
  1009. // TestSetBucketLogging
  1010. func (s *OssClientSuite) TestSetBucketLogging(c *C) {
  1011. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1012. var bucketNameTarget = bucketNameTest + "-target"
  1013. client, err := New(endpoint, accessID, accessKey)
  1014. c.Assert(err, IsNil)
  1015. err = client.CreateBucket(bucketNameTest)
  1016. c.Assert(err, IsNil)
  1017. err = client.CreateBucket(bucketNameTarget)
  1018. c.Assert(err, IsNil)
  1019. time.Sleep(timeoutInOperation)
  1020. // Set logging
  1021. err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", true)
  1022. c.Assert(err, IsNil)
  1023. // Reset
  1024. err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", false)
  1025. c.Assert(err, IsNil)
  1026. time.Sleep(timeoutInOperation)
  1027. res, err := client.GetBucketLogging(bucketNameTest)
  1028. c.Assert(err, IsNil)
  1029. c.Assert(res.LoggingEnabled.TargetBucket, Equals, "")
  1030. c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "")
  1031. err = client.DeleteBucketLogging(bucketNameTest)
  1032. c.Assert(err, IsNil)
  1033. // Set to self
  1034. err = client.SetBucketLogging(bucketNameTest, bucketNameTest, "prefix", true)
  1035. c.Assert(err, IsNil)
  1036. err = client.DeleteBucket(bucketNameTest)
  1037. c.Assert(err, IsNil)
  1038. err = client.DeleteBucket(bucketNameTarget)
  1039. c.Assert(err, IsNil)
  1040. }
  1041. // TestDeleteBucketLogging
  1042. func (s *OssClientSuite) TestDeleteBucketLogging(c *C) {
  1043. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1044. var bucketNameTarget = bucketNameTest + "-target"
  1045. client, err := New(endpoint, accessID, accessKey)
  1046. c.Assert(err, IsNil)
  1047. err = client.CreateBucket(bucketNameTest)
  1048. c.Assert(err, IsNil)
  1049. err = client.CreateBucket(bucketNameTarget)
  1050. c.Assert(err, IsNil)
  1051. time.Sleep(timeoutInOperation)
  1052. // Get when not set
  1053. res, err := client.GetBucketLogging(bucketNameTest)
  1054. c.Assert(err, IsNil)
  1055. c.Assert(res.LoggingEnabled.TargetBucket, Equals, "")
  1056. c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "")
  1057. // Set
  1058. err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", true)
  1059. c.Assert(err, IsNil)
  1060. // Get
  1061. time.Sleep(timeoutInOperation)
  1062. res, err = client.GetBucketLogging(bucketNameTest)
  1063. c.Assert(err, IsNil)
  1064. c.Assert(res.LoggingEnabled.TargetBucket, Equals, bucketNameTarget)
  1065. c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "prefix")
  1066. // Set
  1067. err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", false)
  1068. c.Assert(err, IsNil)
  1069. // Get
  1070. time.Sleep(timeoutInOperation)
  1071. res, err = client.GetBucketLogging(bucketNameTest)
  1072. c.Assert(err, IsNil)
  1073. c.Assert(res.LoggingEnabled.TargetBucket, Equals, "")
  1074. c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "")
  1075. // Delete
  1076. err = client.DeleteBucketLogging(bucketNameTest)
  1077. c.Assert(err, IsNil)
  1078. // Get after delete
  1079. time.Sleep(timeoutInOperation)
  1080. res, err = client.GetBucketLogging(bucketNameTest)
  1081. c.Assert(err, IsNil)
  1082. c.Assert(res.LoggingEnabled.TargetBucket, Equals, "")
  1083. c.Assert(res.LoggingEnabled.TargetPrefix, Equals, "")
  1084. err = client.DeleteBucket(bucketNameTest)
  1085. c.Assert(err, IsNil)
  1086. err = client.DeleteBucket(bucketNameTarget)
  1087. c.Assert(err, IsNil)
  1088. }
  1089. // TestSetBucketLoggingNegative
  1090. func (s *OssClientSuite) TestSetBucketLoggingNegative(c *C) {
  1091. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1092. var bucketNameTarget = bucketNameTest + "-target"
  1093. client, err := New(endpoint, accessID, accessKey)
  1094. c.Assert(err, IsNil)
  1095. // Not exist
  1096. _, err = client.GetBucketLogging(bucketNameTest)
  1097. c.Assert(err, NotNil)
  1098. // Not exist
  1099. err = client.SetBucketLogging(bucketNameTest, "targetbucket", "prefix", true)
  1100. c.Assert(err, NotNil)
  1101. // Not exist
  1102. err = client.DeleteBucketLogging(bucketNameTest)
  1103. c.Assert(err, NotNil)
  1104. err = client.CreateBucket(bucketNameTest)
  1105. c.Assert(err, IsNil)
  1106. time.Sleep(timeoutInOperation)
  1107. // Target bucket not exist
  1108. err = client.SetBucketLogging(bucketNameTest, bucketNameTarget, "prefix", true)
  1109. c.Assert(err, NotNil)
  1110. // Parameter invalid
  1111. err = client.SetBucketLogging(bucketNameTest, "XXXX", "prefix", true)
  1112. c.Assert(err, NotNil)
  1113. err = client.SetBucketLogging(bucketNameTest, "xx", "prefix", true)
  1114. c.Assert(err, NotNil)
  1115. err = client.DeleteBucket(bucketNameTest)
  1116. c.Assert(err, IsNil)
  1117. }
  1118. // TestSetBucketWebsite
  1119. func (s *OssClientSuite) TestSetBucketWebsite(c *C) {
  1120. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1121. var indexWebsite = "myindex.html"
  1122. var errorWebsite = "myerror.html"
  1123. client, err := New(endpoint, accessID, accessKey)
  1124. c.Assert(err, IsNil)
  1125. time.Sleep(timeoutInOperation)
  1126. err = client.CreateBucket(bucketNameTest)
  1127. c.Assert(err, IsNil)
  1128. // Set
  1129. err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
  1130. c.Assert(err, IsNil)
  1131. // Double set
  1132. err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
  1133. c.Assert(err, IsNil)
  1134. res, err := client.GetBucketWebsite(bucketNameTest)
  1135. c.Assert(err, IsNil)
  1136. c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
  1137. c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
  1138. // Reset
  1139. err = client.SetBucketWebsite(bucketNameTest, "your"+indexWebsite, "your"+errorWebsite)
  1140. c.Assert(err, IsNil)
  1141. time.Sleep(timeoutInOperation)
  1142. res, err = client.GetBucketWebsite(bucketNameTest)
  1143. c.Assert(err, IsNil)
  1144. c.Assert(res.IndexDocument.Suffix, Equals, "your"+indexWebsite)
  1145. c.Assert(res.ErrorDocument.Key, Equals, "your"+errorWebsite)
  1146. err = client.DeleteBucketWebsite(bucketNameTest)
  1147. c.Assert(err, IsNil)
  1148. // Set after delete
  1149. err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
  1150. c.Assert(err, IsNil)
  1151. // Eliminate effect of cache
  1152. time.Sleep(timeoutInOperation)
  1153. res, err = client.GetBucketWebsite(bucketNameTest)
  1154. c.Assert(err, IsNil)
  1155. c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
  1156. c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
  1157. err = client.DeleteBucket(bucketNameTest)
  1158. c.Assert(err, IsNil)
  1159. }
  1160. // TestDeleteBucketWebsite
  1161. func (s *OssClientSuite) TestDeleteBucketWebsite(c *C) {
  1162. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1163. var indexWebsite = "myindex.html"
  1164. var errorWebsite = "myerror.html"
  1165. client, err := New(endpoint, accessID, accessKey)
  1166. c.Assert(err, IsNil)
  1167. err = client.CreateBucket(bucketNameTest)
  1168. c.Assert(err, IsNil)
  1169. time.Sleep(timeoutInOperation)
  1170. // Get
  1171. res, err := client.GetBucketWebsite(bucketNameTest)
  1172. c.Assert(err, NotNil)
  1173. // Detele without set
  1174. err = client.DeleteBucketWebsite(bucketNameTest)
  1175. c.Assert(err, IsNil)
  1176. // Set
  1177. err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
  1178. c.Assert(err, IsNil)
  1179. time.Sleep(timeoutInOperation)
  1180. res, err = client.GetBucketWebsite(bucketNameTest)
  1181. c.Assert(err, IsNil)
  1182. c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
  1183. c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
  1184. // Detele
  1185. time.Sleep(timeoutInOperation)
  1186. err = client.DeleteBucketWebsite(bucketNameTest)
  1187. c.Assert(err, IsNil)
  1188. time.Sleep(timeoutInOperation)
  1189. res, err = client.GetBucketWebsite(bucketNameTest)
  1190. c.Assert(err, NotNil)
  1191. // Detele after delete
  1192. err = client.DeleteBucketWebsite(bucketNameTest)
  1193. c.Assert(err, IsNil)
  1194. err = client.DeleteBucket(bucketNameTest)
  1195. c.Assert(err, IsNil)
  1196. }
  1197. // TestSetBucketWebsiteNegative
  1198. func (s *OssClientSuite) TestSetBucketWebsiteNegative(c *C) {
  1199. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1200. var indexWebsite = "myindex.html"
  1201. var errorWebsite = "myerror.html"
  1202. client, err := New(endpoint, accessID, accessKey)
  1203. c.Assert(err, IsNil)
  1204. err = client.DeleteBucket(bucketNameTest)
  1205. // Not exist
  1206. _, err = client.GetBucketWebsite(bucketNameTest)
  1207. c.Assert(err, NotNil)
  1208. err = client.DeleteBucketWebsite(bucketNameTest)
  1209. c.Assert(err, NotNil)
  1210. err = client.SetBucketWebsite(bucketNameTest, indexWebsite, errorWebsite)
  1211. c.Assert(err, NotNil)
  1212. err = client.CreateBucket(bucketNameTest)
  1213. c.Assert(err, IsNil)
  1214. // Set
  1215. time.Sleep(timeoutInOperation)
  1216. err = client.SetBucketWebsite(bucketNameTest, "myindex", "myerror")
  1217. c.Assert(err, IsNil)
  1218. res, err := client.GetBucketWebsite(bucketNameTest)
  1219. c.Assert(err, IsNil)
  1220. c.Assert(res.IndexDocument.Suffix, Equals, "myindex")
  1221. c.Assert(res.ErrorDocument.Key, Equals, "myerror")
  1222. // Detele
  1223. err = client.DeleteBucketWebsite(bucketNameTest)
  1224. c.Assert(err, IsNil)
  1225. time.Sleep(timeoutInOperation)
  1226. _, err = client.GetBucketWebsite(bucketNameTest)
  1227. c.Assert(err, NotNil)
  1228. // Detele after delete
  1229. err = client.DeleteBucketWebsite(bucketNameTest)
  1230. c.Assert(err, IsNil)
  1231. err = client.DeleteBucket(bucketNameTest)
  1232. c.Assert(err, IsNil)
  1233. }
  1234. // TestSetBucketWebsiteDetail
  1235. func (s *OssClientSuite) TestSetBucketWebsiteDetail(c *C) {
  1236. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1237. var indexWebsite = "myindex.html"
  1238. var errorWebsite = "myerror.html"
  1239. client, err := New(endpoint, accessID, accessKey)
  1240. c.Assert(err, IsNil)
  1241. err = client.CreateBucket(bucketNameTest)
  1242. c.Assert(err, IsNil)
  1243. time.Sleep(timeoutInOperation)
  1244. btrue := true
  1245. bfalse := false
  1246. // Define one routing rule
  1247. ruleOk := RoutingRule{
  1248. RuleNumber: 1,
  1249. Condition: Condition{
  1250. KeyPrefixEquals: "",
  1251. HTTPErrorCodeReturnedEquals: 404,
  1252. },
  1253. Redirect: Redirect{
  1254. RedirectType: "Mirror",
  1255. // PassQueryString: &btrue, // set default value
  1256. MirrorURL: "http://www.test.com/",
  1257. // MirrorPassQueryString:&btrue, // set default value
  1258. // MirrorFollowRedirect:&bfalse, // set default value
  1259. // MirrorCheckMd5:&bfalse, // set default value
  1260. MirrorHeaders: MirrorHeaders{
  1261. // PassAll:&bfalse, // set default value
  1262. Pass: []string{"myheader-key1", "myheader-key2"},
  1263. Remove: []string{"myheader-key3", "myheader-key4"},
  1264. Set: []MirrorHeaderSet{
  1265. MirrorHeaderSet{
  1266. Key: "myheader-key5",
  1267. Value: "myheader-value5",
  1268. },
  1269. },
  1270. },
  1271. },
  1272. }
  1273. // Define array routing rule
  1274. ruleArrOk := []RoutingRule{
  1275. RoutingRule{
  1276. RuleNumber: 2,
  1277. Condition: Condition{
  1278. KeyPrefixEquals: "abc/",
  1279. HTTPErrorCodeReturnedEquals: 404,
  1280. IncludeHeader: []IncludeHeader{
  1281. IncludeHeader{
  1282. Key: "host",
  1283. Equals: "test.oss-cn-beijing-internal.aliyuncs.com",
  1284. },
  1285. },
  1286. },
  1287. Redirect: Redirect{
  1288. RedirectType: "AliCDN",
  1289. Protocol: "http",
  1290. HostName: "www.test.com",
  1291. PassQueryString: &bfalse,
  1292. ReplaceKeyWith: "prefix/${key}.suffix",
  1293. HttpRedirectCode: 301,
  1294. },
  1295. },
  1296. RoutingRule{
  1297. RuleNumber: 3,
  1298. Condition: Condition{
  1299. KeyPrefixEquals: "",
  1300. HTTPErrorCodeReturnedEquals: 404,
  1301. },
  1302. Redirect: Redirect{
  1303. RedirectType: "Mirror",
  1304. PassQueryString: &btrue,
  1305. MirrorURL: "http://www.test.com/",
  1306. MirrorPassQueryString: &btrue,
  1307. MirrorFollowRedirect: &bfalse,
  1308. MirrorCheckMd5: &bfalse,
  1309. MirrorHeaders: MirrorHeaders{
  1310. PassAll: &btrue,
  1311. Pass: []string{"myheader-key1", "myheader-key2"},
  1312. Remove: []string{"myheader-key3", "myheader-key4"},
  1313. Set: []MirrorHeaderSet{
  1314. MirrorHeaderSet{
  1315. Key: "myheader-key5",
  1316. Value: "myheader-value5",
  1317. },
  1318. },
  1319. },
  1320. },
  1321. },
  1322. }
  1323. // Set one routing rule
  1324. wxmlOne := WebsiteXML{}
  1325. wxmlOne.RoutingRules = append(wxmlOne.RoutingRules, ruleOk)
  1326. var responseHeader http.Header
  1327. err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlOne, GetResponseHeader(&responseHeader))
  1328. c.Assert(err, IsNil)
  1329. requestId := GetRequestId(responseHeader)
  1330. c.Assert(len(requestId) > 0, Equals, true)
  1331. res, err := client.GetBucketWebsite(bucketNameTest)
  1332. c.Assert(err, IsNil)
  1333. c.Assert(res.RoutingRules[0].Redirect.RedirectType, Equals, "Mirror")
  1334. c.Assert(*res.RoutingRules[0].Redirect.PassQueryString, Equals, false)
  1335. c.Assert(*res.RoutingRules[0].Redirect.MirrorPassQueryString, Equals, false)
  1336. c.Assert(*res.RoutingRules[0].Redirect.MirrorFollowRedirect, Equals, true)
  1337. c.Assert(*res.RoutingRules[0].Redirect.MirrorCheckMd5, Equals, false)
  1338. c.Assert(*res.RoutingRules[0].Redirect.MirrorHeaders.PassAll, Equals, false)
  1339. // Set one routing rule and IndexDocument, IndexDocument
  1340. wxml := WebsiteXML{
  1341. IndexDocument: IndexDocument{Suffix: indexWebsite},
  1342. ErrorDocument: ErrorDocument{Key: errorWebsite},
  1343. }
  1344. wxml.RoutingRules = append(wxml.RoutingRules, ruleOk)
  1345. err = client.SetBucketWebsiteDetail(bucketNameTest, wxml, GetResponseHeader(&responseHeader))
  1346. c.Assert(err, IsNil)
  1347. requestId = GetRequestId(responseHeader)
  1348. c.Assert(len(requestId) > 0, Equals, true)
  1349. res, err = client.GetBucketWebsite(bucketNameTest)
  1350. c.Assert(err, IsNil)
  1351. c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
  1352. c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
  1353. c.Assert(res.RoutingRules[0].Redirect.RedirectType, Equals, "Mirror")
  1354. // Set array routing rule
  1355. wxml.RoutingRules = append(wxml.RoutingRules, ruleArrOk...)
  1356. err = client.SetBucketWebsiteDetail(bucketNameTest, wxml, GetResponseHeader(&responseHeader))
  1357. c.Assert(err, IsNil)
  1358. requestId = GetRequestId(responseHeader)
  1359. c.Assert(len(requestId) > 0, Equals, true)
  1360. res, err = client.GetBucketWebsite(bucketNameTest)
  1361. c.Assert(err, IsNil)
  1362. c.Assert(res.IndexDocument.Suffix, Equals, indexWebsite)
  1363. c.Assert(res.ErrorDocument.Key, Equals, errorWebsite)
  1364. c.Assert(len(res.RoutingRules), Equals, 3)
  1365. c.Assert(res.RoutingRules[1].Redirect.RedirectType, Equals, "AliCDN")
  1366. c.Assert(*res.RoutingRules[2].Redirect.MirrorPassQueryString, Equals, true)
  1367. c.Assert(*res.RoutingRules[2].Redirect.MirrorFollowRedirect, Equals, false)
  1368. // Define one error routing rule
  1369. ruleErr := RoutingRule{
  1370. RuleNumber: 1,
  1371. Redirect: Redirect{
  1372. RedirectType: "Mirror",
  1373. PassQueryString: &btrue,
  1374. },
  1375. }
  1376. // Define array error routing rule
  1377. rulesErrArr := []RoutingRule{
  1378. RoutingRule{
  1379. RuleNumber: 1,
  1380. Redirect: Redirect{
  1381. RedirectType: "Mirror",
  1382. PassQueryString: &btrue,
  1383. },
  1384. },
  1385. RoutingRule{
  1386. RuleNumber: 2,
  1387. Redirect: Redirect{
  1388. RedirectType: "Mirror",
  1389. PassQueryString: &btrue,
  1390. },
  1391. },
  1392. }
  1393. ruleIntErr := RoutingRule{
  1394. // RuleNumber:0, // set NULL value
  1395. Condition: Condition{
  1396. KeyPrefixEquals: "",
  1397. HTTPErrorCodeReturnedEquals: 404,
  1398. },
  1399. Redirect: Redirect{
  1400. RedirectType: "Mirror",
  1401. // PassQueryString: &btrue, // set default value
  1402. MirrorURL: "http://www.test.com/",
  1403. // MirrorPassQueryString:&btrue, // set default value
  1404. // MirrorFollowRedirect:&bfalse, // set default value
  1405. // MirrorCheckMd5:&bfalse, // set default value
  1406. MirrorHeaders: MirrorHeaders{
  1407. // PassAll:&bfalse, // set default value
  1408. Pass: []string{"myheader-key1", "myheader-key2"},
  1409. Remove: []string{"myheader-key3", "myheader-key4"},
  1410. Set: []MirrorHeaderSet{
  1411. MirrorHeaderSet{
  1412. Key: "myheader-key5",
  1413. Value: "myheader-value5",
  1414. },
  1415. },
  1416. },
  1417. },
  1418. }
  1419. // Set one int type error rule
  1420. wxmlIntErr := WebsiteXML{}
  1421. wxmlIntErr.RoutingRules = append(wxmlIntErr.RoutingRules, ruleIntErr)
  1422. err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlIntErr)
  1423. c.Assert(err, NotNil)
  1424. // Set one error rule
  1425. wxmlErr := WebsiteXML{}
  1426. wxmlErr.RoutingRules = append(wxmlErr.RoutingRules, ruleErr)
  1427. err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlErr)
  1428. c.Assert(err, NotNil)
  1429. // Set one error rule and one correct rule
  1430. wxmlErr.RoutingRules = append(wxmlErr.RoutingRules, ruleOk)
  1431. err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlErr)
  1432. c.Assert(err, NotNil)
  1433. wxmlErrRuleArr := WebsiteXML{}
  1434. wxmlErrRuleArr.RoutingRules = append(wxmlErrRuleArr.RoutingRules, rulesErrArr...)
  1435. // Set array error routing rule
  1436. err = client.SetBucketWebsiteDetail(bucketNameTest, wxmlErrRuleArr)
  1437. c.Assert(err, NotNil)
  1438. err = client.DeleteBucketWebsite(bucketNameTest)
  1439. c.Assert(err, IsNil)
  1440. err = client.DeleteBucket(bucketNameTest)
  1441. c.Assert(err, IsNil)
  1442. }
  1443. // TestSetBucketWebsiteXml
  1444. func (s *OssClientSuite) TestSetBucketWebsiteXml(c *C) {
  1445. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1446. client, err := New(endpoint, accessID, accessKey)
  1447. c.Assert(err, IsNil)
  1448. err = client.CreateBucket(bucketNameTest)
  1449. c.Assert(err, IsNil)
  1450. time.Sleep(timeoutInOperation)
  1451. // Define one routing rule
  1452. ruleOk := RoutingRule{
  1453. RuleNumber: 1,
  1454. Condition: Condition{
  1455. KeyPrefixEquals: "",
  1456. HTTPErrorCodeReturnedEquals: 404,
  1457. },
  1458. Redirect: Redirect{
  1459. RedirectType: "Mirror",
  1460. // PassQueryString: &btrue, // set default value
  1461. MirrorURL: "http://www.test.com/",
  1462. // MirrorPassQueryString:&btrue, // set default value
  1463. // MirrorFollowRedirect:&bfalse, // set default value
  1464. // MirrorCheckMd5:&bfalse, // set default value
  1465. MirrorHeaders: MirrorHeaders{
  1466. // PassAll:&bfalse, // set default value
  1467. Pass: []string{"myheader-key1", "myheader-key2"},
  1468. Remove: []string{"myheader-key3", "myheader-key4"},
  1469. Set: []MirrorHeaderSet{
  1470. MirrorHeaderSet{
  1471. Key: "myheader-key5",
  1472. Value: "myheader-value5",
  1473. },
  1474. },
  1475. },
  1476. },
  1477. }
  1478. // Set one routing rule
  1479. wxmlOne := WebsiteXML{}
  1480. wxmlOne.RoutingRules = append(wxmlOne.RoutingRules, ruleOk)
  1481. bs, err := xml.Marshal(wxmlOne)
  1482. c.Assert(err, IsNil)
  1483. var responseHeader http.Header
  1484. err = client.SetBucketWebsiteXml(bucketNameTest, string(bs), GetResponseHeader(&responseHeader))
  1485. c.Assert(err, IsNil)
  1486. requestId := GetRequestId(responseHeader)
  1487. c.Assert(len(requestId) > 0, Equals, true)
  1488. res, err := client.GetBucketWebsite(bucketNameTest)
  1489. c.Assert(err, IsNil)
  1490. c.Assert(res.RoutingRules[0].Redirect.RedirectType, Equals, "Mirror")
  1491. c.Assert(*res.RoutingRules[0].Redirect.PassQueryString, Equals, false)
  1492. c.Assert(*res.RoutingRules[0].Redirect.MirrorPassQueryString, Equals, false)
  1493. c.Assert(*res.RoutingRules[0].Redirect.MirrorFollowRedirect, Equals, true)
  1494. c.Assert(*res.RoutingRules[0].Redirect.MirrorCheckMd5, Equals, false)
  1495. c.Assert(*res.RoutingRules[0].Redirect.MirrorHeaders.PassAll, Equals, false)
  1496. }
  1497. // TestSetBucketCORS
  1498. func (s *OssClientSuite) TestSetBucketCORS(c *C) {
  1499. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1500. var rule1 = CORSRule{
  1501. AllowedOrigin: []string{"*"},
  1502. AllowedMethod: []string{"PUT", "GET", "POST"},
  1503. AllowedHeader: []string{},
  1504. ExposeHeader: []string{},
  1505. MaxAgeSeconds: 100,
  1506. }
  1507. var rule2 = CORSRule{
  1508. AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
  1509. AllowedMethod: []string{"GET"},
  1510. AllowedHeader: []string{"Authorization"},
  1511. ExposeHeader: []string{"x-oss-test", "x-oss-test1"},
  1512. MaxAgeSeconds: 200,
  1513. }
  1514. client, err := New(endpoint, accessID, accessKey)
  1515. c.Assert(err, IsNil)
  1516. err = client.CreateBucket(bucketNameTest)
  1517. c.Assert(err, IsNil)
  1518. time.Sleep(timeoutInOperation)
  1519. // Set
  1520. err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule1})
  1521. c.Assert(err, IsNil)
  1522. gbcr, err := client.GetBucketCORS(bucketNameTest)
  1523. c.Assert(err, IsNil)
  1524. c.Assert(len(gbcr.CORSRules), Equals, 1)
  1525. c.Assert(len(gbcr.CORSRules[0].AllowedOrigin), Equals, 1)
  1526. c.Assert(len(gbcr.CORSRules[0].AllowedMethod), Equals, 3)
  1527. c.Assert(len(gbcr.CORSRules[0].AllowedHeader), Equals, 0)
  1528. c.Assert(len(gbcr.CORSRules[0].ExposeHeader), Equals, 0)
  1529. c.Assert(gbcr.CORSRules[0].MaxAgeSeconds, Equals, 100)
  1530. // Double set
  1531. err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule1})
  1532. c.Assert(err, IsNil)
  1533. gbcr, err = client.GetBucketCORS(bucketNameTest)
  1534. c.Assert(err, IsNil)
  1535. c.Assert(len(gbcr.CORSRules), Equals, 1)
  1536. c.Assert(len(gbcr.CORSRules[0].AllowedOrigin), Equals, 1)
  1537. c.Assert(len(gbcr.CORSRules[0].AllowedMethod), Equals, 3)
  1538. c.Assert(len(gbcr.CORSRules[0].AllowedHeader), Equals, 0)
  1539. c.Assert(len(gbcr.CORSRules[0].ExposeHeader), Equals, 0)
  1540. c.Assert(gbcr.CORSRules[0].MaxAgeSeconds, Equals, 100)
  1541. // Set rule2
  1542. err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule2})
  1543. c.Assert(err, IsNil)
  1544. time.Sleep(timeoutInOperation)
  1545. gbcr, err = client.GetBucketCORS(bucketNameTest)
  1546. c.Assert(err, IsNil)
  1547. c.Assert(len(gbcr.CORSRules), Equals, 1)
  1548. c.Assert(len(gbcr.CORSRules[0].AllowedOrigin), Equals, 2)
  1549. c.Assert(len(gbcr.CORSRules[0].AllowedMethod), Equals, 1)
  1550. c.Assert(len(gbcr.CORSRules[0].AllowedHeader), Equals, 1)
  1551. c.Assert(len(gbcr.CORSRules[0].ExposeHeader), Equals, 2)
  1552. c.Assert(gbcr.CORSRules[0].MaxAgeSeconds, Equals, 200)
  1553. // Reset
  1554. err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule1, rule2})
  1555. c.Assert(err, IsNil)
  1556. time.Sleep(timeoutInOperation)
  1557. gbcr, err = client.GetBucketCORS(bucketNameTest)
  1558. c.Assert(err, IsNil)
  1559. c.Assert(len(gbcr.CORSRules), Equals, 2)
  1560. // Set after delete
  1561. err = client.DeleteBucketCORS(bucketNameTest)
  1562. c.Assert(err, IsNil)
  1563. err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule1, rule2})
  1564. c.Assert(err, IsNil)
  1565. time.Sleep(timeoutInOperation)
  1566. gbcr, err = client.GetBucketCORS(bucketNameTest)
  1567. c.Assert(err, IsNil)
  1568. c.Assert(len(gbcr.CORSRules), Equals, 2)
  1569. err = client.DeleteBucketCORS(bucketNameTest)
  1570. c.Assert(err, IsNil)
  1571. err = client.DeleteBucket(bucketNameTest)
  1572. c.Assert(err, IsNil)
  1573. }
  1574. // TestDeleteBucketCORS
  1575. func (s *OssClientSuite) TestDeleteBucketCORS(c *C) {
  1576. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1577. var rule = CORSRule{
  1578. AllowedOrigin: []string{"*"},
  1579. AllowedMethod: []string{"PUT", "GET", "POST"},
  1580. AllowedHeader: []string{},
  1581. ExposeHeader: []string{},
  1582. MaxAgeSeconds: 100,
  1583. }
  1584. client, err := New(endpoint, accessID, accessKey)
  1585. c.Assert(err, IsNil)
  1586. err = client.CreateBucket(bucketNameTest)
  1587. c.Assert(err, IsNil)
  1588. time.Sleep(timeoutInOperation)
  1589. // Delete not set
  1590. err = client.DeleteBucketCORS(bucketNameTest)
  1591. c.Assert(err, IsNil)
  1592. // Set
  1593. err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule})
  1594. c.Assert(err, IsNil)
  1595. time.Sleep(timeoutInOperation)
  1596. _, err = client.GetBucketCORS(bucketNameTest)
  1597. c.Assert(err, IsNil)
  1598. // Detele
  1599. err = client.DeleteBucketCORS(bucketNameTest)
  1600. c.Assert(err, IsNil)
  1601. time.Sleep(timeoutInOperation)
  1602. _, err = client.GetBucketCORS(bucketNameTest)
  1603. c.Assert(err, NotNil)
  1604. // Detele after deleting
  1605. err = client.DeleteBucketCORS(bucketNameTest)
  1606. c.Assert(err, IsNil)
  1607. err = client.DeleteBucket(bucketNameTest)
  1608. c.Assert(err, IsNil)
  1609. }
  1610. // TestSetBucketCORSNegative
  1611. func (s *OssClientSuite) TestSetBucketCORSNegative(c *C) {
  1612. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1613. var rule = CORSRule{
  1614. AllowedOrigin: []string{"*"},
  1615. AllowedMethod: []string{"PUT", "GET", "POST"},
  1616. AllowedHeader: []string{},
  1617. ExposeHeader: []string{},
  1618. MaxAgeSeconds: 100,
  1619. }
  1620. client, err := New(endpoint, accessID, accessKey)
  1621. c.Assert(err, IsNil)
  1622. err = client.DeleteBucket(bucketNameTest)
  1623. // Not exist
  1624. _, err = client.GetBucketCORS(bucketNameTest)
  1625. c.Assert(err, NotNil)
  1626. err = client.DeleteBucketCORS(bucketNameTest)
  1627. c.Assert(err, NotNil)
  1628. err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule})
  1629. c.Assert(err, NotNil)
  1630. err = client.CreateBucket(bucketNameTest)
  1631. c.Assert(err, IsNil)
  1632. time.Sleep(timeoutInOperation)
  1633. _, err = client.GetBucketCORS(bucketNameTest)
  1634. c.Assert(err, NotNil)
  1635. // Set
  1636. err = client.SetBucketCORS(bucketNameTest, []CORSRule{rule})
  1637. c.Assert(err, IsNil)
  1638. time.Sleep(timeoutInOperation)
  1639. _, err = client.GetBucketCORS(bucketNameTest)
  1640. c.Assert(err, IsNil)
  1641. // Delete
  1642. err = client.DeleteBucketCORS(bucketNameTest)
  1643. c.Assert(err, IsNil)
  1644. time.Sleep(timeoutInOperation)
  1645. _, err = client.GetBucketCORS(bucketNameTest)
  1646. c.Assert(err, NotNil)
  1647. // Delete after deleting
  1648. err = client.DeleteBucketCORS(bucketNameTest)
  1649. c.Assert(err, IsNil)
  1650. err = client.DeleteBucket(bucketNameTest)
  1651. c.Assert(err, IsNil)
  1652. }
  1653. // TestGetBucketInfo
  1654. func (s *OssClientSuite) TestGetBucketInfo(c *C) {
  1655. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1656. client, err := New(endpoint, accessID, accessKey)
  1657. c.Assert(err, IsNil)
  1658. err = client.CreateBucket(bucketNameTest)
  1659. c.Assert(err, IsNil)
  1660. res, err := client.GetBucketInfo(bucketNameTest)
  1661. c.Assert(err, IsNil)
  1662. c.Assert(res.BucketInfo.Name, Equals, bucketNameTest)
  1663. c.Assert(strings.HasPrefix(res.BucketInfo.Location, "oss-"), Equals, true)
  1664. c.Assert(res.BucketInfo.ACL, Equals, "private")
  1665. c.Assert(strings.HasSuffix(res.BucketInfo.ExtranetEndpoint, ".com"), Equals, true)
  1666. c.Assert(strings.HasSuffix(res.BucketInfo.IntranetEndpoint, ".com"), Equals, true)
  1667. c.Assert(res.BucketInfo.CreationDate, NotNil)
  1668. err = client.DeleteBucket(bucketNameTest)
  1669. c.Assert(err, IsNil)
  1670. }
  1671. // TestGetBucketInfoNegative
  1672. func (s *OssClientSuite) TestGetBucketInfoNegative(c *C) {
  1673. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1674. client, err := New(endpoint, accessID, accessKey)
  1675. c.Assert(err, IsNil)
  1676. // Not exist
  1677. _, err = client.GetBucketInfo(bucketNameTest)
  1678. c.Assert(err, NotNil)
  1679. // Bucket name invalid
  1680. _, err = client.GetBucketInfo("InvalidBucketName_")
  1681. c.Assert(err, NotNil)
  1682. }
  1683. // TestEndpointFormat
  1684. func (s *OssClientSuite) TestEndpointFormat(c *C) {
  1685. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1686. // http://host
  1687. client, err := New(endpoint, accessID, accessKey)
  1688. c.Assert(err, IsNil)
  1689. err = client.CreateBucket(bucketNameTest)
  1690. c.Assert(err, IsNil)
  1691. time.Sleep(timeoutInOperation)
  1692. res, err := client.GetBucketACL(bucketNameTest)
  1693. c.Assert(err, IsNil)
  1694. c.Assert(res.ACL, Equals, string(ACLPrivate))
  1695. err = client.DeleteBucket(bucketNameTest)
  1696. c.Assert(err, IsNil)
  1697. time.Sleep(timeoutInOperation)
  1698. // http://host:port
  1699. client, err = New(endpoint+":80", accessID, accessKey)
  1700. c.Assert(err, IsNil)
  1701. err = client.CreateBucket(bucketNameTest)
  1702. c.Assert(err, IsNil)
  1703. time.Sleep(timeoutInOperation)
  1704. res, err = client.GetBucketACL(bucketNameTest)
  1705. c.Assert(err, IsNil)
  1706. c.Assert(res.ACL, Equals, string(ACLPrivate))
  1707. err = client.DeleteBucket(bucketNameTest)
  1708. c.Assert(err, IsNil)
  1709. }
  1710. // TestCname
  1711. func (s *OssClientSuite) _TestCname(c *C) {
  1712. var bucketNameTest = "<my-bucket-cname>"
  1713. client, err := New("<endpoint>", "<accessKeyId>", "<accessKeySecret>", UseCname(true))
  1714. c.Assert(err, IsNil)
  1715. err = client.CreateBucket(bucketNameTest)
  1716. c.Assert(err, IsNil)
  1717. _, err = client.ListBuckets()
  1718. c.Assert(err, NotNil)
  1719. res, err := client.GetBucketACL(bucketNameTest)
  1720. c.Assert(err, IsNil)
  1721. c.Assert(res.ACL, Equals, string(ACLPrivate))
  1722. }
  1723. // TestCnameNegative
  1724. func (s *OssClientSuite) _TestCnameNegative(c *C) {
  1725. var bucketNameTest = "<my-bucket-cname>"
  1726. client, err := New("<endpoint>", "<accessKeyId>", "<accessKeySecret>", UseCname(true))
  1727. c.Assert(err, IsNil)
  1728. err = client.CreateBucket(bucketNameTest)
  1729. c.Assert(err, NotNil)
  1730. _, err = client.ListBuckets()
  1731. c.Assert(err, NotNil)
  1732. _, err = client.GetBucketACL(bucketNameTest)
  1733. c.Assert(err, NotNil)
  1734. }
  1735. // _TestHTTPS
  1736. func (s *OssClientSuite) _TestHTTPS(c *C) {
  1737. var bucketNameTest = "<my-bucket-https>"
  1738. client, err := New("<endpoint>", "<accessKeyId>", "<accessKeySecret>")
  1739. c.Assert(err, IsNil)
  1740. err = client.CreateBucket(bucketNameTest)
  1741. c.Assert(err, IsNil)
  1742. res, err := client.GetBucketACL(bucketNameTest)
  1743. c.Assert(err, IsNil)
  1744. c.Assert(res.ACL, Equals, string(ACLPrivate))
  1745. err = client.DeleteBucket(bucketNameTest)
  1746. c.Assert(err, IsNil)
  1747. }
  1748. // TestClientOption
  1749. func (s *OssClientSuite) TestClientOption(c *C) {
  1750. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  1751. client, err := New(endpoint, accessID, accessKey, UseCname(true),
  1752. Timeout(11, 12), SecurityToken("token"), Proxy(proxyHost))
  1753. c.Assert(err, IsNil)
  1754. // CreateBucket timeout
  1755. err = client.CreateBucket(bucketNameTest)
  1756. c.Assert(err, NotNil)
  1757. c.Assert(client.Conn.config.HTTPTimeout.ConnectTimeout, Equals, time.Second*11)
  1758. c.Assert(client.Conn.config.HTTPTimeout.ReadWriteTimeout, Equals, time.Second*12)
  1759. c.Assert(client.Conn.config.HTTPTimeout.HeaderTimeout, Equals, time.Second*12)
  1760. c.Assert(client.Conn.config.HTTPTimeout.IdleConnTimeout, Equals, time.Second*12)
  1761. c.Assert(client.Conn.config.HTTPTimeout.LongTimeout, Equals, time.Second*12*10)
  1762. c.Assert(client.Conn.config.SecurityToken, Equals, "token")
  1763. c.Assert(client.Conn.config.IsCname, Equals, true)
  1764. c.Assert(client.Conn.config.IsUseProxy, Equals, true)
  1765. c.Assert(client.Config.ProxyHost, Equals, proxyHost)
  1766. client, err = New(endpoint, accessID, accessKey, AuthProxy(proxyHost, proxyUser, proxyPasswd))
  1767. c.Assert(client.Conn.config.IsUseProxy, Equals, true)
  1768. c.Assert(client.Config.ProxyHost, Equals, proxyHost)
  1769. c.Assert(client.Conn.config.IsAuthProxy, Equals, true)
  1770. c.Assert(client.Conn.config.ProxyUser, Equals, proxyUser)
  1771. c.Assert(client.Conn.config.ProxyPassword, Equals, proxyPasswd)
  1772. client, err = New(endpoint, accessID, accessKey, UserAgent("go sdk user agent"))
  1773. c.Assert(client.Conn.config.UserAgent, Equals, "go sdk user agent")
  1774. // Check we can overide the http.Client
  1775. httpClient := new(http.Client)
  1776. client, err = New(endpoint, accessID, accessKey, HTTPClient(httpClient))
  1777. c.Assert(client.HTTPClient, Equals, httpClient)
  1778. c.Assert(client.Conn.client, Equals, httpClient)
  1779. client, err = New(endpoint, accessID, accessKey)
  1780. c.Assert(client.HTTPClient, IsNil)
  1781. }
  1782. // TestProxy
  1783. func (s *OssClientSuite) ProxyTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
  1784. bucketNameTest := bucketNamePrefix + RandLowStr(6)
  1785. objectName := "体育/奥运/首金"
  1786. objectValue := "大江东去,浪淘尽,千古风流人物。 故垒西边,人道是、三国周郎赤壁。"
  1787. client, err := New(endpoint, accessID, accessKey, AuthProxy(proxyHost, proxyUser, proxyPasswd))
  1788. oldType := client.Config.AuthVersion
  1789. oldHeaders := client.Config.AdditionalHeaders
  1790. client.Config.AuthVersion = authVersion
  1791. client.Config.AdditionalHeaders = extraHeaders
  1792. // Create bucket
  1793. err = client.CreateBucket(bucketNameTest)
  1794. c.Assert(err, IsNil)
  1795. // Get bucket info
  1796. _, err = client.GetBucketInfo(bucketNameTest)
  1797. c.Assert(err, IsNil)
  1798. bucket, err := client.Bucket(bucketNameTest)
  1799. // Sign URL
  1800. str, err := bucket.SignURL(objectName, HTTPPut, 60)
  1801. c.Assert(err, IsNil)
  1802. if bucket.Client.Config.AuthVersion == AuthV1 {
  1803. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  1804. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  1805. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  1806. } else {
  1807. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  1808. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  1809. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  1810. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  1811. }
  1812. // Put object with URL
  1813. err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  1814. c.Assert(err, IsNil)
  1815. // Sign URL for get object
  1816. str, err = bucket.SignURL(objectName, HTTPGet, 60)
  1817. c.Assert(err, IsNil)
  1818. if bucket.Client.Config.AuthVersion == AuthV1 {
  1819. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  1820. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  1821. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  1822. } else {
  1823. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  1824. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  1825. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  1826. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  1827. }
  1828. // Get object with URL
  1829. body, err := bucket.GetObjectWithURL(str)
  1830. c.Assert(err, IsNil)
  1831. str, err = readBody(body)
  1832. c.Assert(err, IsNil)
  1833. c.Assert(str, Equals, objectValue)
  1834. // Put object
  1835. err = bucket.PutObject(objectName, strings.NewReader(objectValue))
  1836. c.Assert(err, IsNil)
  1837. // Get object
  1838. _, err = bucket.GetObject(objectName)
  1839. c.Assert(err, IsNil)
  1840. // List objects
  1841. _, err = bucket.ListObjects()
  1842. c.Assert(err, IsNil)
  1843. // Delete object
  1844. err = bucket.DeleteObject(objectName)
  1845. c.Assert(err, IsNil)
  1846. // Delete bucket
  1847. err = client.DeleteBucket(bucketNameTest)
  1848. c.Assert(err, IsNil)
  1849. client.Config.AuthVersion = oldType
  1850. client.Config.AdditionalHeaders = oldHeaders
  1851. }
  1852. func (s *OssClientSuite) TestProxy(c *C) {
  1853. s.ProxyTestFunc(c, AuthV1, []string{})
  1854. s.ProxyTestFunc(c, AuthV2, []string{})
  1855. s.ProxyTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
  1856. }
  1857. // TestProxy for https endpoint
  1858. func (s *OssClientSuite) TestHttpsEndpointProxy(c *C) {
  1859. bucketNameTest := bucketNamePrefix + RandLowStr(6)
  1860. objectName := objectNamePrefix + RandLowStr(6)
  1861. objectValue := RandLowStr(100)
  1862. httpsEndPoint := ""
  1863. if strings.HasPrefix(endpoint, "http://") {
  1864. httpsEndPoint = strings.Replace(endpoint, "http://", "https://", 1)
  1865. } else if !strings.HasPrefix(endpoint, "https://") {
  1866. httpsEndPoint = "https://" + endpoint
  1867. } else {
  1868. httpsEndPoint = endpoint
  1869. }
  1870. client, err := New(httpsEndPoint, accessID, accessKey, AuthProxy(proxyHost, proxyUser, proxyPasswd))
  1871. // Create bucket
  1872. err = client.CreateBucket(bucketNameTest)
  1873. c.Assert(err, IsNil)
  1874. bucket, err := client.Bucket(bucketNameTest)
  1875. // Put object
  1876. err = bucket.PutObject(objectName, strings.NewReader(objectValue))
  1877. c.Assert(err, IsNil)
  1878. // Get object
  1879. _, err = bucket.GetObject(objectName)
  1880. c.Assert(err, IsNil)
  1881. // List objects
  1882. _, err = bucket.ListObjects()
  1883. c.Assert(err, IsNil)
  1884. // Delete object
  1885. err = bucket.DeleteObject(objectName)
  1886. c.Assert(err, IsNil)
  1887. // Delete bucket
  1888. err = client.DeleteBucket(bucketNameTest)
  1889. c.Assert(err, IsNil)
  1890. }
  1891. // Private
  1892. func (s *OssClientSuite) checkBucket(buckets []BucketProperties, bucket string) bool {
  1893. for _, v := range buckets {
  1894. if v.Name == bucket {
  1895. return true
  1896. }
  1897. }
  1898. return false
  1899. }
  1900. func (s *OssClientSuite) getBucket(buckets []BucketProperties, bucket string) (bool, BucketProperties) {
  1901. for _, v := range buckets {
  1902. if v.Name == bucket {
  1903. return true, v
  1904. }
  1905. }
  1906. return false, BucketProperties{}
  1907. }
  1908. func (s *OssClientSuite) TestHttpLogNotSignUrl(c *C) {
  1909. logName := "." + string(os.PathSeparator) + "test-go-sdk-httpdebug.log" + RandStr(5)
  1910. f, err := os.OpenFile(logName, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0660)
  1911. c.Assert(err, IsNil)
  1912. client, err := New(endpoint, accessID, accessKey)
  1913. client.Config.LogLevel = Debug
  1914. client.Config.Logger = log.New(f, "", log.LstdFlags)
  1915. var testBucketName = bucketNamePrefix + RandLowStr(6)
  1916. // CreateBucket
  1917. err = client.CreateBucket(testBucketName)
  1918. f.Close()
  1919. // read log file,get http info
  1920. contents, err := ioutil.ReadFile(logName)
  1921. c.Assert(err, IsNil)
  1922. httpContent := string(contents)
  1923. //fmt.Println(httpContent)
  1924. c.Assert(strings.Contains(httpContent, "signStr"), Equals, true)
  1925. c.Assert(strings.Contains(httpContent, "Method:"), Equals, true)
  1926. // delete test bucket and log
  1927. os.Remove(logName)
  1928. client.DeleteBucket(testBucketName)
  1929. }
  1930. func (s *OssClientSuite) HttpLogSignUrlTestFunc(c *C, authVersion AuthVersionType, extraHeaders []string) {
  1931. logName := "." + string(os.PathSeparator) + "test-go-sdk-httpdebug-signurl.log" + RandStr(5)
  1932. f, err := os.OpenFile(logName, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0660)
  1933. c.Assert(err, IsNil)
  1934. client, err := New(endpoint, accessID, accessKey)
  1935. client.Config.LogLevel = Debug
  1936. client.Config.Logger = log.New(f, "", log.LstdFlags)
  1937. oldType := client.Config.AuthVersion
  1938. oldHeaders := client.Config.AdditionalHeaders
  1939. client.Config.AuthVersion = authVersion
  1940. client.Config.AdditionalHeaders = extraHeaders
  1941. var testBucketName = bucketNamePrefix + RandLowStr(6)
  1942. // CreateBucket
  1943. err = client.CreateBucket(testBucketName)
  1944. f.Close()
  1945. // clear log
  1946. f, err = os.OpenFile(logName, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0660)
  1947. client.Config.Logger = log.New(f, "", log.LstdFlags)
  1948. bucket, _ := client.Bucket(testBucketName)
  1949. objectName := objectNamePrefix + RandStr(8)
  1950. objectValue := RandStr(20)
  1951. // Sign URL for put
  1952. str, err := bucket.SignURL(objectName, HTTPPut, 60)
  1953. c.Assert(err, IsNil)
  1954. if bucket.Client.Config.AuthVersion == AuthV1 {
  1955. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  1956. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  1957. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  1958. } else {
  1959. c.Assert(strings.Contains(str, HTTPParamSignatureVersion+"=OSS2"), Equals, true)
  1960. c.Assert(strings.Contains(str, HTTPParamExpiresV2+"="), Equals, true)
  1961. c.Assert(strings.Contains(str, HTTPParamAccessKeyIDV2+"="), Equals, true)
  1962. c.Assert(strings.Contains(str, HTTPParamSignatureV2+"="), Equals, true)
  1963. }
  1964. // Error put object with URL
  1965. err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue), ContentType("image/tiff"))
  1966. f.Close()
  1967. // read log file,get http info
  1968. contents, err := ioutil.ReadFile(logName)
  1969. c.Assert(err, IsNil)
  1970. httpContent := string(contents)
  1971. //fmt.Println(httpContent)
  1972. c.Assert(strings.Contains(httpContent, "signStr"), Equals, true)
  1973. c.Assert(strings.Contains(httpContent, "Method:"), Equals, true)
  1974. // delete test bucket and log
  1975. os.Remove(logName)
  1976. client.DeleteBucket(testBucketName)
  1977. client.Config.AuthVersion = oldType
  1978. client.Config.AdditionalHeaders = oldHeaders
  1979. }
  1980. func (s *OssClientSuite) TestHttpLogSignUrl(c *C) {
  1981. s.HttpLogSignUrlTestFunc(c, AuthV1, []string{})
  1982. s.HttpLogSignUrlTestFunc(c, AuthV2, []string{})
  1983. s.HttpLogSignUrlTestFunc(c, AuthV2, []string{"host", "range", "user-agent"})
  1984. }
  1985. func (s *OssClientSuite) TestSetLimitUploadSpeed(c *C) {
  1986. client, err := New(endpoint, accessID, accessKey)
  1987. c.Assert(err, IsNil)
  1988. err = client.LimitUploadSpeed(100)
  1989. goVersion := runtime.Version()
  1990. pSlice := strings.Split(strings.ToLower(goVersion), ".")
  1991. // compare with go1.7
  1992. if len(pSlice) >= 2 {
  1993. if pSlice[0] > "go1" {
  1994. c.Assert(err, IsNil)
  1995. } else if pSlice[0] == "go1" {
  1996. subVersion, _ := strconv.Atoi(pSlice[1])
  1997. if subVersion >= 7 {
  1998. c.Assert(err, IsNil)
  1999. } else {
  2000. c.Assert(err, NotNil)
  2001. }
  2002. } else {
  2003. c.Assert(err, NotNil)
  2004. }
  2005. }
  2006. }
  2007. func (s *OssClientSuite) TestBucketEncyptionError(c *C) {
  2008. client, err := New(endpoint, accessID, accessKey)
  2009. c.Assert(err, IsNil)
  2010. bucketName := bucketNamePrefix + RandLowStr(5)
  2011. err = client.CreateBucket(bucketName)
  2012. c.Assert(err, IsNil)
  2013. // SetBucketEncryption:AES256 ,"123"
  2014. encryptionRule := ServerEncryptionRule{}
  2015. encryptionRule.SSEDefault.SSEAlgorithm = string(AESAlgorithm)
  2016. encryptionRule.SSEDefault.KMSMasterKeyID = "123"
  2017. var responseHeader http.Header
  2018. err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
  2019. c.Assert(err, NotNil)
  2020. requestId := GetRequestId(responseHeader)
  2021. c.Assert(len(requestId) > 0, Equals, true)
  2022. // GetBucketEncryption
  2023. _, err = client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
  2024. c.Assert(err, NotNil)
  2025. requestId = GetRequestId(responseHeader)
  2026. c.Assert(len(requestId) > 0, Equals, true)
  2027. // Get default bucket info
  2028. bucketResult, err := client.GetBucketInfo(bucketName)
  2029. c.Assert(err, IsNil)
  2030. c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "")
  2031. c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
  2032. c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
  2033. err = client.DeleteBucket(bucketName)
  2034. c.Assert(err, IsNil)
  2035. }
  2036. func (s *OssClientSuite) TestBucketEncryptionPutAndGetAndDelete(c *C) {
  2037. client, err := New(endpoint, accessID, accessKey)
  2038. c.Assert(err, IsNil)
  2039. bucketName := bucketNamePrefix + RandLowStr(5)
  2040. err = client.CreateBucket(bucketName)
  2041. c.Assert(err, IsNil)
  2042. // SetBucketEncryption:KMS ,""
  2043. encryptionRule := ServerEncryptionRule{}
  2044. encryptionRule.SSEDefault.SSEAlgorithm = string(KMSAlgorithm)
  2045. var responseHeader http.Header
  2046. err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
  2047. c.Assert(err, IsNil)
  2048. requestId := GetRequestId(responseHeader)
  2049. c.Assert(len(requestId) > 0, Equals, true)
  2050. // GetBucketEncryption
  2051. getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
  2052. c.Assert(err, IsNil)
  2053. requestId = GetRequestId(responseHeader)
  2054. c.Assert(len(requestId) > 0, Equals, true)
  2055. // check encryption value
  2056. c.Assert(encryptionRule.SSEDefault.SSEAlgorithm, Equals, getResult.SSEDefault.SSEAlgorithm)
  2057. c.Assert(encryptionRule.SSEDefault.KMSMasterKeyID, Equals, getResult.SSEDefault.KMSMasterKeyID)
  2058. // delete bucket encyption
  2059. err = client.DeleteBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
  2060. c.Assert(err, IsNil)
  2061. requestId = GetRequestId(responseHeader)
  2062. c.Assert(len(requestId) > 0, Equals, true)
  2063. // GetBucketEncryption failure
  2064. _, err = client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
  2065. c.Assert(err, NotNil)
  2066. requestId = GetRequestId(responseHeader)
  2067. c.Assert(len(requestId) > 0, Equals, true)
  2068. // Get default bucket info
  2069. bucketResult, err := client.GetBucketInfo(bucketName)
  2070. c.Assert(err, IsNil)
  2071. c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "")
  2072. c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
  2073. c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
  2074. err = client.DeleteBucket(bucketName)
  2075. c.Assert(err, IsNil)
  2076. }
  2077. func (s *OssClientSuite) TestBucketEncryptionWithSm4(c *C) {
  2078. client, err := New(endpoint, accessID, accessKey)
  2079. c.Assert(err, IsNil)
  2080. bucketName := bucketNamePrefix + RandLowStr(5)
  2081. err = client.CreateBucket(bucketName)
  2082. c.Assert(err, IsNil)
  2083. // SetBucketEncryption:SM4 ,""
  2084. encryptionRule := ServerEncryptionRule{}
  2085. encryptionRule.SSEDefault.SSEAlgorithm = string(SM4Algorithm)
  2086. var responseHeader http.Header
  2087. err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
  2088. c.Assert(err, IsNil)
  2089. requestId := GetRequestId(responseHeader)
  2090. c.Assert(len(requestId) > 0, Equals, true)
  2091. // GetBucketEncryption
  2092. getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
  2093. c.Assert(err, IsNil)
  2094. requestId = GetRequestId(responseHeader)
  2095. c.Assert(len(requestId) > 0, Equals, true)
  2096. // check encryption value
  2097. c.Assert(getResult.SSEDefault.SSEAlgorithm, Equals, string(SM4Algorithm))
  2098. c.Assert(getResult.SSEDefault.KMSMasterKeyID, Equals, "")
  2099. c.Assert(getResult.SSEDefault.KMSDataEncryption, Equals, "")
  2100. // Get default bucket info
  2101. bucketResult, err := client.GetBucketInfo(bucketName)
  2102. c.Assert(err, IsNil)
  2103. c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, string(SM4Algorithm))
  2104. c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
  2105. c.Assert(bucketResult.BucketInfo.SseRule.KMSDataEncryption, Equals, "")
  2106. err = client.DeleteBucket(bucketName)
  2107. c.Assert(err, IsNil)
  2108. }
  2109. func (s *OssClientSuite) TestBucketEncryptionWithKmsSm4(c *C) {
  2110. client, err := New(endpoint, accessID, accessKey)
  2111. c.Assert(err, IsNil)
  2112. bucketName := bucketNamePrefix + RandLowStr(5)
  2113. err = client.CreateBucket(bucketName)
  2114. c.Assert(err, IsNil)
  2115. // SetBucketEncryption:SM4 ,""
  2116. encryptionRule := ServerEncryptionRule{}
  2117. encryptionRule.SSEDefault.SSEAlgorithm = string(KMSAlgorithm)
  2118. encryptionRule.SSEDefault.KMSDataEncryption = string(SM4Algorithm)
  2119. var responseHeader http.Header
  2120. err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
  2121. c.Assert(err, IsNil)
  2122. requestId := GetRequestId(responseHeader)
  2123. c.Assert(len(requestId) > 0, Equals, true)
  2124. // GetBucketEncryption
  2125. getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
  2126. c.Assert(err, IsNil)
  2127. requestId = GetRequestId(responseHeader)
  2128. c.Assert(len(requestId) > 0, Equals, true)
  2129. // check encryption value
  2130. c.Assert(getResult.SSEDefault.SSEAlgorithm, Equals, string(KMSAlgorithm))
  2131. c.Assert(getResult.SSEDefault.KMSMasterKeyID, Equals, "")
  2132. c.Assert(getResult.SSEDefault.KMSDataEncryption, Equals, string(SM4Algorithm))
  2133. // Get default bucket info
  2134. bucketResult, err := client.GetBucketInfo(bucketName)
  2135. c.Assert(err, IsNil)
  2136. c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, string(KMSAlgorithm))
  2137. c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
  2138. c.Assert(bucketResult.BucketInfo.SseRule.KMSDataEncryption, Equals, string(SM4Algorithm))
  2139. err = client.DeleteBucket(bucketName)
  2140. c.Assert(err, IsNil)
  2141. }
  2142. func (s *OssClientSuite) TestBucketEncyptionPutObjectSuccess(c *C) {
  2143. client, err := New(endpoint, accessID, accessKey)
  2144. c.Assert(err, IsNil)
  2145. bucketName := bucketNamePrefix + RandLowStr(5)
  2146. err = client.CreateBucket(bucketName)
  2147. c.Assert(err, IsNil)
  2148. // SetBucketEncryption:KMS ,""
  2149. encryptionRule := ServerEncryptionRule{}
  2150. encryptionRule.SSEDefault.SSEAlgorithm = string(KMSAlgorithm)
  2151. var responseHeader http.Header
  2152. err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
  2153. c.Assert(err, IsNil)
  2154. requestId := GetRequestId(responseHeader)
  2155. c.Assert(len(requestId) > 0, Equals, true)
  2156. // GetBucketEncryption
  2157. getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
  2158. c.Assert(err, IsNil)
  2159. requestId = GetRequestId(responseHeader)
  2160. c.Assert(len(requestId) > 0, Equals, true)
  2161. // check encryption value
  2162. c.Assert(encryptionRule.SSEDefault.SSEAlgorithm, Equals, getResult.SSEDefault.SSEAlgorithm)
  2163. c.Assert(encryptionRule.SSEDefault.KMSMasterKeyID, Equals, getResult.SSEDefault.KMSMasterKeyID)
  2164. // Get default bucket info
  2165. bucketResult, err := client.GetBucketInfo(bucketName)
  2166. c.Assert(err, IsNil)
  2167. c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "KMS")
  2168. c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, "")
  2169. c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
  2170. err = client.DeleteBucket(bucketName)
  2171. c.Assert(err, IsNil)
  2172. }
  2173. func (s *OssClientSuite) TestBucketEncyptionPutObjectError(c *C) {
  2174. client, err := New(endpoint, accessID, accessKey)
  2175. c.Assert(err, IsNil)
  2176. bucketName := bucketNamePrefix + RandLowStr(5)
  2177. err = client.CreateBucket(bucketName)
  2178. c.Assert(err, IsNil)
  2179. // SetBucketEncryption:KMS ,""
  2180. encryptionRule := ServerEncryptionRule{}
  2181. encryptionRule.SSEDefault.SSEAlgorithm = string(KMSAlgorithm)
  2182. kmsId := "123"
  2183. encryptionRule.SSEDefault.KMSMasterKeyID = kmsId
  2184. var responseHeader http.Header
  2185. err = client.SetBucketEncryption(bucketName, encryptionRule, GetResponseHeader(&responseHeader))
  2186. c.Assert(err, IsNil)
  2187. requestId := GetRequestId(responseHeader)
  2188. c.Assert(len(requestId) > 0, Equals, true)
  2189. // GetBucketEncryption
  2190. getResult, err := client.GetBucketEncryption(bucketName, GetResponseHeader(&responseHeader))
  2191. c.Assert(err, IsNil)
  2192. requestId = GetRequestId(responseHeader)
  2193. c.Assert(len(requestId) > 0, Equals, true)
  2194. // check encryption value
  2195. c.Assert(encryptionRule.SSEDefault.SSEAlgorithm, Equals, getResult.SSEDefault.SSEAlgorithm)
  2196. c.Assert(encryptionRule.SSEDefault.KMSMasterKeyID, Equals, getResult.SSEDefault.KMSMasterKeyID)
  2197. // Get default bucket info
  2198. bucketResult, err := client.GetBucketInfo(bucketName)
  2199. c.Assert(err, IsNil)
  2200. c.Assert(bucketResult.BucketInfo.SseRule.SSEAlgorithm, Equals, "KMS")
  2201. c.Assert(bucketResult.BucketInfo.SseRule.KMSMasterKeyID, Equals, kmsId)
  2202. c.Assert(bucketResult.BucketInfo.Versioning, Equals, "")
  2203. // put and get object failure
  2204. bucket, err := client.Bucket(bucketName)
  2205. c.Assert(err, IsNil)
  2206. // put object failure
  2207. objectName := objectNamePrefix + RandStr(8)
  2208. context := RandStr(100)
  2209. err = bucket.PutObject(objectName, strings.NewReader(context))
  2210. c.Assert(err, NotNil)
  2211. err = client.DeleteBucket(bucketName)
  2212. c.Assert(err, IsNil)
  2213. }
  2214. func (s *OssClientSuite) TestBucketTaggingOperation(c *C) {
  2215. client, err := New(endpoint, accessID, accessKey)
  2216. c.Assert(err, IsNil)
  2217. bucketName := bucketNamePrefix + RandLowStr(5)
  2218. err = client.CreateBucket(bucketName)
  2219. c.Assert(err, IsNil)
  2220. var respHeader http.Header
  2221. // Bucket Tagging
  2222. var tagging Tagging
  2223. tagging.Tags = []Tag{Tag{Key: "testkey2", Value: "testvalue2"}}
  2224. err = client.SetBucketTagging(bucketName, tagging, GetResponseHeader(&respHeader))
  2225. c.Assert(err, IsNil)
  2226. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  2227. getResult, err := client.GetBucketTagging(bucketName)
  2228. c.Assert(err, IsNil)
  2229. c.Assert(getResult.Tags[0].Key, Equals, tagging.Tags[0].Key)
  2230. c.Assert(getResult.Tags[0].Value, Equals, tagging.Tags[0].Value)
  2231. // delete BucketTagging
  2232. err = client.DeleteBucketTagging(bucketName, GetResponseHeader(&respHeader))
  2233. c.Assert(err, IsNil)
  2234. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  2235. getResult, err = client.GetBucketTagging(bucketName, GetResponseHeader(&respHeader))
  2236. c.Assert(err, IsNil)
  2237. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  2238. c.Assert(len(getResult.Tags), Equals, 0)
  2239. err = client.DeleteBucket(bucketName)
  2240. c.Assert(err, IsNil)
  2241. }
  2242. func (s *OssClientSuite) TestListBucketsTagging(c *C) {
  2243. client, err := New(endpoint, accessID, accessKey)
  2244. c.Assert(err, IsNil)
  2245. bucketName1 := bucketNamePrefix + RandLowStr(5)
  2246. err = client.CreateBucket(bucketName1)
  2247. c.Assert(err, IsNil)
  2248. bucketName2 := bucketNamePrefix + RandLowStr(5)
  2249. err = client.CreateBucket(bucketName2)
  2250. c.Assert(err, IsNil)
  2251. // Bucket Tagging
  2252. var tagging Tagging
  2253. tagging.Tags = []Tag{Tag{Key: "testkey", Value: "testvalue"}}
  2254. err = client.SetBucketTagging(bucketName1, tagging)
  2255. c.Assert(err, IsNil)
  2256. // list bucket
  2257. listResult, err := client.ListBuckets(TagKey("testkey"))
  2258. c.Assert(err, IsNil)
  2259. c.Assert(len(listResult.Buckets), Equals, 1)
  2260. c.Assert(listResult.Buckets[0].Name, Equals, bucketName1)
  2261. client.DeleteBucket(bucketName1)
  2262. client.DeleteBucket(bucketName2)
  2263. }
  2264. func (s *OssClientSuite) TestGetBucketStat(c *C) {
  2265. client, err := New(endpoint, accessID, accessKey)
  2266. c.Assert(err, IsNil)
  2267. bucketName := bucketNamePrefix + RandLowStr(5)
  2268. err = client.CreateBucket(bucketName)
  2269. c.Assert(err, IsNil)
  2270. bucket, err := client.Bucket(bucketName)
  2271. c.Assert(err, IsNil)
  2272. // put object
  2273. objectName := objectNamePrefix + RandLowStr(5)
  2274. err = bucket.PutObject(objectName, strings.NewReader(RandStr(10)))
  2275. c.Assert(err, IsNil)
  2276. bucket.DeleteObject(objectName)
  2277. err = bucket.PutObject(objectName, strings.NewReader(RandStr(10)))
  2278. c.Assert(err, IsNil)
  2279. bucket.DeleteObject(objectName)
  2280. _, err = client.GetBucketStat(bucketName)
  2281. c.Assert(err, IsNil)
  2282. client.DeleteBucket(bucketName)
  2283. }
  2284. func (s *OssBucketSuite) TestGetBucketVersioning(c *C) {
  2285. // create a bucket with default proprety
  2286. client, err := New(endpoint, accessID, accessKey)
  2287. c.Assert(err, IsNil)
  2288. bucketName := bucketNamePrefix + RandLowStr(6)
  2289. var respHeader http.Header
  2290. err = client.CreateBucket(bucketName, GetResponseHeader(&respHeader))
  2291. c.Assert(err, IsNil)
  2292. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  2293. // put bucket version:enabled
  2294. var versioningConfig VersioningConfig
  2295. versioningConfig.Status = string(VersionEnabled)
  2296. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2297. c.Assert(err, IsNil)
  2298. // get bucket version success
  2299. versioningResult, err := client.GetBucketVersioning(bucketName, GetResponseHeader(&respHeader))
  2300. c.Assert(versioningResult.Status, Equals, "Enabled")
  2301. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  2302. ForceDeleteBucket(client, bucketName, c)
  2303. }
  2304. func (s *OssClientSuite) TestBucketPolicy(c *C) {
  2305. client, err := New(endpoint, accessID, accessKey)
  2306. c.Assert(err, IsNil)
  2307. bucketName := bucketNamePrefix + RandLowStr(5)
  2308. err = client.CreateBucket(bucketName)
  2309. c.Assert(err, IsNil)
  2310. var responseHeader http.Header
  2311. ret, err := client.GetBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
  2312. c.Assert(err, NotNil)
  2313. requestId := GetRequestId(responseHeader)
  2314. c.Assert(len(requestId) > 0, Equals, true)
  2315. policyInfo := `
  2316. {
  2317. "Version":"1",
  2318. "Statement":[
  2319. {
  2320. "Action":[
  2321. "oss:GetObject",
  2322. "oss:PutObject"
  2323. ],
  2324. "Effect":"Deny",
  2325. "Principal":"[123456790]",
  2326. "Resource":["acs:oss:*:1234567890:*/*"]
  2327. }
  2328. ]
  2329. }`
  2330. err = client.SetBucketPolicy(bucketName, policyInfo, GetResponseHeader(&responseHeader))
  2331. c.Assert(err, IsNil)
  2332. requestId = GetRequestId(responseHeader)
  2333. c.Assert(len(requestId) > 0, Equals, true)
  2334. ret, err = client.GetBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
  2335. c.Assert(err, IsNil)
  2336. testLogger.Println("policy:", ret)
  2337. c.Assert(ret, Equals, policyInfo)
  2338. requestId = GetRequestId(responseHeader)
  2339. c.Assert(len(requestId) > 0, Equals, true)
  2340. err = client.DeleteBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
  2341. c.Assert(err, IsNil)
  2342. requestId = GetRequestId(responseHeader)
  2343. c.Assert(len(requestId) > 0, Equals, true)
  2344. client.DeleteBucket(bucketName)
  2345. }
  2346. func (s *OssClientSuite) TestBucketPolicyNegative(c *C) {
  2347. client, err := New(endpoint, accessID, accessKey)
  2348. c.Assert(err, IsNil)
  2349. bucketName := bucketNamePrefix + RandLowStr(5)
  2350. err = client.CreateBucket(bucketName)
  2351. c.Assert(err, IsNil)
  2352. var responseHeader http.Header
  2353. _, err = client.GetBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
  2354. c.Assert(err, NotNil)
  2355. requestId := GetRequestId(responseHeader)
  2356. c.Assert(len(requestId) > 0, Equals, true)
  2357. // Setting the Version is 2, this is error policy
  2358. errPolicy := `
  2359. {
  2360. "Version":"2",
  2361. "Statement":[
  2362. {
  2363. "Action":[
  2364. "oss:GetObject",
  2365. "oss:PutObject"
  2366. ],
  2367. "Effect":"Deny",
  2368. "Principal":"[123456790]",
  2369. "Resource":["acs:oss:*:1234567890:*/*"]
  2370. }
  2371. ]
  2372. }`
  2373. err = client.SetBucketPolicy(bucketName, errPolicy, GetResponseHeader(&responseHeader))
  2374. c.Assert(err, NotNil)
  2375. testLogger.Println("err:", err)
  2376. requestId = GetRequestId(responseHeader)
  2377. c.Assert(len(requestId) > 0, Equals, true)
  2378. err = client.DeleteBucketPolicy(bucketName, GetResponseHeader(&responseHeader))
  2379. c.Assert(err, IsNil)
  2380. bucketNameEmpty := bucketNamePrefix + RandLowStr(5)
  2381. client.DeleteBucket(bucketNameEmpty)
  2382. err = client.DeleteBucketPolicy(bucketNameEmpty, GetResponseHeader(&responseHeader))
  2383. c.Assert(err, NotNil)
  2384. requestId = GetRequestId(responseHeader)
  2385. c.Assert(len(requestId) > 0, Equals, true)
  2386. client.DeleteBucket(bucketName)
  2387. }
  2388. func (s *OssClientSuite) TestSetBucketRequestPayment(c *C) {
  2389. client, err := New(endpoint, accessID, accessKey)
  2390. c.Assert(err, IsNil)
  2391. bucketName := bucketNamePrefix + RandLowStr(5)
  2392. err = client.CreateBucket(bucketName)
  2393. c.Assert(err, IsNil)
  2394. reqPayConf := RequestPaymentConfiguration{
  2395. Payer: "Requester",
  2396. }
  2397. err = client.SetBucketRequestPayment(bucketName, reqPayConf)
  2398. c.Assert(err, IsNil)
  2399. ret, err := client.GetBucketRequestPayment(bucketName)
  2400. c.Assert(err, IsNil)
  2401. c.Assert(ret.Payer, Equals, "Requester")
  2402. client.DeleteBucket(bucketName)
  2403. c.Assert(err, IsNil)
  2404. }
  2405. func (s *OssClientSuite) TestSetBucketRequestPaymentNegative(c *C) {
  2406. client, err := New(endpoint, accessID, accessKey)
  2407. c.Assert(err, IsNil)
  2408. bucketName := bucketNamePrefix + RandLowStr(5)
  2409. err = client.CreateBucket(bucketName)
  2410. c.Assert(err, IsNil)
  2411. reqPayConf := RequestPaymentConfiguration{
  2412. Payer: "Requesterttttt", // this is a error configuration
  2413. }
  2414. err = client.SetBucketRequestPayment(bucketName, reqPayConf)
  2415. c.Assert(err, NotNil)
  2416. ret, err := client.GetBucketRequestPayment(bucketName)
  2417. c.Assert(err, IsNil)
  2418. c.Assert(ret.Payer, Equals, "BucketOwner")
  2419. client.DeleteBucket(bucketName)
  2420. c.Assert(err, IsNil)
  2421. }
  2422. func (s *OssClientSuite) TestBucketQos(c *C) {
  2423. client, err := New(endpoint, accessID, accessKey)
  2424. c.Assert(err, IsNil)
  2425. ret, err := client.GetUserQoSInfo()
  2426. c.Assert(err, IsNil)
  2427. testLogger.Println("QosInfo:", ret)
  2428. bucketName := bucketNamePrefix + RandLowStr(5)
  2429. _ = client.DeleteBucket(bucketName)
  2430. err = client.CreateBucket(bucketName)
  2431. c.Assert(err, IsNil)
  2432. _, err = client.GetBucketQosInfo(bucketName)
  2433. c.Assert(err, NotNil)
  2434. // case 1 set BucketQoSConfiguration every member
  2435. five := 5
  2436. four := 4
  2437. totalQps := 200
  2438. qosConf := BucketQoSConfiguration{
  2439. TotalUploadBandwidth: &five,
  2440. IntranetUploadBandwidth: &four,
  2441. ExtranetUploadBandwidth: &four,
  2442. TotalDownloadBandwidth: &four,
  2443. IntranetDownloadBandwidth: &four,
  2444. ExtranetDownloadBandwidth: &four,
  2445. TotalQPS: &totalQps,
  2446. IntranetQPS: &totalQps,
  2447. ExtranetQPS: &totalQps,
  2448. }
  2449. var responseHeader http.Header
  2450. err = client.SetBucketQoSInfo(bucketName, qosConf, GetResponseHeader(&responseHeader))
  2451. c.Assert(err, IsNil)
  2452. requestId := GetRequestId(responseHeader)
  2453. c.Assert(len(requestId) > 0, Equals, true)
  2454. // wait a moment for configuration effect
  2455. time.Sleep(time.Second)
  2456. retQos, err := client.GetBucketQosInfo(bucketName)
  2457. c.Assert(err, IsNil)
  2458. // set qosConf default value
  2459. qosConf.XMLName.Local = "QoSConfiguration"
  2460. c.Assert(struct2string(retQos, c), Equals, struct2string(qosConf, c))
  2461. // case 2 set BucketQoSConfiguration not every member
  2462. qosConfNo := BucketQoSConfiguration{
  2463. TotalUploadBandwidth: &five,
  2464. IntranetUploadBandwidth: &four,
  2465. ExtranetUploadBandwidth: &four,
  2466. TotalDownloadBandwidth: &four,
  2467. IntranetDownloadBandwidth: &four,
  2468. ExtranetDownloadBandwidth: &four,
  2469. TotalQPS: &totalQps,
  2470. }
  2471. err = client.SetBucketQoSInfo(bucketName, qosConfNo)
  2472. c.Assert(err, IsNil)
  2473. // wait a moment for configuration effect
  2474. time.Sleep(time.Second)
  2475. retQos, err = client.GetBucketQosInfo(bucketName)
  2476. c.Assert(err, IsNil)
  2477. // set qosConfNo default value
  2478. qosConfNo.XMLName.Local = "QoSConfiguration"
  2479. defNum := -1
  2480. qosConfNo.IntranetQPS = &defNum
  2481. qosConfNo.ExtranetQPS = &defNum
  2482. c.Assert(struct2string(retQos, c), Equals, struct2string(qosConfNo, c))
  2483. err = client.DeleteBucketQosInfo(bucketName)
  2484. c.Assert(err, IsNil)
  2485. // wait a moment for configuration effect
  2486. time.Sleep(time.Second)
  2487. _, err = client.GetBucketQosInfo(bucketName)
  2488. c.Assert(err, NotNil)
  2489. // this is a error qos configuration
  2490. to := *ret.TotalUploadBandwidth + 2
  2491. qosErrConf := BucketQoSConfiguration{
  2492. TotalUploadBandwidth: &to, // this exceed user TotalUploadBandwidth
  2493. IntranetUploadBandwidth: &four,
  2494. ExtranetUploadBandwidth: &four,
  2495. TotalDownloadBandwidth: &four,
  2496. IntranetDownloadBandwidth: &four,
  2497. ExtranetDownloadBandwidth: &four,
  2498. TotalQPS: &totalQps,
  2499. IntranetQPS: &totalQps,
  2500. ExtranetQPS: &totalQps,
  2501. }
  2502. err = client.SetBucketQoSInfo(bucketName, qosErrConf)
  2503. c.Assert(err, NotNil)
  2504. err = client.DeleteBucketQosInfo(bucketName)
  2505. c.Assert(err, IsNil)
  2506. err = client.DeleteBucket(bucketName)
  2507. c.Assert(err, IsNil)
  2508. }
  2509. // struct to string
  2510. func struct2string(obj interface{}, c *C) string {
  2511. t := reflect.TypeOf(obj)
  2512. v := reflect.ValueOf(obj)
  2513. var data = make(map[string]interface{})
  2514. for i := 0; i < t.NumField(); i++ {
  2515. data[t.Field(i).Name] = v.Field(i).Interface()
  2516. }
  2517. str, err := json.Marshal(data)
  2518. c.Assert(err, IsNil)
  2519. return string(str)
  2520. }
  2521. type TestCredentials struct {
  2522. }
  2523. func (testCreInf *TestCredentials) GetAccessKeyID() string {
  2524. return os.Getenv("OSS_TEST_ACCESS_KEY_ID")
  2525. }
  2526. func (testCreInf *TestCredentials) GetAccessKeySecret() string {
  2527. return os.Getenv("OSS_TEST_ACCESS_KEY_SECRET")
  2528. }
  2529. func (testCreInf *TestCredentials) GetSecurityToken() string {
  2530. return ""
  2531. }
  2532. type TestCredentialsProvider struct {
  2533. }
  2534. func (testInfBuild *TestCredentialsProvider) GetCredentials() Credentials {
  2535. return &TestCredentials{}
  2536. }
  2537. func (s *OssClientSuite) TestClientCredentialInfBuild(c *C) {
  2538. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  2539. var defaultBuild TestCredentialsProvider
  2540. client, err := New(endpoint, "", "", SetCredentialsProvider(&defaultBuild))
  2541. c.Assert(err, IsNil)
  2542. err = client.CreateBucket(bucketNameTest)
  2543. c.Assert(err, IsNil)
  2544. err = client.DeleteBucket(bucketNameTest)
  2545. c.Assert(err, IsNil)
  2546. }
  2547. func (s *OssClientSuite) TestClientSetLocalIpError(c *C) {
  2548. // create client and bucket
  2549. ipAddr, err := net.ResolveIPAddr("ip", "127.0.0.1")
  2550. c.Assert(err, IsNil)
  2551. localTCPAddr := &(net.TCPAddr{IP: ipAddr.IP})
  2552. client, err := New(endpoint, accessID, accessKey, SetLocalAddr(localTCPAddr))
  2553. c.Assert(err, IsNil)
  2554. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  2555. err = client.CreateBucket(bucketNameTest)
  2556. c.Assert(err, NotNil)
  2557. }
  2558. func (s *OssClientSuite) TestClientSetLocalIpSuccess(c *C) {
  2559. //get local ip
  2560. conn, err := net.Dial("udp", "8.8.8.8:80")
  2561. c.Assert(err, IsNil)
  2562. localAddr := conn.LocalAddr().(*net.UDPAddr)
  2563. localIp := localAddr.IP.String()
  2564. conn.Close()
  2565. ipAddr, err := net.ResolveIPAddr("ip", localIp)
  2566. c.Assert(err, IsNil)
  2567. localTCPAddr := &(net.TCPAddr{IP: ipAddr.IP})
  2568. client, err := New(endpoint, accessID, accessKey, SetLocalAddr(localTCPAddr))
  2569. c.Assert(err, IsNil)
  2570. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  2571. err = client.CreateBucket(bucketNameTest)
  2572. c.Assert(err, IsNil)
  2573. err = client.DeleteBucket(bucketNameTest)
  2574. c.Assert(err, IsNil)
  2575. }
  2576. // TestCreateBucketInvalidName
  2577. func (s *OssClientSuite) TestCreateBucketInvalidName(c *C) {
  2578. var bucketNameTest = "-" + bucketNamePrefix + RandLowStr(6)
  2579. client, err := New(endpoint, accessID, accessKey)
  2580. c.Assert(err, IsNil)
  2581. // Create
  2582. err = client.CreateBucket(bucketNameTest)
  2583. c.Assert(err, NotNil)
  2584. }
  2585. // TestClientProcessEndpointSuccess
  2586. func (s *OssClientSuite) TestClientProcessEndpointSuccess(c *C) {
  2587. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  2588. testEndpoint := endpoint + "/" + "sina.com" + "?" + "para=abc"
  2589. client, err := New(testEndpoint, accessID, accessKey)
  2590. c.Assert(err, IsNil)
  2591. // Create
  2592. err = client.CreateBucket(bucketNameTest)
  2593. c.Assert(err, IsNil)
  2594. // delete
  2595. err = client.DeleteBucket(bucketNameTest)
  2596. c.Assert(err, IsNil)
  2597. }
  2598. // TestClientProcessEndpointSuccess
  2599. func (s *OssClientSuite) TestClientProcessEndpointError(c *C) {
  2600. var bucketNameTest = bucketNamePrefix + RandLowStr(6)
  2601. testEndpoint := "https://127.0.0.1/" + endpoint
  2602. client, err := New(testEndpoint, accessID, accessKey)
  2603. c.Assert(err, IsNil)
  2604. // Create
  2605. err = client.CreateBucket(bucketNameTest)
  2606. c.Assert(err, NotNil)
  2607. }
  2608. // TestClientBucketError
  2609. func (s *OssClientSuite) TestClientBucketError(c *C) {
  2610. client, err := New(endpoint, accessID, accessKey)
  2611. c.Assert(err, IsNil)
  2612. bucketName := "-" + RandLowStr(5)
  2613. _, err = client.Bucket(bucketName)
  2614. c.Assert(err, NotNil)
  2615. }
  2616. func (s *OssClientSuite) TestSetBucketInventory(c *C) {
  2617. client, err := New(endpoint, accessID, accessKey)
  2618. c.Assert(err, IsNil)
  2619. bucketName := bucketNamePrefix + RandLowStr(5)
  2620. err = client.CreateBucket(bucketName)
  2621. c.Assert(err, IsNil)
  2622. // encryption config
  2623. var invSseOss InvSseOss
  2624. invSseKms := InvSseKms{
  2625. KmsId: "keyId",
  2626. }
  2627. var invEncryption InvEncryption
  2628. bl := true
  2629. // not any encryption
  2630. invConfig := InventoryConfiguration{
  2631. Id: "report1",
  2632. IsEnabled: &bl,
  2633. Prefix: "filterPrefix/",
  2634. OSSBucketDestination: OSSBucketDestination{
  2635. Format: "CSV",
  2636. AccountId: accountID,
  2637. RoleArn: stsARN,
  2638. Bucket: "acs:oss:::" + bucketName,
  2639. Prefix: "prefix1",
  2640. },
  2641. Frequency: "Daily",
  2642. IncludedObjectVersions: "All",
  2643. OptionalFields: OptionalFields{
  2644. Field: []string{
  2645. "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
  2646. },
  2647. },
  2648. }
  2649. // case 1: not any encryption
  2650. err = client.SetBucketInventory(bucketName, invConfig)
  2651. c.Assert(err, IsNil)
  2652. // case 2: use kms encryption
  2653. invConfig.Id = "report2"
  2654. invEncryption.SseKms = &invSseKms
  2655. invEncryption.SseOss = nil
  2656. invConfig.OSSBucketDestination.Encryption = &invEncryption
  2657. err = client.SetBucketInventory(bucketName, invConfig)
  2658. c.Assert(err, IsNil)
  2659. // case 3: use SseOss encryption
  2660. invConfig.Id = "report3"
  2661. invEncryption.SseKms = nil
  2662. invEncryption.SseOss = &invSseOss
  2663. invConfig.OSSBucketDestination.Encryption = &invEncryption
  2664. err = client.SetBucketInventory(bucketName, invConfig)
  2665. c.Assert(err, IsNil)
  2666. //case 4: use two type encryption
  2667. invConfig.Id = "report4"
  2668. invEncryption.SseKms = &invSseKms
  2669. invEncryption.SseOss = &invSseOss
  2670. invConfig.OSSBucketDestination.Encryption = &invEncryption
  2671. err = client.SetBucketInventory(bucketName, invConfig)
  2672. c.Assert(err, NotNil)
  2673. err = client.DeleteBucket(bucketName)
  2674. c.Assert(err, IsNil)
  2675. }
  2676. func (s *OssClientSuite) TestBucketInventory(c *C) {
  2677. client, err := New(endpoint, accessID, accessKey)
  2678. c.Assert(err, IsNil)
  2679. bucketName := bucketNamePrefix + RandLowStr(5)
  2680. err = client.CreateBucket(bucketName)
  2681. c.Assert(err, IsNil)
  2682. bl := true
  2683. invConfig := InventoryConfiguration{
  2684. Id: "report1",
  2685. IsEnabled: &bl,
  2686. Prefix: "filterPrefix/",
  2687. OSSBucketDestination: OSSBucketDestination{
  2688. Format: "CSV",
  2689. AccountId: accountID,
  2690. RoleArn: stsARN,
  2691. Bucket: "acs:oss:::" + bucketName,
  2692. Prefix: "prefix1",
  2693. },
  2694. Frequency: "Daily",
  2695. IncludedObjectVersions: "All",
  2696. OptionalFields: OptionalFields{
  2697. Field: []string{
  2698. "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
  2699. },
  2700. },
  2701. }
  2702. // case 1: test SetBucketInventory
  2703. err = client.SetBucketInventory(bucketName, invConfig)
  2704. c.Assert(err, IsNil)
  2705. // case 2: test GetBucketInventory
  2706. out, err := client.GetBucketInventory(bucketName, "report1")
  2707. c.Assert(err, IsNil)
  2708. invConfig.XMLName.Local = "InventoryConfiguration"
  2709. invConfig.OSSBucketDestination.XMLName.Local = "OSSBucketDestination"
  2710. invConfig.OptionalFields.XMLName.Local = "OptionalFields"
  2711. c.Assert(struct2string(invConfig, c), Equals, struct2string(out, c))
  2712. // case 3: test ListBucketInventory
  2713. invConfig2 := InventoryConfiguration{
  2714. Id: "report2",
  2715. IsEnabled: &bl,
  2716. Prefix: "filterPrefix/",
  2717. OSSBucketDestination: OSSBucketDestination{
  2718. Format: "CSV",
  2719. AccountId: accountID,
  2720. RoleArn: stsARN,
  2721. Bucket: "acs:oss:::" + bucketName,
  2722. Prefix: "prefix1",
  2723. },
  2724. Frequency: "Daily",
  2725. IncludedObjectVersions: "All",
  2726. OptionalFields: OptionalFields{
  2727. Field: []string{
  2728. "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
  2729. },
  2730. },
  2731. }
  2732. invConfig2.XMLName.Local = "InventoryConfiguration"
  2733. invConfig2.OSSBucketDestination.XMLName.Local = "OSSBucketDestination"
  2734. invConfig2.OptionalFields.XMLName.Local = "OptionalFields"
  2735. err = client.SetBucketInventory(bucketName, invConfig2)
  2736. c.Assert(err, IsNil)
  2737. listInvConf, err := client.ListBucketInventory(bucketName, "", Marker("report1"), MaxKeys(2))
  2738. c.Assert(err, IsNil)
  2739. var listInvLocal ListInventoryConfigurationsResult
  2740. listInvLocal.InventoryConfiguration = []InventoryConfiguration{
  2741. invConfig,
  2742. invConfig2,
  2743. }
  2744. bo := false
  2745. listInvLocal.IsTruncated = &bo
  2746. listInvLocal.XMLName.Local = "ListInventoryConfigurationsResult"
  2747. c.Assert(struct2string(listInvLocal, c), Equals, struct2string(listInvConf, c))
  2748. for i := 3; i < 109; i++ {
  2749. invConfig2 := InventoryConfiguration{
  2750. Id: "report" + strconv.Itoa(i),
  2751. IsEnabled: &bl,
  2752. Prefix: "filterPrefix/",
  2753. OSSBucketDestination: OSSBucketDestination{
  2754. Format: "CSV",
  2755. AccountId: accountID,
  2756. RoleArn: stsARN,
  2757. Bucket: "acs:oss:::" + bucketName,
  2758. Prefix: "prefix1",
  2759. },
  2760. Frequency: "Daily",
  2761. IncludedObjectVersions: "All",
  2762. OptionalFields: OptionalFields{
  2763. Field: []string{
  2764. "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
  2765. },
  2766. },
  2767. }
  2768. err = client.SetBucketInventory(bucketName, invConfig2)
  2769. c.Assert(err, IsNil)
  2770. }
  2771. token := ""
  2772. for {
  2773. listInvConf1, err := client.ListBucketInventory(bucketName, token)
  2774. c.Assert(err, IsNil)
  2775. token = listInvConf1.NextContinuationToken
  2776. testLogger.Println(listInvConf1.NextContinuationToken, *listInvConf1.IsTruncated, token)
  2777. if *listInvConf1.IsTruncated == false {
  2778. break
  2779. } else {
  2780. c.Assert(listInvConf1.NextContinuationToken, Equals, "report91")
  2781. }
  2782. }
  2783. // case 4: test DeleteBucketInventory
  2784. for i := 1; i < 109; i++ {
  2785. err = client.DeleteBucketInventory(bucketName, "report"+strconv.Itoa(i))
  2786. c.Assert(err, IsNil)
  2787. }
  2788. err = client.DeleteBucket(bucketName)
  2789. c.Assert(err, IsNil)
  2790. }
  2791. func (s *OssClientSuite) TestBucketInventoryNegative(c *C) {
  2792. client, err := New(endpoint, accessID, accessKey)
  2793. c.Assert(err, IsNil)
  2794. bucketName := bucketNamePrefix + RandLowStr(5)
  2795. err = client.CreateBucket(bucketName)
  2796. c.Assert(err, IsNil)
  2797. bl := true
  2798. invConfigErr := InventoryConfiguration{
  2799. Id: "report1",
  2800. IsEnabled: &bl,
  2801. Prefix: "filterPrefix/",
  2802. OSSBucketDestination: OSSBucketDestination{
  2803. Format: "CSV",
  2804. AccountId: accountID,
  2805. RoleArn: stsARN,
  2806. Bucket: "test",
  2807. Prefix: "prefix1",
  2808. },
  2809. Frequency: "Daily",
  2810. IncludedObjectVersions: "All",
  2811. OptionalFields: OptionalFields{
  2812. Field: []string{
  2813. "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
  2814. },
  2815. },
  2816. }
  2817. // case 1: test SetBucketInventory
  2818. err = client.SetBucketInventory(bucketName, invConfigErr)
  2819. c.Assert(err, NotNil)
  2820. // case 2: test GetBucketInventory
  2821. _, err = client.GetBucketInventory(bucketName, "report1")
  2822. c.Assert(err, NotNil)
  2823. // case 3: test ListBucketInventory
  2824. _, err = client.ListBucketInventory(bucketName, "", Marker("report1"), MaxKeys(2))
  2825. c.Assert(err, NotNil)
  2826. // case 4: test DeleteBucketInventory
  2827. err = client.DeleteBucketInventory(bucketName, "report1")
  2828. c.Assert(err, IsNil)
  2829. err = client.DeleteBucket(bucketName)
  2830. c.Assert(err, IsNil)
  2831. }
  2832. func (s *OssClientSuite) TestBucketAsyncTask(c *C) {
  2833. client, err := New(endpoint, accessID, accessKey)
  2834. c.Assert(err, IsNil)
  2835. bucketName := bucketNamePrefix + RandLowStr(5)
  2836. err = client.CreateBucket(bucketName)
  2837. c.Assert(err, IsNil)
  2838. objectName := objectNamePrefix + RandLowStr(6)
  2839. // set asyn task,IgnoreSameKey is false
  2840. asynConf := AsyncFetchTaskConfiguration{
  2841. Url: "http://www.baidu.com",
  2842. Object: objectName,
  2843. Host: "",
  2844. ContentMD5: "",
  2845. Callback: "",
  2846. StorageClass: "",
  2847. IgnoreSameKey: false,
  2848. }
  2849. asynResult, err := client.SetBucketAsyncTask(bucketName, asynConf)
  2850. c.Assert(err, IsNil)
  2851. c.Assert(len(asynResult.TaskId) > 0, Equals, true)
  2852. // get asyn task
  2853. asynTask, err := client.GetBucketAsyncTask(bucketName, asynResult.TaskId)
  2854. c.Assert(err, IsNil)
  2855. c.Assert(asynResult.TaskId, Equals, asynTask.TaskId)
  2856. c.Assert(len(asynTask.State) > 0, Equals, true)
  2857. c.Assert(asynConf.Url, Equals, asynTask.TaskInfo.Url)
  2858. c.Assert(asynConf.Object, Equals, asynTask.TaskInfo.Object)
  2859. c.Assert(asynConf.Callback, Equals, asynTask.TaskInfo.Callback)
  2860. c.Assert(asynConf.IgnoreSameKey, Equals, asynTask.TaskInfo.IgnoreSameKey)
  2861. // test again,IgnoreSameKey is true
  2862. asynConf.IgnoreSameKey = true
  2863. asynResult, err = client.SetBucketAsyncTask(bucketName, asynConf)
  2864. c.Assert(err, IsNil)
  2865. c.Assert(len(asynResult.TaskId) > 0, Equals, true)
  2866. asynTask, err = client.GetBucketAsyncTask(bucketName, asynResult.TaskId)
  2867. c.Assert(asynConf.IgnoreSameKey, Equals, asynTask.TaskInfo.IgnoreSameKey)
  2868. err = client.DeleteBucket(bucketName)
  2869. c.Assert(err, IsNil)
  2870. }
  2871. func (s *OssClientSuite) TestClientOptionHeader(c *C) {
  2872. // create a bucket with default proprety
  2873. client, err := New(endpoint, accessID, accessKey)
  2874. c.Assert(err, IsNil)
  2875. bucketName := bucketNamePrefix + RandLowStr(6)
  2876. var respHeader http.Header
  2877. err = client.CreateBucket(bucketName, GetResponseHeader(&respHeader))
  2878. c.Assert(err, IsNil)
  2879. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  2880. // put bucket version:enabled
  2881. var versioningConfig VersioningConfig
  2882. versioningConfig.Status = string(VersionEnabled)
  2883. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2884. c.Assert(err, IsNil)
  2885. // get bucket version success,use payer
  2886. options := []Option{RequestPayer(BucketOwner), GetResponseHeader(&respHeader)}
  2887. versioningResult, err := client.GetBucketVersioning(bucketName, options...)
  2888. c.Assert(versioningResult.Status, Equals, "Enabled")
  2889. c.Assert(GetRequestId(respHeader) != "", Equals, true)
  2890. //list buckets,use payer
  2891. _, err = client.ListBuckets(options...)
  2892. c.Assert(err, IsNil)
  2893. ForceDeleteBucket(client, bucketName, c)
  2894. }
  2895. // compare with go1.7
  2896. func compareVersion(goVersion string) bool {
  2897. nowVersion := runtime.Version()
  2898. nowVersion = strings.Replace(nowVersion, "go", "", -1)
  2899. pSlice1 := strings.Split(goVersion, ".")
  2900. pSlice2 := strings.Split(nowVersion, ".")
  2901. for k, v := range pSlice2 {
  2902. n2, _ := strconv.Atoi(string(v))
  2903. n1, _ := strconv.Atoi(string(pSlice1[k]))
  2904. if n2 > n1 {
  2905. return true
  2906. }
  2907. if n2 < n1 {
  2908. return false
  2909. }
  2910. }
  2911. return true
  2912. }
  2913. func homeHandler(w http.ResponseWriter, r *http.Request) {
  2914. http.Redirect(w, r, "/redirectTo", http.StatusFound)
  2915. }
  2916. func targetHandler(w http.ResponseWriter, r *http.Request) {
  2917. fmt.Fprintf(w, "You have been redirected here!")
  2918. }
  2919. func (s *OssClientSuite) TestClientRedirect(c *C) {
  2920. // must go1.7.0 onward
  2921. if !compareVersion("1.7.0") {
  2922. return
  2923. }
  2924. // get port
  2925. rand.Seed(time.Now().Unix())
  2926. port := 10000 + rand.Intn(10000)
  2927. // start http server
  2928. httpAddr := fmt.Sprintf("127.0.0.1:%d", port)
  2929. mux := http.NewServeMux()
  2930. mux.HandleFunc("/redirectTo", targetHandler)
  2931. mux.HandleFunc("/", homeHandler)
  2932. svr := &http.Server{
  2933. Addr: httpAddr,
  2934. ReadTimeout: 10 * time.Second,
  2935. WriteTimeout: 10 * time.Second,
  2936. MaxHeaderBytes: 1 << 20,
  2937. Handler: mux,
  2938. }
  2939. go func() {
  2940. svr.ListenAndServe()
  2941. }()
  2942. url := "http://" + httpAddr
  2943. // create client 1,redirect disable
  2944. client1, err := New(endpoint, accessID, accessKey, RedirectEnabled(false))
  2945. resp, err := client1.Conn.client.Get(url)
  2946. c.Assert(err, IsNil)
  2947. c.Assert(resp.StatusCode, Equals, http.StatusFound)
  2948. resp.Body.Close()
  2949. // create client2, redirect enabled
  2950. client2, err := New(endpoint, accessID, accessKey, RedirectEnabled(true))
  2951. resp, err = client2.Conn.client.Get(url)
  2952. c.Assert(err, IsNil)
  2953. c.Assert(resp.StatusCode, Equals, 200)
  2954. data, err := ioutil.ReadAll(resp.Body)
  2955. c.Assert(string(data), Equals, "You have been redirected here!")
  2956. resp.Body.Close()
  2957. }