bucket_test.go 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006
  1. // Bucket test
  2. package oss
  3. import (
  4. "bytes"
  5. "encoding/base64"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "math/rand"
  11. "net/http"
  12. "os"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/baiyubin/aliyun-sts-go-sdk/sts"
  18. . "gopkg.in/check.v1"
  19. )
  20. type OssBucketSuite struct {
  21. client *Client
  22. bucket *Bucket
  23. archiveBucket *Bucket
  24. }
  25. var _ = Suite(&OssBucketSuite{})
  26. var (
  27. pastDate = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
  28. futureDate = time.Date(2049, time.January, 10, 23, 0, 0, 0, time.UTC)
  29. )
  30. // SetUpSuite runs once when the suite starts running.
  31. func (s *OssBucketSuite) SetUpSuite(c *C) {
  32. client, err := New(endpoint, accessID, accessKey)
  33. c.Assert(err, IsNil)
  34. s.client = client
  35. s.client.CreateBucket(bucketName)
  36. err = s.client.CreateBucket(archiveBucketName, StorageClass(StorageArchive))
  37. c.Assert(err, IsNil)
  38. bucket, err := s.client.Bucket(bucketName)
  39. c.Assert(err, IsNil)
  40. s.bucket = bucket
  41. archiveBucket, err := s.client.Bucket(archiveBucketName)
  42. c.Assert(err, IsNil)
  43. s.archiveBucket = archiveBucket
  44. testLogger.Println("test bucket started")
  45. }
  46. // TearDownSuite runs before each test or benchmark starts running.
  47. func (s *OssBucketSuite) TearDownSuite(c *C) {
  48. for _, bucket := range []*Bucket{s.bucket, s.archiveBucket} {
  49. // Delete multipart
  50. keyMarker := KeyMarker("")
  51. uploadIDMarker := UploadIDMarker("")
  52. for {
  53. lmu, err := bucket.ListMultipartUploads(keyMarker, uploadIDMarker)
  54. c.Assert(err, IsNil)
  55. for _, upload := range lmu.Uploads {
  56. imur := InitiateMultipartUploadResult{Bucket: bucketName, Key: upload.Key, UploadID: upload.UploadID}
  57. err = bucket.AbortMultipartUpload(imur)
  58. c.Assert(err, IsNil)
  59. }
  60. keyMarker = KeyMarker(lmu.NextKeyMarker)
  61. uploadIDMarker = UploadIDMarker(lmu.NextUploadIDMarker)
  62. if !lmu.IsTruncated {
  63. break
  64. }
  65. }
  66. // Delete objects
  67. marker := Marker("")
  68. for {
  69. lor, err := bucket.ListObjects(marker)
  70. c.Assert(err, IsNil)
  71. for _, object := range lor.Objects {
  72. err = bucket.DeleteObject(object.Key)
  73. c.Assert(err, IsNil)
  74. }
  75. marker = Marker(lor.NextMarker)
  76. if !lor.IsTruncated {
  77. break
  78. }
  79. }
  80. // Delete bucket
  81. err := s.client.DeleteBucket(bucket.BucketName)
  82. c.Assert(err, IsNil)
  83. }
  84. testLogger.Println("test bucket completed")
  85. }
  86. // SetUpTest runs after each test or benchmark runs.
  87. func (s *OssBucketSuite) SetUpTest(c *C) {
  88. err := removeTempFiles("../oss", ".jpg")
  89. c.Assert(err, IsNil)
  90. }
  91. // TearDownTest runs once after all tests or benchmarks have finished running.
  92. func (s *OssBucketSuite) TearDownTest(c *C) {
  93. err := removeTempFiles("../oss", ".jpg")
  94. c.Assert(err, IsNil)
  95. err = removeTempFiles("../oss", ".txt")
  96. c.Assert(err, IsNil)
  97. err = removeTempFiles("../oss", ".temp")
  98. c.Assert(err, IsNil)
  99. err = removeTempFiles("../oss", ".txt1")
  100. c.Assert(err, IsNil)
  101. err = removeTempFiles("../oss", ".txt2")
  102. c.Assert(err, IsNil)
  103. }
  104. // TestPutObject
  105. func (s *OssBucketSuite) TestPutObject(c *C) {
  106. objectName := objectNamePrefix + randStr(8)
  107. objectValue := "大江东去,浪淘尽,千古风流人物。 故垒西边,人道是、三国周郎赤壁。 乱石穿空,惊涛拍岸,卷起千堆雪。 江山如画,一时多少豪杰。" +
  108. "遥想公谨当年,小乔初嫁了,雄姿英发。 羽扇纶巾,谈笑间、樯橹灰飞烟灭。故国神游,多情应笑我,早生华发,人生如梦,一尊还酹江月。"
  109. // Put string
  110. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  111. c.Assert(err, IsNil)
  112. // Check
  113. body, err := s.bucket.GetObject(objectName)
  114. c.Assert(err, IsNil)
  115. str, err := readBody(body)
  116. c.Assert(err, IsNil)
  117. c.Assert(str, Equals, objectValue)
  118. acl, err := s.bucket.GetObjectACL(objectName)
  119. c.Assert(err, IsNil)
  120. testLogger.Println("aclRes:", acl)
  121. c.Assert(acl.ACL, Equals, "default")
  122. err = s.bucket.DeleteObject(objectName)
  123. c.Assert(err, IsNil)
  124. // Put bytes
  125. err = s.bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
  126. c.Assert(err, IsNil)
  127. // Check
  128. body, err = s.bucket.GetObject(objectName)
  129. c.Assert(err, IsNil)
  130. str, err = readBody(body)
  131. c.Assert(err, IsNil)
  132. c.Assert(str, Equals, objectValue)
  133. err = s.bucket.DeleteObject(objectName)
  134. c.Assert(err, IsNil)
  135. // Put file
  136. err = createFileAndWrite(objectName+".txt", []byte(objectValue))
  137. c.Assert(err, IsNil)
  138. fd, err := os.Open(objectName + ".txt")
  139. c.Assert(err, IsNil)
  140. err = s.bucket.PutObject(objectName, fd)
  141. c.Assert(err, IsNil)
  142. os.Remove(objectName + ".txt")
  143. // Check
  144. body, err = s.bucket.GetObject(objectName)
  145. c.Assert(err, IsNil)
  146. str, err = readBody(body)
  147. c.Assert(err, IsNil)
  148. c.Assert(str, Equals, objectValue)
  149. err = s.bucket.DeleteObject(objectName)
  150. c.Assert(err, IsNil)
  151. // Put with properties
  152. objectName = objectNamePrefix + randStr(8)
  153. options := []Option{
  154. Expires(futureDate),
  155. ObjectACL(ACLPublicRead),
  156. Meta("myprop", "mypropval"),
  157. }
  158. err = s.bucket.PutObject(objectName, strings.NewReader(objectValue), options...)
  159. c.Assert(err, IsNil)
  160. // Check
  161. body, err = s.bucket.GetObject(objectName)
  162. c.Assert(err, IsNil)
  163. str, err = readBody(body)
  164. c.Assert(err, IsNil)
  165. c.Assert(str, Equals, objectValue)
  166. acl, err = s.bucket.GetObjectACL(objectName)
  167. c.Assert(err, IsNil)
  168. testLogger.Println("GetObjectACL:", acl)
  169. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  170. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  171. c.Assert(err, IsNil)
  172. testLogger.Println("GetObjectDetailedMeta:", meta)
  173. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  174. err = s.bucket.DeleteObject(objectName)
  175. c.Assert(err, IsNil)
  176. }
  177. func (s *OssBucketSuite) TestSignURL(c *C) {
  178. objectName := objectNamePrefix + randStr(8)
  179. objectValue := randStr(20)
  180. filePath := randLowStr(10)
  181. content := "复写object"
  182. createFile(filePath, content, c)
  183. notExistfilePath := randLowStr(10)
  184. os.Remove(notExistfilePath)
  185. // Sign URL for put
  186. str, err := s.bucket.SignURL(objectName, HTTPPut, 60)
  187. c.Assert(err, IsNil)
  188. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  189. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  190. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  191. // Error put object with URL
  192. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue), ContentType("image/tiff"))
  193. c.Assert(err, NotNil)
  194. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  195. err = s.bucket.PutObjectFromFileWithURL(str, filePath, ContentType("image/tiff"))
  196. c.Assert(err, NotNil)
  197. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  198. // Put object with URL
  199. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  200. c.Assert(err, IsNil)
  201. acl, err := s.bucket.GetObjectACL(objectName)
  202. c.Assert(err, IsNil)
  203. c.Assert(acl.ACL, Equals, "default")
  204. // Get object meta
  205. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  206. c.Assert(err, IsNil)
  207. c.Assert(meta.Get(HTTPHeaderContentType), Equals, "application/octet-stream")
  208. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "")
  209. // Sign URL for function GetObjectWithURL
  210. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  211. c.Assert(err, IsNil)
  212. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  213. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  214. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  215. // Get object with URL
  216. body, err := s.bucket.GetObjectWithURL(str)
  217. c.Assert(err, IsNil)
  218. str, err = readBody(body)
  219. c.Assert(err, IsNil)
  220. c.Assert(str, Equals, objectValue)
  221. // Sign URL for function PutObjectWithURL
  222. options := []Option{
  223. ObjectACL(ACLPublicRead),
  224. Meta("myprop", "mypropval"),
  225. ContentType("image/tiff"),
  226. ResponseContentEncoding("deflate"),
  227. }
  228. str, err = s.bucket.SignURL(objectName, HTTPPut, 60, options...)
  229. c.Assert(err, IsNil)
  230. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  231. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  232. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  233. // Put object with URL from file
  234. // Without option, error
  235. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  236. c.Assert(err, NotNil)
  237. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  238. err = s.bucket.PutObjectFromFileWithURL(str, filePath)
  239. c.Assert(err, NotNil)
  240. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  241. // With option, error file
  242. err = s.bucket.PutObjectFromFileWithURL(str, notExistfilePath, options...)
  243. c.Assert(err, NotNil)
  244. // With option
  245. err = s.bucket.PutObjectFromFileWithURL(str, filePath, options...)
  246. c.Assert(err, IsNil)
  247. // Get object meta
  248. meta, err = s.bucket.GetObjectDetailedMeta(objectName)
  249. c.Assert(err, IsNil)
  250. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  251. c.Assert(meta.Get(HTTPHeaderContentType), Equals, "image/tiff")
  252. acl, err = s.bucket.GetObjectACL(objectName)
  253. c.Assert(err, IsNil)
  254. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  255. // Sign URL for function GetObjectToFileWithURL
  256. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  257. c.Assert(err, IsNil)
  258. // Get object to file with URL
  259. newFile := randStr(10)
  260. err = s.bucket.GetObjectToFileWithURL(str, newFile)
  261. c.Assert(err, IsNil)
  262. eq, err := compareFiles(filePath, newFile)
  263. c.Assert(err, IsNil)
  264. c.Assert(eq, Equals, true)
  265. os.Remove(newFile)
  266. // Get object to file error
  267. err = s.bucket.GetObjectToFileWithURL(str, newFile, options...)
  268. c.Assert(err, NotNil)
  269. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  270. _, err = os.Stat(newFile)
  271. c.Assert(err, NotNil)
  272. // Get object error
  273. body, err = s.bucket.GetObjectWithURL(str, options...)
  274. c.Assert(err, NotNil)
  275. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  276. c.Assert(body, IsNil)
  277. // Sign URL for function GetObjectToFileWithURL
  278. options = []Option{
  279. Expires(futureDate),
  280. ObjectACL(ACLPublicRead),
  281. Meta("myprop", "mypropval"),
  282. ContentType("image/tiff"),
  283. ResponseContentEncoding("deflate"),
  284. }
  285. str, err = s.bucket.SignURL(objectName, HTTPGet, 60, options...)
  286. c.Assert(err, IsNil)
  287. // Get object to file with URL and options
  288. err = s.bucket.GetObjectToFileWithURL(str, newFile, options...)
  289. c.Assert(err, IsNil)
  290. eq, err = compareFiles(filePath, newFile)
  291. c.Assert(err, IsNil)
  292. c.Assert(eq, Equals, true)
  293. os.Remove(newFile)
  294. // Get object to file error
  295. err = s.bucket.GetObjectToFileWithURL(str, newFile)
  296. c.Assert(err, NotNil)
  297. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  298. _, err = os.Stat(newFile)
  299. c.Assert(err, NotNil)
  300. // Get object error
  301. body, err = s.bucket.GetObjectWithURL(str)
  302. c.Assert(err, NotNil)
  303. c.Assert(err.(ServiceError).Code, Equals, "SignatureDoesNotMatch")
  304. c.Assert(body, IsNil)
  305. err = s.bucket.PutObjectFromFile(objectName, "../sample/The Go Programming Language.html")
  306. c.Assert(err, IsNil)
  307. str, err = s.bucket.SignURL(objectName, HTTPGet, 3600, AcceptEncoding("gzip"))
  308. c.Assert(err, IsNil)
  309. s.bucket.GetObjectToFileWithURL(str, newFile)
  310. c.Assert(err, IsNil)
  311. os.Remove(filePath)
  312. os.Remove(newFile)
  313. // Sign URL error
  314. str, err = s.bucket.SignURL(objectName, HTTPGet, -1)
  315. c.Assert(err, NotNil)
  316. err = s.bucket.DeleteObject(objectName)
  317. c.Assert(err, IsNil)
  318. // Invalid URL parse
  319. str = randStr(20)
  320. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  321. c.Assert(err, NotNil)
  322. err = s.bucket.GetObjectToFileWithURL(str, newFile)
  323. c.Assert(err, NotNil)
  324. }
  325. func (s *OssBucketSuite) TestSignURLWithEscapedKey(c *C) {
  326. // Key with '/'
  327. objectName := "zyimg/86/e8/653b5dc97bb0022051a84c632bc4"
  328. objectValue := "弃我去者,昨日之日不可留;乱我心者,今日之日多烦忧。长风万里送秋雁,对此可以酣高楼。蓬莱文章建安骨,中间小谢又清发。" +
  329. "俱怀逸兴壮思飞,欲上青天揽明月。抽刀断水水更流,举杯销愁愁更愁。人生在世不称意,明朝散发弄扁舟。"
  330. // Sign URL for function PutObjectWithURL
  331. str, err := s.bucket.SignURL(objectName, HTTPPut, 60)
  332. c.Assert(err, IsNil)
  333. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  334. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  335. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  336. // Put object with URL
  337. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  338. c.Assert(err, IsNil)
  339. // Sign URL for function GetObjectWithURL
  340. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  341. c.Assert(err, IsNil)
  342. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  343. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  344. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  345. // Get object with URL
  346. body, err := s.bucket.GetObjectWithURL(str)
  347. c.Assert(err, IsNil)
  348. str, err = readBody(body)
  349. c.Assert(err, IsNil)
  350. c.Assert(str, Equals, objectValue)
  351. // Key with escaped chars
  352. objectName = "<>[]()`?.,!@#$%^&'/*-_=+~:;"
  353. // Sign URL for funciton PutObjectWithURL
  354. str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
  355. c.Assert(err, IsNil)
  356. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  357. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  358. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  359. // Put object with URL
  360. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  361. c.Assert(err, IsNil)
  362. // Sign URL for function GetObjectWithURL
  363. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  364. c.Assert(err, IsNil)
  365. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  366. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  367. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  368. // Get object with URL
  369. body, err = s.bucket.GetObjectWithURL(str)
  370. c.Assert(err, IsNil)
  371. str, err = readBody(body)
  372. c.Assert(err, IsNil)
  373. c.Assert(str, Equals, objectValue)
  374. // Key with Chinese chars
  375. objectName = "风吹柳花满店香,吴姬压酒劝客尝。金陵子弟来相送,欲行不行各尽觞。请君试问东流水,别意与之谁短长。"
  376. // Sign URL for function PutObjectWithURL
  377. str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
  378. c.Assert(err, IsNil)
  379. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  380. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  381. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  382. // Put object with URL
  383. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  384. c.Assert(err, IsNil)
  385. // Sign URL for get function GetObjectWithURL
  386. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  387. c.Assert(err, IsNil)
  388. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  389. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  390. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  391. // Get object with URL
  392. body, err = s.bucket.GetObjectWithURL(str)
  393. c.Assert(err, IsNil)
  394. str, err = readBody(body)
  395. c.Assert(err, IsNil)
  396. c.Assert(str, Equals, objectValue)
  397. // Key
  398. objectName = "test/此情无计可消除/才下眉头/却上 心头/。,;:‘’“”?()『』【】《》!@#¥%……&×/test+ =-_*&^%$#@!`~[]{}()<>|\\/?.,;.txt"
  399. // Sign URL for function PutObjectWithURL
  400. str, err = s.bucket.SignURL(objectName, HTTPPut, 60)
  401. c.Assert(err, IsNil)
  402. // Put object with URL
  403. err = s.bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  404. c.Assert(err, IsNil)
  405. // Sign URL for function GetObjectWithURL
  406. str, err = s.bucket.SignURL(objectName, HTTPGet, 60)
  407. c.Assert(err, IsNil)
  408. // Get object with URL
  409. body, err = s.bucket.GetObjectWithURL(str)
  410. c.Assert(err, IsNil)
  411. str, err = readBody(body)
  412. c.Assert(err, IsNil)
  413. c.Assert(str, Equals, objectValue)
  414. // Put object
  415. err = s.bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
  416. c.Assert(err, IsNil)
  417. // Get object
  418. body, err = s.bucket.GetObject(objectName)
  419. c.Assert(err, IsNil)
  420. str, err = readBody(body)
  421. c.Assert(err, IsNil)
  422. c.Assert(str, Equals, objectValue)
  423. // Delete object
  424. err = s.bucket.DeleteObject(objectName)
  425. c.Assert(err, IsNil)
  426. }
  427. func (s *OssBucketSuite) TestSignURLWithEscapedKeyAndPorxy(c *C) {
  428. // Key with '/'
  429. objectName := "zyimg/86/e8/653b5dc97bb0022051a84c632bc4"
  430. objectValue := "弃我去者,昨日之日不可留;乱我心者,今日之日多烦忧。长风万里送秋雁,对此可以酣高楼。蓬莱文章建安骨,中间小谢又清发。" +
  431. "俱怀逸兴壮思飞,欲上青天揽明月。抽刀断水水更流,举杯销愁愁更愁。人生在世不称意,明朝散发弄扁舟。"
  432. client, err := New(endpoint, accessID, accessKey, AuthProxy(proxyHost, proxyUser, proxyPasswd))
  433. bucket, err := client.Bucket(bucketName)
  434. // Sign URL for put
  435. str, err := bucket.SignURL(objectName, HTTPPut, 60)
  436. c.Assert(err, IsNil)
  437. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  438. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  439. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  440. // Put object with URL
  441. err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  442. c.Assert(err, IsNil)
  443. // Sign URL for function GetObjectWithURL
  444. str, err = bucket.SignURL(objectName, HTTPGet, 60)
  445. c.Assert(err, IsNil)
  446. c.Assert(strings.Contains(str, HTTPParamExpires+"="), Equals, true)
  447. c.Assert(strings.Contains(str, HTTPParamAccessKeyID+"="), Equals, true)
  448. c.Assert(strings.Contains(str, HTTPParamSignature+"="), Equals, true)
  449. // Get object with URL
  450. body, err := bucket.GetObjectWithURL(str)
  451. c.Assert(err, IsNil)
  452. str, err = readBody(body)
  453. c.Assert(err, IsNil)
  454. c.Assert(str, Equals, objectValue)
  455. // Key with Chinese chars
  456. objectName = "test/此情无计可消除/才下眉头/却上 心头/。,;:‘’“”?()『』【】《》!@#¥%……&×/test+ =-_*&^%$#@!`~[]{}()<>|\\/?.,;.txt"
  457. // Sign URL for function PutObjectWithURL
  458. str, err = bucket.SignURL(objectName, HTTPPut, 60)
  459. c.Assert(err, IsNil)
  460. // Put object with URL
  461. err = bucket.PutObjectWithURL(str, strings.NewReader(objectValue))
  462. c.Assert(err, IsNil)
  463. // Sign URL for function GetObjectWithURL
  464. str, err = bucket.SignURL(objectName, HTTPGet, 60)
  465. c.Assert(err, IsNil)
  466. // Get object with URL
  467. body, err = bucket.GetObjectWithURL(str)
  468. c.Assert(err, IsNil)
  469. str, err = readBody(body)
  470. c.Assert(err, IsNil)
  471. c.Assert(str, Equals, objectValue)
  472. // Put object
  473. err = bucket.PutObject(objectName, bytes.NewReader([]byte(objectValue)))
  474. c.Assert(err, IsNil)
  475. // Get object
  476. body, err = bucket.GetObject(objectName)
  477. c.Assert(err, IsNil)
  478. str, err = readBody(body)
  479. c.Assert(err, IsNil)
  480. c.Assert(str, Equals, objectValue)
  481. // Delete object
  482. err = bucket.DeleteObject(objectName)
  483. c.Assert(err, IsNil)
  484. }
  485. // TestPutObjectType
  486. func (s *OssBucketSuite) TestPutObjectType(c *C) {
  487. objectName := objectNamePrefix + randStr(8)
  488. objectValue := "乱石穿空,惊涛拍岸,卷起千堆雪。 江山如画,一时多少豪杰。"
  489. // Put
  490. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  491. c.Assert(err, IsNil)
  492. // Check
  493. body, err := s.bucket.GetObject(objectName)
  494. c.Assert(err, IsNil)
  495. str, err := readBody(body)
  496. c.Assert(err, IsNil)
  497. c.Assert(str, Equals, objectValue)
  498. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  499. c.Assert(err, IsNil)
  500. c.Assert(meta.Get("Content-Type"), Equals, "application/octet-stream")
  501. err = s.bucket.DeleteObject(objectName)
  502. c.Assert(err, IsNil)
  503. // Put
  504. err = s.bucket.PutObject(objectName+".txt", strings.NewReader(objectValue))
  505. c.Assert(err, IsNil)
  506. meta, err = s.bucket.GetObjectDetailedMeta(objectName + ".txt")
  507. c.Assert(err, IsNil)
  508. c.Assert(meta.Get("Content-Type"), Equals, "text/plain; charset=utf-8")
  509. err = s.bucket.DeleteObject(objectName + ".txt")
  510. c.Assert(err, IsNil)
  511. // Put
  512. err = s.bucket.PutObject(objectName+".apk", strings.NewReader(objectValue))
  513. c.Assert(err, IsNil)
  514. meta, err = s.bucket.GetObjectDetailedMeta(objectName + ".apk")
  515. c.Assert(err, IsNil)
  516. c.Assert(meta.Get("Content-Type"), Equals, "application/vnd.android.package-archive")
  517. err = s.bucket.DeleteObject(objectName + ".txt")
  518. c.Assert(err, IsNil)
  519. }
  520. // TestPutObject
  521. func (s *OssBucketSuite) TestPutObjectKeyChars(c *C) {
  522. objectName := objectNamePrefix + randStr(8)
  523. objectValue := "白日依山尽,黄河入海流。欲穷千里目,更上一层楼。"
  524. // Put
  525. objectKey := objectName + "十步杀一人,千里不留行。事了拂衣去,深藏身与名"
  526. err := s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
  527. c.Assert(err, IsNil)
  528. // Check
  529. body, err := s.bucket.GetObject(objectKey)
  530. c.Assert(err, IsNil)
  531. str, err := readBody(body)
  532. c.Assert(err, IsNil)
  533. c.Assert(str, Equals, objectValue)
  534. err = s.bucket.DeleteObject(objectKey)
  535. c.Assert(err, IsNil)
  536. // Put
  537. objectKey = objectName + "ごきげん如何ですかおれの顔をよく拝んでおけ"
  538. err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
  539. c.Assert(err, IsNil)
  540. // Check
  541. body, err = s.bucket.GetObject(objectKey)
  542. c.Assert(err, IsNil)
  543. str, err = readBody(body)
  544. c.Assert(err, IsNil)
  545. c.Assert(str, Equals, objectValue)
  546. err = s.bucket.DeleteObject(objectKey)
  547. c.Assert(err, IsNil)
  548. // Put
  549. objectKey = objectName + "~!@#$%^&*()_-+=|\\[]{}<>,./?"
  550. err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
  551. c.Assert(err, IsNil)
  552. // Check
  553. body, err = s.bucket.GetObject(objectKey)
  554. c.Assert(err, IsNil)
  555. str, err = readBody(body)
  556. c.Assert(err, IsNil)
  557. c.Assert(str, Equals, objectValue)
  558. err = s.bucket.DeleteObject(objectKey)
  559. c.Assert(err, IsNil)
  560. // Put
  561. objectKey = "go/中国 日本 +-#&=*"
  562. err = s.bucket.PutObject(objectKey, strings.NewReader(objectValue))
  563. c.Assert(err, IsNil)
  564. // Check
  565. body, err = s.bucket.GetObject(objectKey)
  566. c.Assert(err, IsNil)
  567. str, err = readBody(body)
  568. c.Assert(err, IsNil)
  569. c.Assert(str, Equals, objectValue)
  570. err = s.bucket.DeleteObject(objectKey)
  571. c.Assert(err, IsNil)
  572. }
  573. // TestPutObjectNegative
  574. func (s *OssBucketSuite) TestPutObjectNegative(c *C) {
  575. objectName := objectNamePrefix + randStr(8)
  576. objectValue := "大江东去,浪淘尽,千古风流人物。 "
  577. // Put
  578. objectName = objectNamePrefix + randStr(8)
  579. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue),
  580. Meta("meta-my", "myprop"))
  581. c.Assert(err, IsNil)
  582. // Check meta
  583. body, err := s.bucket.GetObject(objectName)
  584. c.Assert(err, IsNil)
  585. str, err := readBody(body)
  586. c.Assert(err, IsNil)
  587. c.Assert(str, Equals, objectValue)
  588. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  589. c.Assert(err, IsNil)
  590. c.Assert(meta.Get("X-Oss-Meta-My"), Not(Equals), "myprop")
  591. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "")
  592. err = s.bucket.DeleteObject(objectName)
  593. c.Assert(err, IsNil)
  594. // Invalid option
  595. err = s.bucket.PutObject(objectName, strings.NewReader(objectValue),
  596. IfModifiedSince(pastDate))
  597. c.Assert(err, NotNil)
  598. err = s.bucket.PutObjectFromFile(objectName, "bucket.go", IfModifiedSince(pastDate))
  599. c.Assert(err, NotNil)
  600. err = s.bucket.PutObjectFromFile(objectName, "/tmp/xxx")
  601. c.Assert(err, NotNil)
  602. }
  603. // TestPutObjectFromFile
  604. func (s *OssBucketSuite) TestPutObjectFromFile(c *C) {
  605. objectName := objectNamePrefix + randStr(8)
  606. localFile := "../sample/BingWallpaper-2015-11-07.jpg"
  607. newFile := "newpic11.jpg"
  608. // Put
  609. err := s.bucket.PutObjectFromFile(objectName, localFile)
  610. c.Assert(err, IsNil)
  611. // Check
  612. err = s.bucket.GetObjectToFile(objectName, newFile)
  613. c.Assert(err, IsNil)
  614. eq, err := compareFiles(localFile, newFile)
  615. c.Assert(err, IsNil)
  616. c.Assert(eq, Equals, true)
  617. acl, err := s.bucket.GetObjectACL(objectName)
  618. c.Assert(err, IsNil)
  619. testLogger.Println("aclRes:", acl)
  620. c.Assert(acl.ACL, Equals, "default")
  621. err = s.bucket.DeleteObject(objectName)
  622. c.Assert(err, IsNil)
  623. // Put with properties
  624. options := []Option{
  625. Expires(futureDate),
  626. ObjectACL(ACLPublicRead),
  627. Meta("myprop", "mypropval"),
  628. }
  629. os.Remove(newFile)
  630. err = s.bucket.PutObjectFromFile(objectName, localFile, options...)
  631. c.Assert(err, IsNil)
  632. // Check
  633. err = s.bucket.GetObjectToFile(objectName, newFile)
  634. c.Assert(err, IsNil)
  635. eq, err = compareFiles(localFile, newFile)
  636. c.Assert(err, IsNil)
  637. c.Assert(eq, Equals, true)
  638. acl, err = s.bucket.GetObjectACL(objectName)
  639. c.Assert(err, IsNil)
  640. testLogger.Println("GetObjectACL:", acl)
  641. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  642. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  643. c.Assert(err, IsNil)
  644. testLogger.Println("GetObjectDetailedMeta:", meta)
  645. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  646. err = s.bucket.DeleteObject(objectName)
  647. c.Assert(err, IsNil)
  648. os.Remove(newFile)
  649. }
  650. // TestPutObjectFromFile
  651. func (s *OssBucketSuite) TestPutObjectFromFileType(c *C) {
  652. objectName := objectNamePrefix + randStr(8)
  653. localFile := "../sample/BingWallpaper-2015-11-07.jpg"
  654. newFile := randStr(8) + ".jpg"
  655. // Put
  656. err := s.bucket.PutObjectFromFile(objectName, localFile)
  657. c.Assert(err, IsNil)
  658. // Check
  659. err = s.bucket.GetObjectToFile(objectName, newFile)
  660. c.Assert(err, IsNil)
  661. eq, err := compareFiles(localFile, newFile)
  662. c.Assert(err, IsNil)
  663. c.Assert(eq, Equals, true)
  664. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  665. c.Assert(err, IsNil)
  666. c.Assert(meta.Get("Content-Type"), Equals, "image/jpeg")
  667. err = s.bucket.DeleteObject(objectName)
  668. c.Assert(err, IsNil)
  669. os.Remove(newFile)
  670. }
  671. // TestGetObject
  672. func (s *OssBucketSuite) TestGetObject(c *C) {
  673. objectName := objectNamePrefix + randStr(8)
  674. objectValue := "长忆观潮,满郭人争江上望。来疑沧海尽成空,万面鼓声中。弄潮儿向涛头立,手把红旗旗不湿。别来几向梦中看,梦觉尚心寒。"
  675. // Put
  676. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  677. c.Assert(err, IsNil)
  678. // Check
  679. body, err := s.bucket.GetObject(objectName)
  680. c.Assert(err, IsNil)
  681. data, err := ioutil.ReadAll(body)
  682. body.Close()
  683. str := string(data)
  684. c.Assert(str, Equals, objectValue)
  685. testLogger.Println("GetObjec:", str)
  686. // Range
  687. var subObjectValue = string(([]byte(objectValue))[15:36])
  688. body, err = s.bucket.GetObject(objectName, Range(15, 35))
  689. c.Assert(err, IsNil)
  690. data, err = ioutil.ReadAll(body)
  691. body.Close()
  692. str = string(data)
  693. c.Assert(str, Equals, subObjectValue)
  694. testLogger.Println("GetObject:", str, ",", subObjectValue)
  695. // If-Modified-Since
  696. _, err = s.bucket.GetObject(objectName, IfModifiedSince(futureDate))
  697. c.Assert(err, NotNil)
  698. // If-Unmodified-Since
  699. body, err = s.bucket.GetObject(objectName, IfUnmodifiedSince(futureDate))
  700. c.Assert(err, IsNil)
  701. data, err = ioutil.ReadAll(body)
  702. body.Close()
  703. c.Assert(string(data), Equals, objectValue)
  704. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  705. c.Assert(err, IsNil)
  706. // If-Match
  707. body, err = s.bucket.GetObject(objectName, IfMatch(meta.Get("Etag")))
  708. c.Assert(err, IsNil)
  709. data, err = ioutil.ReadAll(body)
  710. body.Close()
  711. c.Assert(string(data), Equals, objectValue)
  712. // If-None-Match
  713. _, err = s.bucket.GetObject(objectName, IfNoneMatch(meta.Get("Etag")))
  714. c.Assert(err, NotNil)
  715. // process
  716. err = s.bucket.PutObjectFromFile(objectName, "../sample/BingWallpaper-2015-11-07.jpg")
  717. c.Assert(err, IsNil)
  718. _, err = s.bucket.GetObject(objectName, Process("image/format,png"))
  719. c.Assert(err, IsNil)
  720. err = s.bucket.DeleteObject(objectName)
  721. c.Assert(err, IsNil)
  722. }
  723. // TestGetObjectNegative
  724. func (s *OssBucketSuite) TestGetObjectToWriterNegative(c *C) {
  725. objectName := objectNamePrefix + randStr(8)
  726. objectValue := "长忆观潮,满郭人争江上望。"
  727. // Object not exist
  728. _, err := s.bucket.GetObject("NotExist")
  729. c.Assert(err, NotNil)
  730. // Constraint invalid
  731. err = s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  732. c.Assert(err, IsNil)
  733. // Out of range
  734. _, err = s.bucket.GetObject(objectName, Range(15, 1000))
  735. c.Assert(err, IsNil)
  736. // Not exist
  737. err = s.bucket.GetObjectToFile(objectName, "/root/123abc9874")
  738. c.Assert(err, NotNil)
  739. // Invalid option
  740. _, err = s.bucket.GetObject(objectName, ACL(ACLPublicRead))
  741. c.Assert(err, IsNil)
  742. err = s.bucket.GetObjectToFile(objectName, "newpic15.jpg", ACL(ACLPublicRead))
  743. c.Assert(err, IsNil)
  744. err = s.bucket.DeleteObject(objectName)
  745. c.Assert(err, IsNil)
  746. }
  747. // TestGetObjectToFile
  748. func (s *OssBucketSuite) TestGetObjectToFile(c *C) {
  749. objectName := objectNamePrefix + randStr(8)
  750. objectValue := "江南好,风景旧曾谙;日出江花红胜火,春来江水绿如蓝。能不忆江南?江南忆,最忆是杭州;山寺月中寻桂子,郡亭枕上看潮头。何日更重游!"
  751. newFile := randStr(8) + ".jpg"
  752. // Put
  753. var val = []byte(objectValue)
  754. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  755. c.Assert(err, IsNil)
  756. // Check
  757. err = s.bucket.GetObjectToFile(objectName, newFile)
  758. c.Assert(err, IsNil)
  759. eq, err := compareFileData(newFile, val)
  760. c.Assert(err, IsNil)
  761. c.Assert(eq, Equals, true)
  762. os.Remove(newFile)
  763. // Range
  764. err = s.bucket.GetObjectToFile(objectName, newFile, Range(15, 35))
  765. c.Assert(err, IsNil)
  766. eq, err = compareFileData(newFile, val[15:36])
  767. c.Assert(err, IsNil)
  768. c.Assert(eq, Equals, true)
  769. os.Remove(newFile)
  770. err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("15-35"))
  771. c.Assert(err, IsNil)
  772. eq, err = compareFileData(newFile, val[15:36])
  773. c.Assert(err, IsNil)
  774. c.Assert(eq, Equals, true)
  775. os.Remove(newFile)
  776. err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("15-"))
  777. c.Assert(err, IsNil)
  778. eq, err = compareFileData(newFile, val[15:])
  779. c.Assert(err, IsNil)
  780. c.Assert(eq, Equals, true)
  781. os.Remove(newFile)
  782. err = s.bucket.GetObjectToFile(objectName, newFile, NormalizedRange("-10"))
  783. c.Assert(err, IsNil)
  784. eq, err = compareFileData(newFile, val[(len(val)-10):len(val)])
  785. c.Assert(err, IsNil)
  786. c.Assert(eq, Equals, true)
  787. os.Remove(newFile)
  788. // If-Modified-Since
  789. err = s.bucket.GetObjectToFile(objectName, newFile, IfModifiedSince(futureDate))
  790. c.Assert(err, NotNil)
  791. // If-Unmodified-Since
  792. err = s.bucket.GetObjectToFile(objectName, newFile, IfUnmodifiedSince(futureDate))
  793. c.Assert(err, IsNil)
  794. eq, err = compareFileData(newFile, val)
  795. c.Assert(err, IsNil)
  796. c.Assert(eq, Equals, true)
  797. os.Remove(newFile)
  798. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  799. c.Assert(err, IsNil)
  800. testLogger.Println("GetObjectDetailedMeta:", meta)
  801. // If-Match
  802. err = s.bucket.GetObjectToFile(objectName, newFile, IfMatch(meta.Get("Etag")))
  803. c.Assert(err, IsNil)
  804. eq, err = compareFileData(newFile, val)
  805. c.Assert(err, IsNil)
  806. c.Assert(eq, Equals, true)
  807. // If-None-Match
  808. err = s.bucket.GetObjectToFile(objectName, newFile, IfNoneMatch(meta.Get("Etag")))
  809. c.Assert(err, NotNil)
  810. // Accept-Encoding:gzip
  811. err = s.bucket.PutObjectFromFile(objectName, "../sample/The Go Programming Language.html")
  812. c.Assert(err, IsNil)
  813. err = s.bucket.GetObjectToFile(objectName, newFile, AcceptEncoding("gzip"))
  814. c.Assert(err, IsNil)
  815. os.Remove(newFile)
  816. err = s.bucket.DeleteObject(objectName)
  817. c.Assert(err, IsNil)
  818. }
  819. // TestListObjects
  820. func (s *OssBucketSuite) TestListObjects(c *C) {
  821. objectName := objectNamePrefix + randStr(8)
  822. // List empty bucket
  823. lor, err := s.bucket.ListObjects()
  824. c.Assert(err, IsNil)
  825. left := len(lor.Objects)
  826. // Put three objects
  827. err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  828. c.Assert(err, IsNil)
  829. err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
  830. c.Assert(err, IsNil)
  831. err = s.bucket.PutObject(objectName+"3", strings.NewReader(""))
  832. c.Assert(err, IsNil)
  833. // List
  834. lor, err = s.bucket.ListObjects()
  835. c.Assert(err, IsNil)
  836. c.Assert(len(lor.Objects), Equals, left+3)
  837. // List with prefix
  838. lor, err = s.bucket.ListObjects(Prefix(objectName + "2"))
  839. c.Assert(err, IsNil)
  840. c.Assert(len(lor.Objects), Equals, 1)
  841. lor, err = s.bucket.ListObjects(Prefix(objectName + "22"))
  842. c.Assert(err, IsNil)
  843. c.Assert(len(lor.Objects), Equals, 0)
  844. // List with max keys
  845. lor, err = s.bucket.ListObjects(Prefix(objectName), MaxKeys(2))
  846. c.Assert(err, IsNil)
  847. c.Assert(len(lor.Objects), Equals, 2)
  848. // List with marker
  849. lor, err = s.bucket.ListObjects(Marker(objectName+"1"), MaxKeys(1))
  850. c.Assert(err, IsNil)
  851. c.Assert(len(lor.Objects), Equals, 1)
  852. err = s.bucket.DeleteObject(objectName + "1")
  853. c.Assert(err, IsNil)
  854. err = s.bucket.DeleteObject(objectName + "2")
  855. c.Assert(err, IsNil)
  856. err = s.bucket.DeleteObject(objectName + "3")
  857. c.Assert(err, IsNil)
  858. }
  859. // TestListObjects
  860. func (s *OssBucketSuite) TestListObjectsEncodingType(c *C) {
  861. prefix := objectNamePrefix + "床前明月光,疑是地上霜。举头望明月,低头思故乡。"
  862. for i := 0; i < 10; i++ {
  863. err := s.bucket.PutObject(prefix+strconv.Itoa(i), strings.NewReader(""))
  864. c.Assert(err, IsNil)
  865. }
  866. lor, err := s.bucket.ListObjects(Prefix(objectNamePrefix + "床前明月光,"))
  867. c.Assert(err, IsNil)
  868. c.Assert(len(lor.Objects), Equals, 10)
  869. lor, err = s.bucket.ListObjects(Marker(objectNamePrefix + "床前明月光,疑是地上霜。举头望明月,低头思故乡。"))
  870. c.Assert(err, IsNil)
  871. c.Assert(len(lor.Objects), Equals, 10)
  872. lor, err = s.bucket.ListObjects(Prefix(objectNamePrefix + "床前明月光"))
  873. c.Assert(err, IsNil)
  874. for i, obj := range lor.Objects {
  875. c.Assert(obj.Key, Equals, prefix+strconv.Itoa(i))
  876. }
  877. for i := 0; i < 10; i++ {
  878. err = s.bucket.DeleteObject(prefix + strconv.Itoa(i))
  879. c.Assert(err, IsNil)
  880. }
  881. // Special characters
  882. objectName := objectNamePrefix + "` ~ ! @ # $ % ^ & * () - _ + =[] {} \\ | < > , . ? / 0"
  883. err = s.bucket.PutObject(objectName, strings.NewReader("明月几时有,把酒问青天"))
  884. c.Assert(err, IsNil)
  885. lor, err = s.bucket.ListObjects(Prefix(objectName))
  886. c.Assert(err, IsNil)
  887. c.Assert(len(lor.Objects), Equals, 1)
  888. err = s.bucket.DeleteObject(objectName)
  889. c.Assert(err, IsNil)
  890. objectName = objectNamePrefix + "中国 日本 +-#&=*"
  891. err = s.bucket.PutObject(objectName, strings.NewReader("明月几时有,把酒问青天"))
  892. c.Assert(err, IsNil)
  893. lor, err = s.bucket.ListObjects(Prefix(objectName))
  894. c.Assert(err, IsNil)
  895. c.Assert(len(lor.Objects), Equals, 1)
  896. err = s.bucket.DeleteObject(objectName)
  897. c.Assert(err, IsNil)
  898. }
  899. // TestIsBucketExist
  900. func (s *OssBucketSuite) TestIsObjectExist(c *C) {
  901. objectName := objectNamePrefix + randStr(8)
  902. // Put three objects
  903. err := s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  904. c.Assert(err, IsNil)
  905. err = s.bucket.PutObject(objectName+"11", strings.NewReader(""))
  906. c.Assert(err, IsNil)
  907. err = s.bucket.PutObject(objectName+"111", strings.NewReader(""))
  908. c.Assert(err, IsNil)
  909. // Exist
  910. exist, err := s.bucket.IsObjectExist(objectName + "11")
  911. c.Assert(err, IsNil)
  912. c.Assert(exist, Equals, true)
  913. exist, err = s.bucket.IsObjectExist(objectName + "1")
  914. c.Assert(err, IsNil)
  915. c.Assert(exist, Equals, true)
  916. exist, err = s.bucket.IsObjectExist(objectName + "111")
  917. c.Assert(err, IsNil)
  918. c.Assert(exist, Equals, true)
  919. // Not exist
  920. exist, err = s.bucket.IsObjectExist(objectName + "1111")
  921. c.Assert(err, IsNil)
  922. c.Assert(exist, Equals, false)
  923. exist, err = s.bucket.IsObjectExist(objectName)
  924. c.Assert(err, IsNil)
  925. c.Assert(exist, Equals, false)
  926. err = s.bucket.DeleteObject(objectName + "1")
  927. c.Assert(err, IsNil)
  928. err = s.bucket.DeleteObject(objectName + "11")
  929. c.Assert(err, IsNil)
  930. err = s.bucket.DeleteObject(objectName + "111")
  931. c.Assert(err, IsNil)
  932. }
  933. // TestDeleteObject
  934. func (s *OssBucketSuite) TestDeleteObject(c *C) {
  935. objectName := objectNamePrefix + randStr(8)
  936. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  937. c.Assert(err, IsNil)
  938. lor, err := s.bucket.ListObjects(Prefix(objectName))
  939. c.Assert(err, IsNil)
  940. c.Assert(len(lor.Objects), Equals, 1)
  941. // Delete
  942. err = s.bucket.DeleteObject(objectName)
  943. c.Assert(err, IsNil)
  944. // Duplicate delete
  945. err = s.bucket.DeleteObject(objectName)
  946. c.Assert(err, IsNil)
  947. lor, err = s.bucket.ListObjects(Prefix(objectName))
  948. c.Assert(err, IsNil)
  949. c.Assert(len(lor.Objects), Equals, 0)
  950. }
  951. // TestDeleteObjects
  952. func (s *OssBucketSuite) TestDeleteObjects(c *C) {
  953. objectName := objectNamePrefix + randStr(8)
  954. // Delete objects
  955. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  956. c.Assert(err, IsNil)
  957. res, err := s.bucket.DeleteObjects([]string{objectName})
  958. c.Assert(err, IsNil)
  959. c.Assert(len(res.DeletedObjects), Equals, 1)
  960. lor, err := s.bucket.ListObjects(Prefix(objectName))
  961. c.Assert(err, IsNil)
  962. c.Assert(len(lor.Objects), Equals, 0)
  963. // Delete objects
  964. err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  965. c.Assert(err, IsNil)
  966. err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
  967. c.Assert(err, IsNil)
  968. res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"})
  969. c.Assert(err, IsNil)
  970. c.Assert(len(res.DeletedObjects), Equals, 2)
  971. lor, err = s.bucket.ListObjects(Prefix(objectName))
  972. c.Assert(err, IsNil)
  973. c.Assert(len(lor.Objects), Equals, 0)
  974. // Delete 0
  975. _, err = s.bucket.DeleteObjects([]string{})
  976. c.Assert(err, NotNil)
  977. // DeleteObjectsQuiet
  978. err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  979. c.Assert(err, IsNil)
  980. err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
  981. c.Assert(err, IsNil)
  982. res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"},
  983. DeleteObjectsQuiet(false))
  984. c.Assert(err, IsNil)
  985. c.Assert(len(res.DeletedObjects), Equals, 2)
  986. lor, err = s.bucket.ListObjects(Prefix(objectName))
  987. c.Assert(err, IsNil)
  988. c.Assert(len(lor.Objects), Equals, 0)
  989. // DeleteObjectsQuiet
  990. err = s.bucket.PutObject(objectName+"1", strings.NewReader(""))
  991. c.Assert(err, IsNil)
  992. err = s.bucket.PutObject(objectName+"2", strings.NewReader(""))
  993. c.Assert(err, IsNil)
  994. res, err = s.bucket.DeleteObjects([]string{objectName + "1", objectName + "2"},
  995. DeleteObjectsQuiet(true))
  996. c.Assert(err, IsNil)
  997. c.Assert(len(res.DeletedObjects), Equals, 0)
  998. lor, err = s.bucket.ListObjects(Prefix(objectName))
  999. c.Assert(err, IsNil)
  1000. c.Assert(len(lor.Objects), Equals, 0)
  1001. // EncodingType
  1002. err = s.bucket.PutObject("中国人", strings.NewReader(""))
  1003. c.Assert(err, IsNil)
  1004. res, err = s.bucket.DeleteObjects([]string{"中国人"})
  1005. c.Assert(err, IsNil)
  1006. c.Assert(len(res.DeletedObjects), Equals, 1)
  1007. c.Assert(res.DeletedObjects[0], Equals, "中国人")
  1008. // EncodingType
  1009. err = s.bucket.PutObject("中国人", strings.NewReader(""))
  1010. c.Assert(err, IsNil)
  1011. res, err = s.bucket.DeleteObjects([]string{"中国人"}, DeleteObjectsQuiet(false))
  1012. c.Assert(err, IsNil)
  1013. c.Assert(len(res.DeletedObjects), Equals, 1)
  1014. c.Assert(res.DeletedObjects[0], Equals, "中国人")
  1015. // EncodingType
  1016. err = s.bucket.PutObject("中国人", strings.NewReader(""))
  1017. c.Assert(err, IsNil)
  1018. res, err = s.bucket.DeleteObjects([]string{"中国人"}, DeleteObjectsQuiet(true))
  1019. c.Assert(err, IsNil)
  1020. c.Assert(len(res.DeletedObjects), Equals, 0)
  1021. // Special characters
  1022. key := "A ' < > \" & ~ ` ! @ # $ % ^ & * ( ) [] {} - _ + = / | \\ ? . , : ; A"
  1023. err = s.bucket.PutObject(key, strings.NewReader("value"))
  1024. c.Assert(err, IsNil)
  1025. _, err = s.bucket.DeleteObjects([]string{key})
  1026. c.Assert(err, IsNil)
  1027. ress, err := s.bucket.ListObjects(Prefix(key))
  1028. c.Assert(err, IsNil)
  1029. c.Assert(len(ress.Objects), Equals, 0)
  1030. // Not exist
  1031. _, err = s.bucket.DeleteObjects([]string{"NotExistObject"})
  1032. c.Assert(err, IsNil)
  1033. }
  1034. // TestSetObjectMeta
  1035. func (s *OssBucketSuite) TestSetObjectMeta(c *C) {
  1036. objectName := objectNamePrefix + randStr(8)
  1037. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  1038. c.Assert(err, IsNil)
  1039. err = s.bucket.SetObjectMeta(objectName,
  1040. Expires(futureDate),
  1041. Meta("myprop", "mypropval"))
  1042. c.Assert(err, IsNil)
  1043. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  1044. c.Assert(err, IsNil)
  1045. testLogger.Println("Meta:", meta)
  1046. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  1047. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  1048. acl, err := s.bucket.GetObjectACL(objectName)
  1049. c.Assert(err, IsNil)
  1050. c.Assert(acl.ACL, Equals, "default")
  1051. // Invalid option
  1052. err = s.bucket.SetObjectMeta(objectName, AcceptEncoding("url"))
  1053. c.Assert(err, IsNil)
  1054. // Invalid option value
  1055. err = s.bucket.SetObjectMeta(objectName, ServerSideEncryption("invalid"))
  1056. c.Assert(err, NotNil)
  1057. err = s.bucket.DeleteObject(objectName)
  1058. c.Assert(err, IsNil)
  1059. // Not exist
  1060. err = s.bucket.SetObjectMeta(objectName, Expires(futureDate))
  1061. c.Assert(err, NotNil)
  1062. }
  1063. // TestGetObjectMeta
  1064. func (s *OssBucketSuite) TestGetObjectMeta(c *C) {
  1065. objectName := objectNamePrefix + randStr(8)
  1066. // Put
  1067. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  1068. c.Assert(err, IsNil)
  1069. meta, err := s.bucket.GetObjectMeta(objectName)
  1070. c.Assert(err, IsNil)
  1071. c.Assert(len(meta) > 0, Equals, true)
  1072. err = s.bucket.DeleteObject(objectName)
  1073. c.Assert(err, IsNil)
  1074. _, err = s.bucket.GetObjectMeta("NotExistObject")
  1075. c.Assert(err, NotNil)
  1076. }
  1077. // TestGetObjectDetailedMeta
  1078. func (s *OssBucketSuite) TestGetObjectDetailedMeta(c *C) {
  1079. objectName := objectNamePrefix + randStr(8)
  1080. // Put
  1081. err := s.bucket.PutObject(objectName, strings.NewReader(""),
  1082. Expires(futureDate), Meta("myprop", "mypropval"))
  1083. c.Assert(err, IsNil)
  1084. // Check
  1085. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  1086. c.Assert(err, IsNil)
  1087. testLogger.Println("GetObjectDetailedMeta:", meta)
  1088. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  1089. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  1090. c.Assert(meta.Get("Content-Length"), Equals, "0")
  1091. c.Assert(len(meta.Get("Date")) > 0, Equals, true)
  1092. c.Assert(len(meta.Get("X-Oss-Request-Id")) > 0, Equals, true)
  1093. c.Assert(len(meta.Get("Last-Modified")) > 0, Equals, true)
  1094. // IfModifiedSince/IfModifiedSince
  1095. _, err = s.bucket.GetObjectDetailedMeta(objectName, IfModifiedSince(futureDate))
  1096. c.Assert(err, NotNil)
  1097. meta, err = s.bucket.GetObjectDetailedMeta(objectName, IfUnmodifiedSince(futureDate))
  1098. c.Assert(err, IsNil)
  1099. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  1100. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  1101. // IfMatch/IfNoneMatch
  1102. _, err = s.bucket.GetObjectDetailedMeta(objectName, IfNoneMatch(meta.Get("Etag")))
  1103. c.Assert(err, NotNil)
  1104. meta, err = s.bucket.GetObjectDetailedMeta(objectName, IfMatch(meta.Get("Etag")))
  1105. c.Assert(err, IsNil)
  1106. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  1107. c.Assert(meta.Get("X-Oss-Meta-Myprop"), Equals, "mypropval")
  1108. err = s.bucket.DeleteObject(objectName)
  1109. c.Assert(err, IsNil)
  1110. _, err = s.bucket.GetObjectDetailedMeta("NotExistObject")
  1111. c.Assert(err, NotNil)
  1112. }
  1113. // TestSetAndGetObjectAcl
  1114. func (s *OssBucketSuite) TestSetAndGetObjectAcl(c *C) {
  1115. objectName := objectNamePrefix + randStr(8)
  1116. err := s.bucket.PutObject(objectName, strings.NewReader(""))
  1117. c.Assert(err, IsNil)
  1118. // Default
  1119. acl, err := s.bucket.GetObjectACL(objectName)
  1120. c.Assert(err, IsNil)
  1121. c.Assert(acl.ACL, Equals, "default")
  1122. // Set ACL_PUBLIC_RW
  1123. err = s.bucket.SetObjectACL(objectName, ACLPublicReadWrite)
  1124. c.Assert(err, IsNil)
  1125. acl, err = s.bucket.GetObjectACL(objectName)
  1126. c.Assert(err, IsNil)
  1127. c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
  1128. // Set ACL_PRIVATE
  1129. err = s.bucket.SetObjectACL(objectName, ACLPrivate)
  1130. c.Assert(err, IsNil)
  1131. acl, err = s.bucket.GetObjectACL(objectName)
  1132. c.Assert(err, IsNil)
  1133. c.Assert(acl.ACL, Equals, string(ACLPrivate))
  1134. // Set ACL_PUBLIC_R
  1135. err = s.bucket.SetObjectACL(objectName, ACLPublicRead)
  1136. c.Assert(err, IsNil)
  1137. acl, err = s.bucket.GetObjectACL(objectName)
  1138. c.Assert(err, IsNil)
  1139. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  1140. err = s.bucket.DeleteObject(objectName)
  1141. c.Assert(err, IsNil)
  1142. }
  1143. // TestSetAndGetObjectAclNegative
  1144. func (s *OssBucketSuite) TestSetAndGetObjectAclNegative(c *C) {
  1145. objectName := objectNamePrefix + randStr(8)
  1146. // Object not exist
  1147. err := s.bucket.SetObjectACL(objectName, ACLPublicRead)
  1148. c.Assert(err, NotNil)
  1149. }
  1150. // TestCopyObject
  1151. func (s *OssBucketSuite) TestCopyObject(c *C) {
  1152. objectName := objectNamePrefix + randStr(8)
  1153. objectValue := "男儿何不带吴钩,收取关山五十州。请君暂上凌烟阁,若个书生万户侯?"
  1154. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue),
  1155. ACL(ACLPublicRead), Meta("my", "myprop"))
  1156. c.Assert(err, IsNil)
  1157. // Copy
  1158. var objectNameDest = objectName + "dest"
  1159. _, err = s.bucket.CopyObject(objectName, objectNameDest)
  1160. c.Assert(err, IsNil)
  1161. // Check
  1162. lor, err := s.bucket.ListObjects(Prefix(objectName))
  1163. c.Assert(err, IsNil)
  1164. testLogger.Println("objects:", lor.Objects)
  1165. c.Assert(len(lor.Objects), Equals, 2)
  1166. body, err := s.bucket.GetObject(objectName)
  1167. c.Assert(err, IsNil)
  1168. str, err := readBody(body)
  1169. c.Assert(err, IsNil)
  1170. c.Assert(str, Equals, objectValue)
  1171. err = s.bucket.DeleteObject(objectNameDest)
  1172. c.Assert(err, IsNil)
  1173. // Copy with constraints x-oss-copy-source-if-modified-since
  1174. _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfModifiedSince(futureDate))
  1175. c.Assert(err, NotNil)
  1176. testLogger.Println("CopyObject:", err)
  1177. // Copy with constraints x-oss-copy-source-if-unmodified-since
  1178. _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfUnmodifiedSince(futureDate))
  1179. c.Assert(err, IsNil)
  1180. // Check
  1181. lor, err = s.bucket.ListObjects(Prefix(objectName))
  1182. c.Assert(err, IsNil)
  1183. testLogger.Println("objects:", lor.Objects)
  1184. c.Assert(len(lor.Objects), Equals, 2)
  1185. body, err = s.bucket.GetObject(objectName)
  1186. c.Assert(err, IsNil)
  1187. str, err = readBody(body)
  1188. c.Assert(err, IsNil)
  1189. c.Assert(str, Equals, objectValue)
  1190. err = s.bucket.DeleteObject(objectNameDest)
  1191. c.Assert(err, IsNil)
  1192. // Copy with constraints x-oss-copy-source-if-match
  1193. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  1194. c.Assert(err, IsNil)
  1195. testLogger.Println("GetObjectDetailedMeta:", meta)
  1196. _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfMatch(meta.Get("Etag")))
  1197. c.Assert(err, IsNil)
  1198. // Check
  1199. body, err = s.bucket.GetObject(objectName)
  1200. c.Assert(err, IsNil)
  1201. str, err = readBody(body)
  1202. c.Assert(err, IsNil)
  1203. c.Assert(str, Equals, objectValue)
  1204. err = s.bucket.DeleteObject(objectNameDest)
  1205. c.Assert(err, IsNil)
  1206. // Copy with constraints x-oss-copy-source-if-none-match
  1207. _, err = s.bucket.CopyObject(objectName, objectNameDest, CopySourceIfNoneMatch(meta.Get("Etag")))
  1208. c.Assert(err, NotNil)
  1209. // Copy with constraints x-oss-metadata-directive
  1210. _, err = s.bucket.CopyObject(objectName, objectNameDest, Meta("my", "mydestprop"),
  1211. MetadataDirective(MetaCopy))
  1212. c.Assert(err, IsNil)
  1213. // Check
  1214. body, err = s.bucket.GetObject(objectName)
  1215. c.Assert(err, IsNil)
  1216. str, err = readBody(body)
  1217. c.Assert(err, IsNil)
  1218. c.Assert(str, Equals, objectValue)
  1219. destMeta, err := s.bucket.GetObjectDetailedMeta(objectNameDest)
  1220. c.Assert(err, IsNil)
  1221. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
  1222. acl, err := s.bucket.GetObjectACL(objectNameDest)
  1223. c.Assert(err, IsNil)
  1224. c.Assert(acl.ACL, Equals, "default")
  1225. err = s.bucket.DeleteObject(objectNameDest)
  1226. c.Assert(err, IsNil)
  1227. // Copy with constraints x-oss-metadata-directive and self defined dest object meta
  1228. options := []Option{
  1229. ObjectACL(ACLPublicReadWrite),
  1230. Meta("my", "mydestprop"),
  1231. MetadataDirective(MetaReplace),
  1232. }
  1233. _, err = s.bucket.CopyObject(objectName, objectNameDest, options...)
  1234. c.Assert(err, IsNil)
  1235. // Check
  1236. body, err = s.bucket.GetObject(objectName)
  1237. c.Assert(err, IsNil)
  1238. str, err = readBody(body)
  1239. c.Assert(err, IsNil)
  1240. c.Assert(str, Equals, objectValue)
  1241. destMeta, err = s.bucket.GetObjectDetailedMeta(objectNameDest)
  1242. c.Assert(err, IsNil)
  1243. c.Assert(destMeta.Get("X-Oss-Meta-My"), Equals, "mydestprop")
  1244. acl, err = s.bucket.GetObjectACL(objectNameDest)
  1245. c.Assert(err, IsNil)
  1246. c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
  1247. err = s.bucket.DeleteObject(objectNameDest)
  1248. c.Assert(err, IsNil)
  1249. err = s.bucket.DeleteObject(objectName)
  1250. c.Assert(err, IsNil)
  1251. }
  1252. // TestCopyObjectToOrFrom
  1253. func (s *OssBucketSuite) TestCopyObjectToOrFrom(c *C) {
  1254. objectName := objectNamePrefix + randStr(8)
  1255. objectValue := "男儿何不带吴钩,收取关山五十州。请君暂上凌烟阁,若个书生万户侯?"
  1256. destBucketName := bucketName + "-dest"
  1257. objectNameDest := objectName + "-dest"
  1258. err := s.client.CreateBucket(destBucketName)
  1259. c.Assert(err, IsNil)
  1260. destBucket, err := s.client.Bucket(destBucketName)
  1261. c.Assert(err, IsNil)
  1262. err = s.bucket.PutObject(objectName, strings.NewReader(objectValue))
  1263. c.Assert(err, IsNil)
  1264. // Copy from
  1265. _, err = destBucket.CopyObjectFrom(bucketName, objectName, objectNameDest)
  1266. c.Assert(err, IsNil)
  1267. // Check
  1268. body, err := destBucket.GetObject(objectNameDest)
  1269. c.Assert(err, IsNil)
  1270. str, err := readBody(body)
  1271. c.Assert(err, IsNil)
  1272. c.Assert(str, Equals, objectValue)
  1273. err = s.bucket.DeleteObject(objectName)
  1274. c.Assert(err, IsNil)
  1275. // Copy to
  1276. _, err = destBucket.CopyObjectTo(bucketName, objectName, objectNameDest)
  1277. c.Assert(err, IsNil)
  1278. // Check
  1279. body, err = s.bucket.GetObject(objectName)
  1280. c.Assert(err, IsNil)
  1281. str, err = readBody(body)
  1282. c.Assert(err, IsNil)
  1283. c.Assert(str, Equals, objectValue)
  1284. // Clean
  1285. err = destBucket.DeleteObject(objectNameDest)
  1286. c.Assert(err, IsNil)
  1287. err = s.bucket.DeleteObject(objectName)
  1288. c.Assert(err, IsNil)
  1289. err = s.client.DeleteBucket(destBucketName)
  1290. c.Assert(err, IsNil)
  1291. }
  1292. // TestCopyObjectToOrFromNegative
  1293. func (s *OssBucketSuite) TestCopyObjectToOrFromNegative(c *C) {
  1294. objectName := objectNamePrefix + randStr(8)
  1295. destBucket := bucketName + "-dest"
  1296. objectNameDest := objectName + "-dest"
  1297. // Object not exist
  1298. _, err := s.bucket.CopyObjectTo(bucketName, objectName, objectNameDest)
  1299. c.Assert(err, NotNil)
  1300. // Bucket not exist
  1301. _, err = s.bucket.CopyObjectFrom(destBucket, objectNameDest, objectName)
  1302. c.Assert(err, NotNil)
  1303. }
  1304. // TestAppendObject
  1305. func (s *OssBucketSuite) TestAppendObject(c *C) {
  1306. objectName := objectNamePrefix + randStr(8)
  1307. objectValue := "昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。"
  1308. var val = []byte(objectValue)
  1309. var localFile = randStr(8) + ".txt"
  1310. var nextPos int64
  1311. var midPos = 1 + rand.Intn(len(val)-1)
  1312. var err = createFileAndWrite(localFile+"1", val[0:midPos])
  1313. c.Assert(err, IsNil)
  1314. err = createFileAndWrite(localFile+"2", val[midPos:])
  1315. c.Assert(err, IsNil)
  1316. // String append
  1317. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,"), nextPos)
  1318. c.Assert(err, IsNil)
  1319. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("却道海棠依旧。知否?知否?应是绿肥红瘦。"), nextPos)
  1320. c.Assert(err, IsNil)
  1321. body, err := s.bucket.GetObject(objectName)
  1322. c.Assert(err, IsNil)
  1323. str, err := readBody(body)
  1324. c.Assert(err, IsNil)
  1325. c.Assert(str, Equals, objectValue)
  1326. err = s.bucket.DeleteObject(objectName)
  1327. c.Assert(err, IsNil)
  1328. // Byte append
  1329. nextPos = 0
  1330. nextPos, err = s.bucket.AppendObject(objectName, bytes.NewReader(val[0:midPos]), nextPos)
  1331. c.Assert(err, IsNil)
  1332. nextPos, err = s.bucket.AppendObject(objectName, bytes.NewReader(val[midPos:]), nextPos)
  1333. c.Assert(err, IsNil)
  1334. body, err = s.bucket.GetObject(objectName)
  1335. c.Assert(err, IsNil)
  1336. str, err = readBody(body)
  1337. c.Assert(err, IsNil)
  1338. c.Assert(str, Equals, objectValue)
  1339. err = s.bucket.DeleteObject(objectName)
  1340. c.Assert(err, IsNil)
  1341. // File append
  1342. options := []Option{
  1343. ObjectACL(ACLPublicReadWrite),
  1344. Meta("my", "myprop"),
  1345. }
  1346. fd, err := os.Open(localFile + "1")
  1347. c.Assert(err, IsNil)
  1348. defer fd.Close()
  1349. nextPos = 0
  1350. nextPos, err = s.bucket.AppendObject(objectName, fd, nextPos, options...)
  1351. c.Assert(err, IsNil)
  1352. meta, err := s.bucket.GetObjectDetailedMeta(objectName)
  1353. c.Assert(err, IsNil)
  1354. testLogger.Println("GetObjectDetailedMeta:", meta, ",", nextPos)
  1355. c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Appendable")
  1356. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
  1357. c.Assert(meta.Get("x-oss-Meta-Mine"), Equals, "")
  1358. c.Assert(meta.Get("X-Oss-Next-Append-Position"), Equals, strconv.FormatInt(nextPos, 10))
  1359. acl, err := s.bucket.GetObjectACL(objectName)
  1360. c.Assert(err, IsNil)
  1361. testLogger.Println("GetObjectACL:", acl)
  1362. c.Assert(acl.ACL, Equals, string(ACLPublicReadWrite))
  1363. // Second append
  1364. options = []Option{
  1365. ObjectACL(ACLPublicRead),
  1366. Meta("my", "myproptwo"),
  1367. Meta("mine", "mypropmine"),
  1368. }
  1369. fd, err = os.Open(localFile + "2")
  1370. c.Assert(err, IsNil)
  1371. defer fd.Close()
  1372. nextPos, err = s.bucket.AppendObject(objectName, fd, nextPos, options...)
  1373. c.Assert(err, IsNil)
  1374. body, err = s.bucket.GetObject(objectName)
  1375. c.Assert(err, IsNil)
  1376. str, err = readBody(body)
  1377. c.Assert(err, IsNil)
  1378. c.Assert(str, Equals, objectValue)
  1379. meta, err = s.bucket.GetObjectDetailedMeta(objectName)
  1380. c.Assert(err, IsNil)
  1381. testLogger.Println("GetObjectDetailedMeta xxx:", meta)
  1382. c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Appendable")
  1383. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
  1384. c.Assert(meta.Get("x-Oss-Meta-Mine"), Equals, "")
  1385. c.Assert(meta.Get("X-Oss-Next-Append-Position"), Equals, strconv.FormatInt(nextPos, 10))
  1386. acl, err = s.bucket.GetObjectACL(objectName)
  1387. c.Assert(err, IsNil)
  1388. c.Assert(acl.ACL, Equals, string(ACLPublicRead))
  1389. err = s.bucket.DeleteObject(objectName)
  1390. c.Assert(err, IsNil)
  1391. }
  1392. // TestAppendObjectNegative
  1393. func (s *OssBucketSuite) TestAppendObjectNegative(c *C) {
  1394. objectName := objectNamePrefix + randStr(8)
  1395. nextPos := int64(0)
  1396. nextPos, err := s.bucket.AppendObject(objectName, strings.NewReader("ObjectValue"), nextPos)
  1397. c.Assert(err, IsNil)
  1398. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader("ObjectValue"), 0)
  1399. c.Assert(err, NotNil)
  1400. err = s.bucket.DeleteObject(objectName)
  1401. c.Assert(err, IsNil)
  1402. }
  1403. // TestContentType
  1404. func (s *OssBucketSuite) TestAddContentType(c *C) {
  1405. opts := addContentType(nil, "abc.txt")
  1406. typ, err := findOption(opts, HTTPHeaderContentType, "")
  1407. c.Assert(err, IsNil)
  1408. c.Assert(typ, Equals, "text/plain; charset=utf-8")
  1409. opts = addContentType(nil)
  1410. typ, err = findOption(opts, HTTPHeaderContentType, "")
  1411. c.Assert(err, IsNil)
  1412. c.Assert(len(opts), Equals, 1)
  1413. c.Assert(typ, Equals, "application/octet-stream")
  1414. opts = addContentType(nil, "abc.txt", "abc.pdf")
  1415. typ, err = findOption(opts, HTTPHeaderContentType, "")
  1416. c.Assert(err, IsNil)
  1417. c.Assert(typ, Equals, "text/plain; charset=utf-8")
  1418. opts = addContentType(nil, "abc", "abc.txt", "abc.pdf")
  1419. typ, err = findOption(opts, HTTPHeaderContentType, "")
  1420. c.Assert(err, IsNil)
  1421. c.Assert(typ, Equals, "text/plain; charset=utf-8")
  1422. opts = addContentType(nil, "abc", "abc", "edf")
  1423. typ, err = findOption(opts, HTTPHeaderContentType, "")
  1424. c.Assert(err, IsNil)
  1425. c.Assert(typ, Equals, "application/octet-stream")
  1426. opts = addContentType([]Option{Meta("meta", "my")}, "abc", "abc.txt", "abc.pdf")
  1427. typ, err = findOption(opts, HTTPHeaderContentType, "")
  1428. c.Assert(err, IsNil)
  1429. c.Assert(len(opts), Equals, 2)
  1430. c.Assert(typ, Equals, "text/plain; charset=utf-8")
  1431. }
  1432. func (s *OssBucketSuite) TestGetConfig(c *C) {
  1433. client, err := New(endpoint, accessID, accessKey, UseCname(true),
  1434. Timeout(11, 12), SecurityToken("token"), EnableMD5(false))
  1435. c.Assert(err, IsNil)
  1436. bucket, err := client.Bucket(bucketName)
  1437. c.Assert(err, IsNil)
  1438. c.Assert(bucket.getConfig().HTTPTimeout.ConnectTimeout, Equals, time.Second*11)
  1439. c.Assert(bucket.getConfig().HTTPTimeout.ReadWriteTimeout, Equals, time.Second*12)
  1440. c.Assert(bucket.getConfig().HTTPTimeout.HeaderTimeout, Equals, time.Second*12)
  1441. c.Assert(bucket.getConfig().HTTPTimeout.IdleConnTimeout, Equals, time.Second*12)
  1442. c.Assert(bucket.getConfig().HTTPTimeout.LongTimeout, Equals, time.Second*12*10)
  1443. c.Assert(bucket.getConfig().SecurityToken, Equals, "token")
  1444. c.Assert(bucket.getConfig().IsCname, Equals, true)
  1445. c.Assert(bucket.getConfig().IsEnableMD5, Equals, false)
  1446. }
  1447. func (s *OssBucketSuite) TestSTSToken(c *C) {
  1448. objectName := objectNamePrefix + randStr(8)
  1449. objectValue := "红藕香残玉簟秋。轻解罗裳,独上兰舟。云中谁寄锦书来?雁字回时,月满西楼。"
  1450. stsClient := sts.NewClient(stsaccessID, stsaccessKey, stsARN, "oss_test_sess")
  1451. resp, err := stsClient.AssumeRole(1800)
  1452. c.Assert(err, IsNil)
  1453. client, err := New(endpoint, resp.Credentials.AccessKeyId, resp.Credentials.AccessKeySecret,
  1454. SecurityToken(resp.Credentials.SecurityToken))
  1455. c.Assert(err, IsNil)
  1456. bucket, err := client.Bucket(bucketName)
  1457. c.Assert(err, IsNil)
  1458. // Put
  1459. err = bucket.PutObject(objectName, strings.NewReader(objectValue))
  1460. c.Assert(err, IsNil)
  1461. // Get
  1462. body, err := bucket.GetObject(objectName)
  1463. c.Assert(err, IsNil)
  1464. str, err := readBody(body)
  1465. c.Assert(err, IsNil)
  1466. c.Assert(str, Equals, objectValue)
  1467. // List
  1468. lor, err := bucket.ListObjects()
  1469. c.Assert(err, IsNil)
  1470. testLogger.Println("Objects:", lor.Objects)
  1471. // Put with URL
  1472. signedURL, err := bucket.SignURL(objectName, HTTPPut, 3600)
  1473. c.Assert(err, IsNil)
  1474. err = bucket.PutObjectWithURL(signedURL, strings.NewReader(objectValue))
  1475. c.Assert(err, IsNil)
  1476. // Get with URL
  1477. signedURL, err = bucket.SignURL(objectName, HTTPGet, 3600)
  1478. c.Assert(err, IsNil)
  1479. body, err = bucket.GetObjectWithURL(signedURL)
  1480. c.Assert(err, IsNil)
  1481. str, err = readBody(body)
  1482. c.Assert(err, IsNil)
  1483. c.Assert(str, Equals, objectValue)
  1484. // Delete
  1485. err = bucket.DeleteObject(objectName)
  1486. c.Assert(err, IsNil)
  1487. }
  1488. func (s *OssBucketSuite) TestSTSTonekNegative(c *C) {
  1489. objectName := objectNamePrefix + randStr(8)
  1490. localFile := objectName + ".jpg"
  1491. client, err := New(endpoint, accessID, accessKey, SecurityToken("Invalid"))
  1492. c.Assert(err, IsNil)
  1493. _, err = client.ListBuckets()
  1494. c.Assert(err, NotNil)
  1495. bucket, err := client.Bucket(bucketName)
  1496. c.Assert(err, IsNil)
  1497. err = bucket.PutObject(objectName, strings.NewReader(""))
  1498. c.Assert(err, NotNil)
  1499. err = bucket.PutObjectFromFile(objectName, "")
  1500. c.Assert(err, NotNil)
  1501. _, err = bucket.GetObject(objectName)
  1502. c.Assert(err, NotNil)
  1503. err = bucket.GetObjectToFile(objectName, "")
  1504. c.Assert(err, NotNil)
  1505. _, err = bucket.ListObjects()
  1506. c.Assert(err, NotNil)
  1507. err = bucket.SetObjectACL(objectName, ACLPublicRead)
  1508. c.Assert(err, NotNil)
  1509. _, err = bucket.GetObjectACL(objectName)
  1510. c.Assert(err, NotNil)
  1511. err = bucket.UploadFile(objectName, localFile, MinPartSize)
  1512. c.Assert(err, NotNil)
  1513. err = bucket.DownloadFile(objectName, localFile, MinPartSize)
  1514. c.Assert(err, NotNil)
  1515. _, err = bucket.IsObjectExist(objectName)
  1516. c.Assert(err, NotNil)
  1517. _, err = bucket.ListMultipartUploads()
  1518. c.Assert(err, NotNil)
  1519. err = bucket.DeleteObject(objectName)
  1520. c.Assert(err, NotNil)
  1521. _, err = bucket.DeleteObjects([]string{objectName})
  1522. c.Assert(err, NotNil)
  1523. err = client.DeleteBucket(bucketName)
  1524. c.Assert(err, NotNil)
  1525. }
  1526. func (s *OssBucketSuite) TestUploadBigFile(c *C) {
  1527. objectName := objectNamePrefix + randStr(8)
  1528. bigFile := "D:\\tmp\\bigfile.zip"
  1529. newFile := "D:\\tmp\\newbigfile.zip"
  1530. exist, err := isFileExist(bigFile)
  1531. c.Assert(err, IsNil)
  1532. if !exist {
  1533. return
  1534. }
  1535. // Put
  1536. start := GetNowSec()
  1537. err = s.bucket.PutObjectFromFile(objectName, bigFile)
  1538. c.Assert(err, IsNil)
  1539. end := GetNowSec()
  1540. testLogger.Println("Put big file:", bigFile, "use sec:", end-start)
  1541. // Check
  1542. start = GetNowSec()
  1543. err = s.bucket.GetObjectToFile(objectName, newFile)
  1544. c.Assert(err, IsNil)
  1545. end = GetNowSec()
  1546. testLogger.Println("Get big file:", bigFile, "use sec:", end-start)
  1547. start = GetNowSec()
  1548. eq, err := compareFiles(bigFile, newFile)
  1549. c.Assert(err, IsNil)
  1550. c.Assert(eq, Equals, true)
  1551. end = GetNowSec()
  1552. testLogger.Println("Compare big file:", bigFile, "use sec:", end-start)
  1553. err = s.bucket.DeleteObject(objectName)
  1554. c.Assert(err, IsNil)
  1555. }
  1556. func (s *OssBucketSuite) TestSymlink(c *C) {
  1557. objectName := objectNamePrefix + randStr(8)
  1558. targetObjectName := objectName + "target"
  1559. err := s.bucket.DeleteObject(objectName)
  1560. c.Assert(err, IsNil)
  1561. err = s.bucket.DeleteObject(targetObjectName)
  1562. c.Assert(err, IsNil)
  1563. meta, err := s.bucket.GetSymlink(objectName)
  1564. c.Assert(err, NotNil)
  1565. // Put symlink
  1566. err = s.bucket.PutSymlink(objectName, targetObjectName)
  1567. c.Assert(err, IsNil)
  1568. err = s.bucket.PutObject(targetObjectName, strings.NewReader("target"))
  1569. c.Assert(err, IsNil)
  1570. err = s.bucket.PutSymlink(objectName, targetObjectName)
  1571. c.Assert(err, IsNil)
  1572. meta, err = s.bucket.GetSymlink(objectName)
  1573. c.Assert(err, IsNil)
  1574. c.Assert(meta.Get(HTTPHeaderOssSymlinkTarget), Equals, targetObjectName)
  1575. // List object
  1576. lor, err := s.bucket.ListObjects()
  1577. c.Assert(err, IsNil)
  1578. exist, v := s.getObject(lor.Objects, objectName)
  1579. c.Assert(exist, Equals, true)
  1580. c.Assert(v.Type, Equals, "Symlink")
  1581. body, err := s.bucket.GetObject(objectName)
  1582. c.Assert(err, IsNil)
  1583. str, err := readBody(body)
  1584. c.Assert(err, IsNil)
  1585. c.Assert(str, Equals, "target")
  1586. meta, err = s.bucket.GetSymlink(targetObjectName)
  1587. c.Assert(err, NotNil)
  1588. err = s.bucket.PutObject(objectName, strings.NewReader("src"))
  1589. c.Assert(err, IsNil)
  1590. body, err = s.bucket.GetObject(objectName)
  1591. c.Assert(err, IsNil)
  1592. str, err = readBody(body)
  1593. c.Assert(err, IsNil)
  1594. c.Assert(str, Equals, "src")
  1595. err = s.bucket.DeleteObject(objectName)
  1596. c.Assert(err, IsNil)
  1597. err = s.bucket.DeleteObject(targetObjectName)
  1598. c.Assert(err, IsNil)
  1599. // Put symlink again
  1600. objectName = objectNamePrefix + randStr(8)
  1601. targetObjectName = objectName + "-target"
  1602. err = s.bucket.PutSymlink(objectName, targetObjectName)
  1603. c.Assert(err, IsNil)
  1604. err = s.bucket.PutObject(targetObjectName, strings.NewReader("target1"))
  1605. c.Assert(err, IsNil)
  1606. meta, err = s.bucket.GetSymlink(objectName)
  1607. c.Assert(err, IsNil)
  1608. c.Assert(meta.Get(HTTPHeaderOssSymlinkTarget), Equals, targetObjectName)
  1609. body, err = s.bucket.GetObject(objectName)
  1610. c.Assert(err, IsNil)
  1611. str, err = readBody(body)
  1612. c.Assert(err, IsNil)
  1613. c.Assert(str, Equals, "target1")
  1614. err = s.bucket.DeleteObject(objectName)
  1615. c.Assert(err, IsNil)
  1616. err = s.bucket.DeleteObject(targetObjectName)
  1617. c.Assert(err, IsNil)
  1618. }
  1619. // TestRestoreObject
  1620. func (s *OssBucketSuite) TestRestoreObject(c *C) {
  1621. objectName := objectNamePrefix + randStr(8)
  1622. // List objects
  1623. lor, err := s.archiveBucket.ListObjects()
  1624. c.Assert(err, IsNil)
  1625. left := len(lor.Objects)
  1626. // Put object
  1627. err = s.archiveBucket.PutObject(objectName, strings.NewReader(""))
  1628. c.Assert(err, IsNil)
  1629. // List
  1630. lor, err = s.archiveBucket.ListObjects()
  1631. c.Assert(err, IsNil)
  1632. c.Assert(len(lor.Objects), Equals, left+1)
  1633. for _, object := range lor.Objects {
  1634. c.Assert(object.StorageClass, Equals, string(StorageArchive))
  1635. c.Assert(object.Type, Equals, "Normal")
  1636. }
  1637. // Head object
  1638. meta, err := s.archiveBucket.GetObjectDetailedMeta(objectName)
  1639. c.Assert(err, IsNil)
  1640. _, ok := meta["X-Oss-Restore"]
  1641. c.Assert(ok, Equals, false)
  1642. c.Assert(meta.Get("X-Oss-Storage-Class"), Equals, "Archive")
  1643. // Error restore object
  1644. err = s.archiveBucket.RestoreObject("notexistobject")
  1645. c.Assert(err, NotNil)
  1646. // Restore object
  1647. err = s.archiveBucket.RestoreObject(objectName)
  1648. c.Assert(err, IsNil)
  1649. // Head object
  1650. meta, err = s.archiveBucket.GetObjectDetailedMeta(objectName)
  1651. c.Assert(err, IsNil)
  1652. c.Assert(meta.Get("X-Oss-Restore"), Equals, "ongoing-request=\"true\"")
  1653. c.Assert(meta.Get("X-Oss-Storage-Class"), Equals, "Archive")
  1654. }
  1655. // TestProcessObject
  1656. func (s *OssBucketSuite) TestProcessObject(c *C) {
  1657. objectName := objectNamePrefix + randStr(8) + ".jpg"
  1658. err := s.bucket.PutObjectFromFile(objectName, "../sample/BingWallpaper-2015-11-07.jpg")
  1659. c.Assert(err, IsNil)
  1660. // If bucket-name not specified, it is saved to the current bucket by default.
  1661. destObjName := objectNamePrefix + randStr(8) + "-dest.jpg"
  1662. process := fmt.Sprintf("image/resize,w_100|sys/saveas,o_%v", base64.URLEncoding.EncodeToString([]byte(destObjName)))
  1663. result, err := s.bucket.ProcessObject(objectName, process)
  1664. c.Assert(err, IsNil)
  1665. exist, _ := s.bucket.IsObjectExist(destObjName)
  1666. c.Assert(exist, Equals, true)
  1667. c.Assert(result.Bucket, Equals, "")
  1668. c.Assert(result.Object, Equals, destObjName)
  1669. destObjName = objectNamePrefix + randStr(8) + "-dest.jpg"
  1670. process = fmt.Sprintf("image/resize,w_100|sys/saveas,o_%v,b_%v", base64.URLEncoding.EncodeToString([]byte(destObjName)), base64.URLEncoding.EncodeToString([]byte(s.bucket.BucketName)))
  1671. result, err = s.bucket.ProcessObject(objectName, process)
  1672. c.Assert(err, IsNil)
  1673. exist, _ = s.bucket.IsObjectExist(destObjName)
  1674. c.Assert(exist, Equals, true)
  1675. c.Assert(result.Bucket, Equals, s.bucket.BucketName)
  1676. c.Assert(result.Object, Equals, destObjName)
  1677. //no support process
  1678. process = fmt.Sprintf("image/resize,w_100|saveas,o_%v,b_%v", base64.URLEncoding.EncodeToString([]byte(destObjName)), base64.URLEncoding.EncodeToString([]byte(s.bucket.BucketName)))
  1679. result, err = s.bucket.ProcessObject(objectName, process)
  1680. c.Assert(err, NotNil)
  1681. }
  1682. // Private
  1683. func createFileAndWrite(fileName string, data []byte) error {
  1684. os.Remove(fileName)
  1685. fo, err := os.Create(fileName)
  1686. if err != nil {
  1687. return err
  1688. }
  1689. defer fo.Close()
  1690. bytes, err := fo.Write(data)
  1691. if err != nil {
  1692. return err
  1693. }
  1694. if bytes != len(data) {
  1695. return fmt.Errorf(fmt.Sprintf("write %d bytes not equal data length %d", bytes, len(data)))
  1696. }
  1697. return nil
  1698. }
  1699. // Compare the content between fileL and fileR
  1700. func compareFiles(fileL string, fileR string) (bool, error) {
  1701. finL, err := os.Open(fileL)
  1702. if err != nil {
  1703. return false, err
  1704. }
  1705. defer finL.Close()
  1706. finR, err := os.Open(fileR)
  1707. if err != nil {
  1708. return false, err
  1709. }
  1710. defer finR.Close()
  1711. statL, err := finL.Stat()
  1712. if err != nil {
  1713. return false, err
  1714. }
  1715. statR, err := finR.Stat()
  1716. if err != nil {
  1717. return false, err
  1718. }
  1719. if statL.Size() != statR.Size() {
  1720. return false, nil
  1721. }
  1722. size := statL.Size()
  1723. if size > 102400 {
  1724. size = 102400
  1725. }
  1726. bufL := make([]byte, size)
  1727. bufR := make([]byte, size)
  1728. for {
  1729. n, _ := finL.Read(bufL)
  1730. if 0 == n {
  1731. break
  1732. }
  1733. n, _ = finR.Read(bufR)
  1734. if 0 == n {
  1735. break
  1736. }
  1737. if !bytes.Equal(bufL, bufR) {
  1738. return false, nil
  1739. }
  1740. }
  1741. return true, nil
  1742. }
  1743. // Compare the content of file and data
  1744. func compareFileData(file string, data []byte) (bool, error) {
  1745. fin, err := os.Open(file)
  1746. if err != nil {
  1747. return false, err
  1748. }
  1749. defer fin.Close()
  1750. stat, err := fin.Stat()
  1751. if err != nil {
  1752. return false, err
  1753. }
  1754. if stat.Size() != (int64)(len(data)) {
  1755. return false, nil
  1756. }
  1757. buf := make([]byte, stat.Size())
  1758. n, err := fin.Read(buf)
  1759. if err != nil {
  1760. return false, err
  1761. }
  1762. if stat.Size() != (int64)(n) {
  1763. return false, errors.New("read error")
  1764. }
  1765. if !bytes.Equal(buf, data) {
  1766. return false, nil
  1767. }
  1768. return true, nil
  1769. }
  1770. func walkDir(dirPth, suffix string) ([]string, error) {
  1771. var files = []string{}
  1772. suffix = strings.ToUpper(suffix)
  1773. err := filepath.Walk(dirPth,
  1774. func(filename string, fi os.FileInfo, err error) error {
  1775. if err != nil {
  1776. return err
  1777. }
  1778. if fi.IsDir() {
  1779. return nil
  1780. }
  1781. if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
  1782. files = append(files, filename)
  1783. }
  1784. return nil
  1785. })
  1786. return files, err
  1787. }
  1788. func removeTempFiles(path string, prefix string) error {
  1789. files, err := walkDir(path, prefix)
  1790. if err != nil {
  1791. return nil
  1792. }
  1793. for _, file := range files {
  1794. os.Remove(file)
  1795. }
  1796. return nil
  1797. }
  1798. func isFileExist(filename string) (bool, error) {
  1799. _, err := os.Stat(filename)
  1800. if err != nil && os.IsNotExist(err) {
  1801. return false, nil
  1802. } else if err != nil {
  1803. return false, err
  1804. } else {
  1805. return true, nil
  1806. }
  1807. }
  1808. func readBody(body io.ReadCloser) (string, error) {
  1809. data, err := ioutil.ReadAll(body)
  1810. body.Close()
  1811. if err != nil {
  1812. return "", err
  1813. }
  1814. return string(data), nil
  1815. }
  1816. func (s *OssBucketSuite) getObject(objects []ObjectProperties, object string) (bool, ObjectProperties) {
  1817. for _, v := range objects {
  1818. if v.Key == object {
  1819. return true, v
  1820. }
  1821. }
  1822. return false, ObjectProperties{}
  1823. }
  1824. func (s *OssBucketSuite) detectUploadSpeed(bucket *Bucket, c *C) (upSpeed int) {
  1825. objectName := objectNamePrefix + randStr(8)
  1826. // 1M byte
  1827. textBuffer := randStr(1024 * 1024)
  1828. // Put string
  1829. startT := time.Now()
  1830. err := bucket.PutObject(objectName, strings.NewReader(textBuffer))
  1831. endT := time.Now()
  1832. c.Assert(err, IsNil)
  1833. err = bucket.DeleteObject(objectName)
  1834. c.Assert(err, IsNil)
  1835. // byte/s
  1836. upSpeed = len(textBuffer) * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  1837. return upSpeed
  1838. }
  1839. func (s *OssBucketSuite) TestPutSingleObjectLimitSpeed(c *C) {
  1840. // create client and bucket
  1841. client, err := New(endpoint, accessID, accessKey)
  1842. c.Assert(err, IsNil)
  1843. err = client.LimitUploadSpeed(1)
  1844. if err != nil {
  1845. // go version is less than go1.7,not support limit upload speed
  1846. // doesn't run this test
  1847. return
  1848. }
  1849. // set unlimited again
  1850. client.LimitUploadSpeed(0)
  1851. bucketName := bucketNamePrefix + randLowStr(6)
  1852. err = client.CreateBucket(bucketName)
  1853. c.Assert(err, IsNil)
  1854. bucket, err := client.Bucket(bucketName)
  1855. c.Assert(err, IsNil)
  1856. //detect speed:byte/s
  1857. detectSpeed := s.detectUploadSpeed(bucket, c)
  1858. var limitSpeed = 0
  1859. if detectSpeed <= perTokenBandwidthSize*2 {
  1860. limitSpeed = perTokenBandwidthSize
  1861. } else {
  1862. //this situation, the test works better
  1863. limitSpeed = detectSpeed / 2
  1864. }
  1865. // KB/s
  1866. err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
  1867. c.Assert(err, IsNil)
  1868. objectName := objectNamePrefix + randStr(8)
  1869. // 1M byte
  1870. textBuffer := randStr(1024 * 1024)
  1871. // Put body
  1872. startT := time.Now()
  1873. err = bucket.PutObject(objectName, strings.NewReader(textBuffer))
  1874. endT := time.Now()
  1875. realSpeed := int64(len(textBuffer)) * 1000 / (endT.UnixNano()/1000/1000 - startT.UnixNano()/1000/1000)
  1876. fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
  1877. c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
  1878. if detectSpeed > perTokenBandwidthSize {
  1879. // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
  1880. c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
  1881. }
  1882. // Get object and compare content
  1883. body, err := bucket.GetObject(objectName)
  1884. c.Assert(err, IsNil)
  1885. str, err := readBody(body)
  1886. c.Assert(err, IsNil)
  1887. c.Assert(str, Equals, textBuffer)
  1888. bucket.DeleteObject(objectName)
  1889. client.DeleteBucket(bucketName)
  1890. c.Assert(err, IsNil)
  1891. return
  1892. }
  1893. func putObjectRoutin(bucket *Bucket, object string, textBuffer *string, notifyChan chan int) error {
  1894. err := bucket.PutObject(object, strings.NewReader(*textBuffer))
  1895. if err == nil {
  1896. notifyChan <- 1
  1897. } else {
  1898. notifyChan <- 0
  1899. }
  1900. return err
  1901. }
  1902. func (s *OssBucketSuite) TestPutManyObjectLimitSpeed(c *C) {
  1903. // create client and bucket
  1904. client, err := New(endpoint, accessID, accessKey)
  1905. c.Assert(err, IsNil)
  1906. err = client.LimitUploadSpeed(1)
  1907. if err != nil {
  1908. // go version is less than go1.7,not support limit upload speed
  1909. // doesn't run this test
  1910. return
  1911. }
  1912. // set unlimited
  1913. client.LimitUploadSpeed(0)
  1914. bucketName := bucketNamePrefix + randLowStr(6)
  1915. err = client.CreateBucket(bucketName)
  1916. c.Assert(err, IsNil)
  1917. bucket, err := client.Bucket(bucketName)
  1918. c.Assert(err, IsNil)
  1919. //detect speed:byte/s
  1920. detectSpeed := s.detectUploadSpeed(bucket, c)
  1921. var limitSpeed = 0
  1922. if detectSpeed <= perTokenBandwidthSize*2 {
  1923. limitSpeed = perTokenBandwidthSize
  1924. } else {
  1925. limitSpeed = detectSpeed / 2
  1926. }
  1927. // KB/s
  1928. err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
  1929. c.Assert(err, IsNil)
  1930. // object1
  1931. objectNameFirst := objectNamePrefix + randStr(8)
  1932. objectNameSecond := objectNamePrefix + randStr(8)
  1933. // 1M byte
  1934. textBuffer := randStr(1024 * 1024)
  1935. objectCount := 2
  1936. notifyChan := make(chan int, objectCount)
  1937. //start routin
  1938. startT := time.Now()
  1939. go putObjectRoutin(bucket, objectNameFirst, &textBuffer, notifyChan)
  1940. go putObjectRoutin(bucket, objectNameSecond, &textBuffer, notifyChan)
  1941. // wait routin end
  1942. sum := int(0)
  1943. for j := 0; j < objectCount; j++ {
  1944. result := <-notifyChan
  1945. sum += result
  1946. }
  1947. endT := time.Now()
  1948. realSpeed := len(textBuffer) * 2 * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  1949. c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
  1950. if detectSpeed > perTokenBandwidthSize {
  1951. // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
  1952. c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
  1953. }
  1954. c.Assert(sum, Equals, 2)
  1955. // Get object and compare content
  1956. body, err := bucket.GetObject(objectNameFirst)
  1957. c.Assert(err, IsNil)
  1958. str, err := readBody(body)
  1959. c.Assert(err, IsNil)
  1960. c.Assert(str, Equals, textBuffer)
  1961. body, err = bucket.GetObject(objectNameSecond)
  1962. c.Assert(err, IsNil)
  1963. str, err = readBody(body)
  1964. c.Assert(err, IsNil)
  1965. c.Assert(str, Equals, textBuffer)
  1966. // clear bucket and object
  1967. bucket.DeleteObject(objectNameFirst)
  1968. bucket.DeleteObject(objectNameSecond)
  1969. client.DeleteBucket(bucketName)
  1970. fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
  1971. return
  1972. }
  1973. func (s *OssBucketSuite) TestPutMultipartObjectLimitSpeed(c *C) {
  1974. // create client and bucket
  1975. client, err := New(endpoint, accessID, accessKey)
  1976. c.Assert(err, IsNil)
  1977. err = client.LimitUploadSpeed(1)
  1978. if err != nil {
  1979. // go version is less than go1.7,not support limit upload speed
  1980. // doesn't run this test
  1981. return
  1982. }
  1983. // set unlimited
  1984. client.LimitUploadSpeed(0)
  1985. bucketName := bucketNamePrefix + randLowStr(6)
  1986. err = client.CreateBucket(bucketName)
  1987. c.Assert(err, IsNil)
  1988. bucket, err := client.Bucket(bucketName)
  1989. c.Assert(err, IsNil)
  1990. //detect speed:byte/s
  1991. detectSpeed := s.detectUploadSpeed(bucket, c)
  1992. var limitSpeed = 0
  1993. if detectSpeed <= perTokenBandwidthSize*2 {
  1994. limitSpeed = perTokenBandwidthSize
  1995. } else {
  1996. //this situation, the test works better
  1997. limitSpeed = detectSpeed / 2
  1998. }
  1999. // KB/s
  2000. err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
  2001. c.Assert(err, IsNil)
  2002. objectName := objectNamePrefix + randStr(8)
  2003. fileName := "." + string(os.PathSeparator) + objectName
  2004. // 1M byte
  2005. fileSize := 0
  2006. textBuffer := randStr(1024 * 1024)
  2007. if detectSpeed < perTokenBandwidthSize {
  2008. ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
  2009. f, err := os.Stat(fileName)
  2010. c.Assert(err, IsNil)
  2011. fileSize = int(f.Size())
  2012. c.Assert(fileSize, Equals, len(textBuffer))
  2013. } else {
  2014. loopCount := 5
  2015. f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
  2016. c.Assert(err, IsNil)
  2017. for i := 0; i < loopCount; i++ {
  2018. f.Write([]byte(textBuffer))
  2019. }
  2020. fileInfo, err := f.Stat()
  2021. c.Assert(err, IsNil)
  2022. fileSize = int(fileInfo.Size())
  2023. c.Assert(fileSize, Equals, len(textBuffer)*loopCount)
  2024. f.Close()
  2025. }
  2026. // Put body
  2027. startT := time.Now()
  2028. err = bucket.UploadFile(objectName, fileName, 100*1024, Routines(3), Checkpoint(true, ""))
  2029. endT := time.Now()
  2030. c.Assert(err, IsNil)
  2031. realSpeed := fileSize * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  2032. c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
  2033. if detectSpeed > perTokenBandwidthSize {
  2034. // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
  2035. c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
  2036. }
  2037. // Get object and compare content
  2038. body, err := bucket.GetObject(objectName)
  2039. c.Assert(err, IsNil)
  2040. str, err := readBody(body)
  2041. c.Assert(err, IsNil)
  2042. fileBody, err := ioutil.ReadFile(fileName)
  2043. c.Assert(err, IsNil)
  2044. c.Assert(str, Equals, string(fileBody))
  2045. // delete bucket、object、file
  2046. bucket.DeleteObject(objectName)
  2047. client.DeleteBucket(bucketName)
  2048. os.Remove(fileName)
  2049. fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
  2050. return
  2051. }
  2052. func (s *OssBucketSuite) TestPutObjectFromFileLimitSpeed(c *C) {
  2053. // create client and bucket
  2054. client, err := New(endpoint, accessID, accessKey)
  2055. c.Assert(err, IsNil)
  2056. err = client.LimitUploadSpeed(1)
  2057. if err != nil {
  2058. // go version is less than go1.7,not support limit upload speed
  2059. // doesn't run this test
  2060. return
  2061. }
  2062. // set unlimited
  2063. client.LimitUploadSpeed(0)
  2064. bucketName := bucketNamePrefix + randLowStr(6)
  2065. err = client.CreateBucket(bucketName)
  2066. c.Assert(err, IsNil)
  2067. bucket, err := client.Bucket(bucketName)
  2068. c.Assert(err, IsNil)
  2069. //detect speed:byte/s
  2070. detectSpeed := s.detectUploadSpeed(bucket, c)
  2071. var limitSpeed = 0
  2072. if detectSpeed <= perTokenBandwidthSize*2 {
  2073. limitSpeed = perTokenBandwidthSize
  2074. } else {
  2075. //this situation, the test works better
  2076. limitSpeed = detectSpeed / 2
  2077. }
  2078. // KB/s
  2079. err = client.LimitUploadSpeed(limitSpeed / perTokenBandwidthSize)
  2080. c.Assert(err, IsNil)
  2081. objectName := objectNamePrefix + randStr(8)
  2082. fileName := "." + string(os.PathSeparator) + objectName
  2083. // 1M byte
  2084. fileSize := 0
  2085. textBuffer := randStr(1024 * 1024)
  2086. if detectSpeed < perTokenBandwidthSize {
  2087. ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
  2088. f, err := os.Stat(fileName)
  2089. c.Assert(err, IsNil)
  2090. fileSize = int(f.Size())
  2091. c.Assert(fileSize, Equals, len(textBuffer))
  2092. } else {
  2093. loopCount := 2
  2094. f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
  2095. c.Assert(err, IsNil)
  2096. for i := 0; i < loopCount; i++ {
  2097. f.Write([]byte(textBuffer))
  2098. }
  2099. fileInfo, err := f.Stat()
  2100. c.Assert(err, IsNil)
  2101. fileSize = int(fileInfo.Size())
  2102. c.Assert(fileSize, Equals, len(textBuffer)*loopCount)
  2103. f.Close()
  2104. }
  2105. // Put body
  2106. startT := time.Now()
  2107. err = bucket.PutObjectFromFile(objectName, fileName)
  2108. endT := time.Now()
  2109. c.Assert(err, IsNil)
  2110. realSpeed := fileSize * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  2111. c.Assert(float64(realSpeed) < float64(limitSpeed)*1.1, Equals, true)
  2112. if detectSpeed > perTokenBandwidthSize {
  2113. // the minimum uploas limit speed is perTokenBandwidthSize(1024 byte/s)
  2114. c.Assert(float64(realSpeed) > float64(limitSpeed)*0.9, Equals, true)
  2115. }
  2116. // Get object and compare content
  2117. body, err := bucket.GetObject(objectName)
  2118. c.Assert(err, IsNil)
  2119. str, err := readBody(body)
  2120. c.Assert(err, IsNil)
  2121. fileBody, err := ioutil.ReadFile(fileName)
  2122. c.Assert(err, IsNil)
  2123. c.Assert(str, Equals, string(fileBody))
  2124. // delete bucket、file、object
  2125. bucket.DeleteObject(objectName)
  2126. client.DeleteBucket(bucketName)
  2127. os.Remove(fileName)
  2128. fmt.Printf("detect speed:%d,limit speed:%d,real speed:%d.\n", detectSpeed, limitSpeed, realSpeed)
  2129. return
  2130. }
  2131. // upload speed limit parameters will not affect download speed
  2132. func (s *OssBucketSuite) TestUploadObjectLimitSpeed(c *C) {
  2133. // create limit client and bucket
  2134. client, err := New(endpoint, accessID, accessKey)
  2135. c.Assert(err, IsNil)
  2136. tokenCount := 1
  2137. err = client.LimitUploadSpeed(tokenCount)
  2138. if err != nil {
  2139. // go version is less than go1.7,not support limit upload speed
  2140. // doesn't run this test
  2141. return
  2142. }
  2143. // set unlimited
  2144. client.LimitUploadSpeed(0)
  2145. bucketName := bucketNamePrefix + randLowStr(6)
  2146. err = client.CreateBucket(bucketName)
  2147. c.Assert(err, IsNil)
  2148. bucket, err := client.Bucket(bucketName)
  2149. c.Assert(err, IsNil)
  2150. //first:upload a object
  2151. textBuffer := randStr(1024 * 100)
  2152. objectName := objectNamePrefix + randStr(8)
  2153. err = bucket.PutObject(objectName, strings.NewReader(textBuffer))
  2154. c.Assert(err, IsNil)
  2155. // limit upload speed
  2156. err = client.LimitUploadSpeed(tokenCount)
  2157. c.Assert(err, IsNil)
  2158. // then download the object
  2159. startT := time.Now()
  2160. body, err := bucket.GetObject(objectName)
  2161. c.Assert(err, IsNil)
  2162. str, err := readBody(body)
  2163. c.Assert(err, IsNil)
  2164. endT := time.Now()
  2165. c.Assert(str, Equals, textBuffer)
  2166. // byte/s
  2167. downloadSpeed := len(textBuffer) * 1000 / int(endT.UnixNano()/1000/1000-startT.UnixNano()/1000/1000)
  2168. // upload speed limit parameters will not affect download speed
  2169. c.Assert(downloadSpeed > 2*tokenCount*perTokenBandwidthSize, Equals, true)
  2170. bucket.DeleteObject(objectName)
  2171. client.DeleteBucket(bucketName)
  2172. }
  2173. // test LimitUploadSpeed failure
  2174. func (s *OssBucketSuite) TestLimitUploadSpeedFail(c *C) {
  2175. // create limit client and bucket
  2176. client, err := New(endpoint, accessID, accessKey)
  2177. c.Assert(err, IsNil)
  2178. err = client.LimitUploadSpeed(-1)
  2179. c.Assert(err, NotNil)
  2180. client.Config = nil
  2181. err = client.LimitUploadSpeed(100)
  2182. c.Assert(err, NotNil)
  2183. }
  2184. // upload webp object
  2185. func (s *OssBucketSuite) TestUploadObjectWithWebpFormat(c *C) {
  2186. client, err := New(endpoint, accessID, accessKey)
  2187. c.Assert(err, IsNil)
  2188. bucketName := bucketNamePrefix + randLowStr(6)
  2189. err = client.CreateBucket(bucketName)
  2190. c.Assert(err, IsNil)
  2191. bucket, err := client.Bucket(bucketName)
  2192. c.Assert(err, IsNil)
  2193. // create webp file
  2194. textBuffer := randStr(1024)
  2195. objectName := objectNamePrefix + randStr(8)
  2196. fileName := "." + string(os.PathSeparator) + objectName + ".webp"
  2197. ioutil.WriteFile(fileName, []byte(textBuffer), 0644)
  2198. _, err = os.Stat(fileName)
  2199. c.Assert(err, IsNil)
  2200. err = bucket.PutObjectFromFile(objectName, fileName)
  2201. c.Assert(err, IsNil)
  2202. // check object content-type
  2203. props, err := bucket.GetObjectDetailedMeta(objectName)
  2204. c.Assert(err, IsNil)
  2205. c.Assert(props["Content-Type"][0], Equals, "image/webp")
  2206. os.Remove(fileName)
  2207. bucket.DeleteObject(objectName)
  2208. client.DeleteBucket(bucketName)
  2209. }
  2210. func (s *OssBucketSuite) TestPutObjectTagging(c *C) {
  2211. // put object with tagging
  2212. objectName := objectNamePrefix + randStr(8)
  2213. tag1 := Tag{
  2214. Key: randStr(8),
  2215. Value: randStr(16),
  2216. }
  2217. tag2 := Tag{
  2218. Key: randStr(8),
  2219. Value: randStr(16),
  2220. }
  2221. tagging := Tagging{
  2222. Tags: []Tag{tag1, tag2},
  2223. }
  2224. err := s.bucket.PutObject(objectName, strings.NewReader(randStr(1024)), SetTagging(tagging))
  2225. c.Assert(err, IsNil)
  2226. headers, err := s.bucket.GetObjectDetailedMeta(objectName)
  2227. taggingCount, err := strconv.Atoi(headers["X-Oss-Tagging-Count"][0])
  2228. c.Assert(err, IsNil)
  2229. c.Assert(taggingCount, Equals, 2)
  2230. // copy object with default option
  2231. destObjectName := objectNamePrefix + randStr(8)
  2232. _, err = s.bucket.CopyObject(objectName, destObjectName)
  2233. c.Assert(err, IsNil)
  2234. headers, err = s.bucket.GetObjectDetailedMeta(destObjectName)
  2235. taggingCount, err = strconv.Atoi(headers["X-Oss-Tagging-Count"][0])
  2236. c.Assert(err, IsNil)
  2237. c.Assert(taggingCount, Equals, 2)
  2238. // delete object tagging
  2239. err = s.bucket.DeleteObjectTagging(objectName)
  2240. c.Assert(err, IsNil)
  2241. // get object tagging again
  2242. taggingResult, err := s.bucket.GetObjectTagging(objectName)
  2243. c.Assert(err, IsNil)
  2244. c.Assert(len(taggingResult.Tags), Equals, 0)
  2245. // put tagging
  2246. tag := Tag{
  2247. Key: randStr(8),
  2248. Value: randStr(16),
  2249. }
  2250. tagging.Tags = []Tag{tag}
  2251. err = s.bucket.PutObjectTagging(objectName, tagging)
  2252. c.Assert(err, IsNil)
  2253. taggingResult, err = s.bucket.GetObjectTagging(objectName)
  2254. c.Assert(len(taggingResult.Tags), Equals, 1)
  2255. c.Assert(taggingResult.Tags[0].Key, Equals, tag.Key)
  2256. c.Assert(taggingResult.Tags[0].Value, Equals, tag.Value)
  2257. //put tagging, the length of the key exceeds 128
  2258. tag = Tag{
  2259. Key: randStr(129),
  2260. Value: randStr(16),
  2261. }
  2262. tagging.Tags = []Tag{tag}
  2263. err = s.bucket.PutObjectTagging(objectName, tagging)
  2264. c.Assert(err, NotNil)
  2265. //put tagging, the length of the value exceeds 256
  2266. tag = Tag{
  2267. Key: randStr(8),
  2268. Value: randStr(257),
  2269. }
  2270. tagging.Tags = []Tag{tag}
  2271. err = s.bucket.PutObjectTagging(objectName, tagging)
  2272. c.Assert(err, NotNil)
  2273. //put tagging, the lens of tags exceed 10
  2274. tagging.Tags = []Tag{}
  2275. for i := 0; i < 11; i++ {
  2276. tag = Tag{
  2277. Key: randStr(8),
  2278. Value: randStr(16),
  2279. }
  2280. tagging.Tags = append(tagging.Tags, tag)
  2281. }
  2282. err = s.bucket.PutObjectTagging(objectName, tagging)
  2283. c.Assert(err, NotNil)
  2284. //put tagging, invalid value of tag key
  2285. tag = Tag{
  2286. Key: randStr(8) + "&",
  2287. Value: randStr(16),
  2288. }
  2289. tagging.Tags = []Tag{tag}
  2290. err = s.bucket.PutObjectTagging(objectName, tagging)
  2291. c.Assert(err, NotNil)
  2292. //put tagging, invalid value of tag value
  2293. tag = Tag{
  2294. Key: randStr(8),
  2295. Value: randStr(16) + "&",
  2296. }
  2297. tagging.Tags = []Tag{tag}
  2298. err = s.bucket.PutObjectTagging(objectName, tagging)
  2299. c.Assert(err, NotNil)
  2300. //put tagging, repeated tag keys
  2301. tag1 = Tag{
  2302. Key: randStr(8),
  2303. Value: randStr(16),
  2304. }
  2305. tag2 = Tag{
  2306. Key: tag1.Key,
  2307. Value: randStr(16),
  2308. }
  2309. tagging.Tags = []Tag{tag1, tag2}
  2310. err = s.bucket.PutObjectTagging(objectName, tagging)
  2311. c.Assert(err, NotNil)
  2312. s.bucket.DeleteObject(destObjectName)
  2313. s.bucket.DeleteObject(objectName)
  2314. }
  2315. func (s *OssBucketSuite) TestGetObjectTagging(c *C) {
  2316. // get object which has 2 tags
  2317. objectName := objectNamePrefix + randStr(8)
  2318. tag1 := Tag{
  2319. Key: randStr(8),
  2320. Value: randStr(16),
  2321. }
  2322. tag2 := Tag{
  2323. Key: randStr(8),
  2324. Value: randStr(16),
  2325. }
  2326. taggingInfo := Tagging{
  2327. Tags: []Tag{tag1, tag2},
  2328. }
  2329. err := s.bucket.PutObject(objectName, strings.NewReader(randStr(1024)), SetTagging(taggingInfo))
  2330. c.Assert(err, IsNil)
  2331. tagging, err := s.bucket.GetObjectTagging(objectName)
  2332. c.Assert(len(tagging.Tags), Equals, 2)
  2333. if tagging.Tags[0].Key == tag1.Key {
  2334. c.Assert(tagging.Tags[0].Value, Equals, tag1.Value)
  2335. c.Assert(tagging.Tags[1].Key, Equals, tag2.Key)
  2336. c.Assert(tagging.Tags[1].Value, Equals, tag2.Value)
  2337. } else {
  2338. c.Assert(tagging.Tags[0].Key, Equals, tag2.Key)
  2339. c.Assert(tagging.Tags[0].Value, Equals, tag2.Value)
  2340. c.Assert(tagging.Tags[1].Key, Equals, tag1.Key)
  2341. c.Assert(tagging.Tags[1].Value, Equals, tag1.Value)
  2342. }
  2343. // get tagging of an object that is not exist
  2344. err = s.bucket.DeleteObject(objectName)
  2345. c.Assert(err, IsNil)
  2346. tagging, err = s.bucket.GetObjectTagging(objectName)
  2347. c.Assert(err, NotNil)
  2348. c.Assert(len(tagging.Tags), Equals, 0)
  2349. // get object which has no tag
  2350. objectName = objectNamePrefix + randStr(8)
  2351. err = s.bucket.PutObject(objectName, strings.NewReader(randStr(1024)))
  2352. c.Assert(err, IsNil)
  2353. tagging, err = s.bucket.GetObjectTagging(objectName)
  2354. c.Assert(err, IsNil)
  2355. c.Assert(len(tagging.Tags), Equals, 0)
  2356. // copy object, with tagging option
  2357. destObjectName := objectName + "-dest"
  2358. tagging.Tags = []Tag{tag1, tag2}
  2359. _, err = s.bucket.CopyObject(objectName, destObjectName, SetTagging(taggingInfo))
  2360. c.Assert(err, IsNil)
  2361. tagging, err = s.bucket.GetObjectTagging(objectName)
  2362. c.Assert(err, IsNil)
  2363. c.Assert(len(tagging.Tags), Equals, 0)
  2364. // copy object, with tagging option, the value of tagging directive is "REPLACE"
  2365. tagging.Tags = []Tag{tag1, tag2}
  2366. _, err = s.bucket.CopyObject(objectName, destObjectName, SetTagging(taggingInfo), TaggingDirective(TaggingReplace))
  2367. c.Assert(err, IsNil)
  2368. tagging, err = s.bucket.GetObjectTagging(destObjectName)
  2369. c.Assert(err, IsNil)
  2370. c.Assert(len(tagging.Tags), Equals, 2)
  2371. if tagging.Tags[0].Key == tag1.Key {
  2372. c.Assert(tagging.Tags[0].Value, Equals, tag1.Value)
  2373. c.Assert(tagging.Tags[1].Key, Equals, tag2.Key)
  2374. c.Assert(tagging.Tags[1].Value, Equals, tag2.Value)
  2375. } else {
  2376. c.Assert(tagging.Tags[0].Key, Equals, tag2.Key)
  2377. c.Assert(tagging.Tags[0].Value, Equals, tag2.Value)
  2378. c.Assert(tagging.Tags[1].Key, Equals, tag1.Key)
  2379. c.Assert(tagging.Tags[1].Value, Equals, tag1.Value)
  2380. }
  2381. s.bucket.DeleteObject(objectName)
  2382. s.bucket.DeleteObject(destObjectName)
  2383. }
  2384. func (s *OssBucketSuite) TestDeleteObjectTagging(c *C) {
  2385. // delete object tagging, the object is not exist
  2386. objectName := objectNamePrefix + randStr(8)
  2387. err := s.bucket.DeleteObjectTagging(objectName)
  2388. c.Assert(err, NotNil)
  2389. // delete object tagging
  2390. tag := Tag{
  2391. Key: randStr(8),
  2392. Value: randStr(16),
  2393. }
  2394. tagging := Tagging{
  2395. Tags: []Tag{tag},
  2396. }
  2397. err = s.bucket.PutObject(objectName, strings.NewReader(randStr(1024)), SetTagging(tagging))
  2398. c.Assert(err, IsNil)
  2399. err = s.bucket.DeleteObjectTagging(objectName)
  2400. c.Assert(err, IsNil)
  2401. taggingResult, err := s.bucket.GetObjectTagging(objectName)
  2402. c.Assert(err, IsNil)
  2403. c.Assert(len(taggingResult.Tags), Equals, 0)
  2404. //delete object tagging again
  2405. err = s.bucket.DeleteObjectTagging(objectName)
  2406. c.Assert(err, IsNil)
  2407. s.bucket.DeleteObject(objectName)
  2408. }