bucket_test.go 138 KB

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