bucket_test.go 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747
  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(strings.Contains(meta.Get("Content-Type"), "text/plain"), Equals, true)
  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, "/root1/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) TestUploadFileMimeShtml(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. bucket, err := client.Bucket(bucketName)
  2418. objectName := objectNamePrefix + randStr(8)
  2419. fileName := "oss-sdk-test-file-" + randLowStr(5) + ".shtml"
  2420. createFile(fileName, "123", c)
  2421. err = bucket.PutObjectFromFile(objectName, fileName)
  2422. c.Assert(err, IsNil)
  2423. headResult, err := bucket.GetObjectDetailedMeta(objectName)
  2424. c.Assert(err, IsNil)
  2425. c.Assert(headResult.Get("Content-Type"), Equals, "text/html")
  2426. os.Remove(fileName)
  2427. forceDeleteBucket(client, bucketName, c)
  2428. }
  2429. func (s *OssBucketSuite) TestVersioningPutAndGetObject(c *C) {
  2430. // create a bucket with default proprety
  2431. client, err := New(endpoint, accessID, accessKey)
  2432. c.Assert(err, IsNil)
  2433. bucketName := bucketNamePrefix + randLowStr(6)
  2434. err = client.CreateBucket(bucketName)
  2435. c.Assert(err, IsNil)
  2436. bucket, err := client.Bucket(bucketName)
  2437. // put bucket version:enabled
  2438. var versioningConfig VersioningConfig
  2439. versioningConfig.Status = string(VersionEnabled)
  2440. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2441. c.Assert(err, IsNil)
  2442. bucketResult, err := client.GetBucketInfo(bucketName)
  2443. c.Assert(err, IsNil)
  2444. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2445. // put object v1
  2446. objectName := objectNamePrefix + randStr(8)
  2447. contextV1 := randStr(100)
  2448. versionIdV1 := ""
  2449. var respHeader http.Header
  2450. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2451. c.Assert(err, IsNil)
  2452. versionIdV1 = GetVersionId(respHeader)
  2453. c.Assert(len(versionIdV1) > 0, Equals, true)
  2454. // put object v2
  2455. contextV2 := randStr(200)
  2456. versionIdV2 := ""
  2457. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2458. c.Assert(err, IsNil)
  2459. versionIdV2 = GetVersionId(respHeader)
  2460. c.Assert(len(versionIdV2) > 0, Equals, true)
  2461. // check v1 and v2
  2462. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2463. // get object v1
  2464. body, err := bucket.GetObject(objectName, VersionId(versionIdV1))
  2465. c.Assert(err, IsNil)
  2466. str, err := readBody(body)
  2467. c.Assert(err, IsNil)
  2468. body.Close()
  2469. c.Assert(str, Equals, contextV1)
  2470. // get object v2
  2471. body, err = bucket.GetObject(objectName, VersionId(versionIdV2))
  2472. c.Assert(err, IsNil)
  2473. str, err = readBody(body)
  2474. c.Assert(err, IsNil)
  2475. body.Close()
  2476. c.Assert(str, Equals, contextV2)
  2477. // get object without version
  2478. body, err = bucket.GetObject(objectName)
  2479. c.Assert(err, IsNil)
  2480. str, err = readBody(body)
  2481. c.Assert(err, IsNil)
  2482. body.Close()
  2483. c.Assert(str, Equals, contextV2)
  2484. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2485. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2486. forceDeleteBucket(client, bucketName, c)
  2487. }
  2488. func (s *OssBucketSuite) TestVersioningHeadObject(c *C) {
  2489. // create a bucket with default proprety
  2490. client, err := New(endpoint, accessID, accessKey)
  2491. c.Assert(err, IsNil)
  2492. bucketName := bucketNamePrefix + randLowStr(6)
  2493. err = client.CreateBucket(bucketName)
  2494. c.Assert(err, IsNil)
  2495. bucket, err := client.Bucket(bucketName)
  2496. // put bucket version:enabled
  2497. var versioningConfig VersioningConfig
  2498. versioningConfig.Status = string(VersionEnabled)
  2499. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2500. c.Assert(err, IsNil)
  2501. bucketResult, err := client.GetBucketInfo(bucketName)
  2502. c.Assert(err, IsNil)
  2503. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2504. // put object v1
  2505. objectName := objectNamePrefix + randStr(8)
  2506. contextV1 := randStr(100)
  2507. versionIdV1 := ""
  2508. var respHeader http.Header
  2509. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2510. c.Assert(err, IsNil)
  2511. versionIdV1 = GetVersionId(respHeader)
  2512. c.Assert(len(versionIdV1) > 0, Equals, true)
  2513. // put object v2
  2514. contextV2 := randStr(200)
  2515. versionIdV2 := ""
  2516. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2517. c.Assert(err, IsNil)
  2518. versionIdV2 = GetVersionId(respHeader)
  2519. c.Assert(len(versionIdV2) > 0, Equals, true)
  2520. // check v1 and v2
  2521. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2522. // head object v1
  2523. headResultV1, err := bucket.GetObjectMeta(objectName, VersionId(versionIdV1))
  2524. objLen, err := strconv.Atoi(headResultV1.Get("Content-Length"))
  2525. c.Assert(objLen, Equals, len(contextV1))
  2526. headResultV1, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV1))
  2527. objLen, err = strconv.Atoi(headResultV1.Get("Content-Length"))
  2528. c.Assert(objLen, Equals, len(contextV1))
  2529. // head object v2
  2530. headResultV2, err := bucket.GetObjectMeta(objectName, VersionId(versionIdV2))
  2531. objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
  2532. c.Assert(objLen, Equals, len(contextV2))
  2533. headResultV2, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV2))
  2534. objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
  2535. c.Assert(objLen, Equals, len(contextV2))
  2536. // head object without version
  2537. // head object v2
  2538. headResult, err := bucket.GetObjectMeta(objectName)
  2539. objLen, err = strconv.Atoi(headResult.Get("Content-Length"))
  2540. c.Assert(objLen, Equals, len(contextV2))
  2541. headResult, err = bucket.GetObjectDetailedMeta(objectName)
  2542. objLen, err = strconv.Atoi(headResultV2.Get("Content-Length"))
  2543. c.Assert(objLen, Equals, len(contextV2))
  2544. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2545. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2546. forceDeleteBucket(client, bucketName, c)
  2547. }
  2548. func (s *OssBucketSuite) TestVersioningDeleteLatestVersionObject(c *C) {
  2549. // create a bucket with default proprety
  2550. client, err := New(endpoint, accessID, accessKey)
  2551. c.Assert(err, IsNil)
  2552. bucketName := bucketNamePrefix + randLowStr(6)
  2553. err = client.CreateBucket(bucketName)
  2554. c.Assert(err, IsNil)
  2555. bucket, err := client.Bucket(bucketName)
  2556. // put bucket version:enabled
  2557. var versioningConfig VersioningConfig
  2558. versioningConfig.Status = string(VersionEnabled)
  2559. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2560. c.Assert(err, IsNil)
  2561. bucketResult, err := client.GetBucketInfo(bucketName)
  2562. c.Assert(err, IsNil)
  2563. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2564. // put object v1
  2565. objectName := objectNamePrefix + randStr(8)
  2566. contextV1 := randStr(100)
  2567. versionIdV1 := ""
  2568. var respHeader http.Header
  2569. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2570. c.Assert(err, IsNil)
  2571. versionIdV1 = GetVersionId(respHeader)
  2572. c.Assert(len(versionIdV1) > 0, Equals, true)
  2573. // put object v2
  2574. contextV2 := randStr(200)
  2575. versionIdV2 := ""
  2576. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2577. c.Assert(err, IsNil)
  2578. versionIdV2 = GetVersionId(respHeader)
  2579. c.Assert(len(versionIdV2) > 0, Equals, true)
  2580. // check v1 and v2
  2581. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2582. // delete v2 object:permently delete
  2583. options := []Option{VersionId(versionIdV2), GetResponseHeader(&respHeader)}
  2584. err = bucket.DeleteObject(objectName, options...)
  2585. c.Assert(err, IsNil)
  2586. c.Assert(GetVersionId(respHeader), Equals, versionIdV2)
  2587. // get v2 object failure
  2588. body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
  2589. c.Assert(err, NotNil)
  2590. c.Assert(err.(ServiceError).Code, Equals, "NoSuchVersion")
  2591. // get v1 object success
  2592. body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
  2593. c.Assert(err, IsNil)
  2594. str, err := readBody(body)
  2595. body.Close()
  2596. c.Assert(err, IsNil)
  2597. c.Assert(str, Equals, contextV1)
  2598. // get default object success:v1
  2599. body, err = bucket.GetObject(objectName)
  2600. c.Assert(err, IsNil)
  2601. str, err = readBody(body)
  2602. body.Close()
  2603. c.Assert(err, IsNil)
  2604. c.Assert(str, Equals, contextV1)
  2605. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2606. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2607. forceDeleteBucket(client, bucketName, c)
  2608. }
  2609. func (s *OssBucketSuite) TestVersioningDeleteOldVersionObject(c *C) {
  2610. // create a bucket with default proprety
  2611. client, err := New(endpoint, accessID, accessKey)
  2612. c.Assert(err, IsNil)
  2613. bucketName := bucketNamePrefix + randLowStr(6)
  2614. err = client.CreateBucket(bucketName)
  2615. c.Assert(err, IsNil)
  2616. bucket, err := client.Bucket(bucketName)
  2617. // put bucket version:enabled
  2618. var versioningConfig VersioningConfig
  2619. versioningConfig.Status = string(VersionEnabled)
  2620. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2621. c.Assert(err, IsNil)
  2622. bucketResult, err := client.GetBucketInfo(bucketName)
  2623. c.Assert(err, IsNil)
  2624. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2625. // put object v1
  2626. objectName := objectNamePrefix + randStr(8)
  2627. contextV1 := randStr(100)
  2628. versionIdV1 := ""
  2629. var respHeader http.Header
  2630. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2631. c.Assert(err, IsNil)
  2632. versionIdV1 = GetVersionId(respHeader)
  2633. c.Assert(len(versionIdV1) > 0, Equals, true)
  2634. // put object v2
  2635. contextV2 := randStr(200)
  2636. versionIdV2 := ""
  2637. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2638. c.Assert(err, IsNil)
  2639. versionIdV2 = GetVersionId(respHeader)
  2640. c.Assert(len(versionIdV2) > 0, Equals, true)
  2641. // check v1 and v2
  2642. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2643. // delete v1 object:permently delete
  2644. options := []Option{VersionId(versionIdV1), GetResponseHeader(&respHeader)}
  2645. err = bucket.DeleteObject(objectName, options...)
  2646. c.Assert(err, IsNil)
  2647. c.Assert(GetVersionId(respHeader), Equals, versionIdV1)
  2648. // get v2 object success
  2649. body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
  2650. c.Assert(err, IsNil)
  2651. str, err := readBody(body)
  2652. body.Close()
  2653. c.Assert(err, IsNil)
  2654. c.Assert(str, Equals, contextV2)
  2655. // get v1 object faliure
  2656. body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
  2657. c.Assert(err, NotNil)
  2658. c.Assert(err.(ServiceError).Code, Equals, "NoSuchVersion")
  2659. // get default object success:v2
  2660. body, err = bucket.GetObject(objectName)
  2661. c.Assert(err, IsNil)
  2662. str, err = readBody(body)
  2663. body.Close()
  2664. c.Assert(err, IsNil)
  2665. c.Assert(str, Equals, contextV2)
  2666. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2667. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2668. forceDeleteBucket(client, bucketName, c)
  2669. }
  2670. func (s *OssBucketSuite) TestVersioningDeleteDefaultVersionObject(c *C) {
  2671. // create a bucket with default proprety
  2672. client, err := New(endpoint, accessID, accessKey)
  2673. c.Assert(err, IsNil)
  2674. bucketName := bucketNamePrefix + randLowStr(6)
  2675. err = client.CreateBucket(bucketName)
  2676. c.Assert(err, IsNil)
  2677. bucket, err := client.Bucket(bucketName)
  2678. // put bucket version:enabled
  2679. var versioningConfig VersioningConfig
  2680. versioningConfig.Status = string(VersionEnabled)
  2681. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2682. c.Assert(err, IsNil)
  2683. bucketResult, err := client.GetBucketInfo(bucketName)
  2684. c.Assert(err, IsNil)
  2685. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2686. // put object v1
  2687. objectName := objectNamePrefix + randStr(8)
  2688. contextV1 := randStr(100)
  2689. versionIdV1 := ""
  2690. var respHeader http.Header
  2691. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2692. c.Assert(err, IsNil)
  2693. versionIdV1 = GetVersionId(respHeader)
  2694. c.Assert(len(versionIdV1) > 0, Equals, true)
  2695. // put object v2
  2696. contextV2 := randStr(200)
  2697. versionIdV2 := ""
  2698. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2699. c.Assert(err, IsNil)
  2700. versionIdV2 = GetVersionId(respHeader)
  2701. c.Assert(len(versionIdV2) > 0, Equals, true)
  2702. // check v1 and v2
  2703. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2704. // delete default object:mark delete v2
  2705. options := []Option{GetResponseHeader(&respHeader)}
  2706. err = bucket.DeleteObject(objectName, options...)
  2707. c.Assert(err, IsNil)
  2708. markVersionId := GetVersionId(respHeader)
  2709. c.Assert(len(markVersionId) > 0, Equals, true)
  2710. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  2711. // get v2 object success
  2712. body, err := bucket.GetObject(objectName, VersionId(versionIdV2))
  2713. c.Assert(err, IsNil)
  2714. str, err := readBody(body)
  2715. body.Close()
  2716. c.Assert(err, IsNil)
  2717. c.Assert(str, Equals, contextV2)
  2718. // get v1 object success
  2719. body, err = bucket.GetObject(objectName, VersionId(versionIdV1))
  2720. c.Assert(err, IsNil)
  2721. str, err = readBody(body)
  2722. body.Close()
  2723. c.Assert(err, IsNil)
  2724. c.Assert(str, Equals, contextV1)
  2725. // get default object failure:marker v2
  2726. body, err = bucket.GetObject(objectName, GetResponseHeader(&respHeader))
  2727. c.Assert(err, NotNil)
  2728. c.Assert(err.(ServiceError).Code, Equals, "NoSuchKey")
  2729. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  2730. // delete mark v2
  2731. options = []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
  2732. err = bucket.DeleteObject(objectName, options...)
  2733. c.Assert(err, IsNil)
  2734. c.Assert(GetVersionId(respHeader), Equals, markVersionId)
  2735. // get default object success:v2
  2736. body, err = bucket.GetObject(objectName, VersionId(versionIdV2))
  2737. c.Assert(err, IsNil)
  2738. str, err = readBody(body)
  2739. body.Close()
  2740. c.Assert(err, IsNil)
  2741. c.Assert(str, Equals, contextV2)
  2742. err = bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2743. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2744. forceDeleteBucket(client, bucketName, c)
  2745. }
  2746. func (s *OssBucketSuite) TestVersioningListObjectVersions(c *C) {
  2747. // create a bucket with default proprety
  2748. client, err := New(endpoint, accessID, accessKey)
  2749. c.Assert(err, IsNil)
  2750. bucketName := bucketNamePrefix + randLowStr(6)
  2751. err = client.CreateBucket(bucketName)
  2752. c.Assert(err, IsNil)
  2753. bucket, err := client.Bucket(bucketName)
  2754. // put bucket version:enabled
  2755. var versioningConfig VersioningConfig
  2756. versioningConfig.Status = string(VersionEnabled)
  2757. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2758. c.Assert(err, IsNil)
  2759. bucketResult, err := client.GetBucketInfo(bucketName)
  2760. c.Assert(err, IsNil)
  2761. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2762. // put object v1
  2763. objectName := objectNamePrefix + randStr(8)
  2764. contextV1 := randStr(100)
  2765. versionIdV1 := ""
  2766. var respHeader http.Header
  2767. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2768. c.Assert(err, IsNil)
  2769. versionIdV1 = GetVersionId(respHeader)
  2770. c.Assert(len(versionIdV1) > 0, Equals, true)
  2771. // put object v2
  2772. contextV2 := randStr(200)
  2773. versionIdV2 := ""
  2774. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2775. c.Assert(err, IsNil)
  2776. versionIdV2 = GetVersionId(respHeader)
  2777. c.Assert(len(versionIdV2) > 0, Equals, true)
  2778. // check v1 and v2
  2779. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2780. // delete default object:mark delete v2
  2781. options := []Option{GetResponseHeader(&respHeader)}
  2782. err = bucket.DeleteObject(objectName, options...)
  2783. c.Assert(err, IsNil)
  2784. markVersionId := GetVersionId(respHeader)
  2785. c.Assert(len(markVersionId) > 0, Equals, true)
  2786. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  2787. // delete default object again:mark delete v2
  2788. err = bucket.DeleteObject(objectName, options...)
  2789. c.Assert(err, IsNil)
  2790. markVersionIdAgain := GetVersionId(respHeader)
  2791. c.Assert(len(markVersionIdAgain) > 0, Equals, true)
  2792. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  2793. c.Assert(markVersionId != markVersionIdAgain, Equals, true)
  2794. // list bucket versions
  2795. listResult, err := bucket.ListObjectVersions()
  2796. c.Assert(err, IsNil)
  2797. c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 2)
  2798. c.Assert(len(listResult.ObjectVersions), Equals, 2)
  2799. mapMarkVersion := map[string]string{}
  2800. mapMarkVersion[listResult.ObjectDeleteMarkers[0].VersionId] = listResult.ObjectDeleteMarkers[0].VersionId
  2801. mapMarkVersion[listResult.ObjectDeleteMarkers[1].VersionId] = listResult.ObjectDeleteMarkers[1].VersionId
  2802. // check delete mark
  2803. _, ok := mapMarkVersion[markVersionId]
  2804. c.Assert(ok == true, Equals, true)
  2805. _, ok = mapMarkVersion[markVersionIdAgain]
  2806. c.Assert(ok == true, Equals, true)
  2807. // check versionId
  2808. mapVersion := map[string]string{}
  2809. mapVersion[listResult.ObjectVersions[0].VersionId] = listResult.ObjectVersions[0].VersionId
  2810. mapVersion[listResult.ObjectVersions[1].VersionId] = listResult.ObjectVersions[1].VersionId
  2811. _, ok = mapVersion[versionIdV1]
  2812. c.Assert(ok == true, Equals, true)
  2813. _, ok = mapVersion[versionIdV2]
  2814. c.Assert(ok == true, Equals, true)
  2815. // delete deleteMark v2
  2816. options = []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
  2817. err = bucket.DeleteObject(objectName, options...)
  2818. c.Assert(err, IsNil)
  2819. c.Assert(GetVersionId(respHeader), Equals, markVersionId)
  2820. // delete deleteMark v2 again
  2821. options = []Option{VersionId(markVersionIdAgain), GetResponseHeader(&respHeader)}
  2822. err = bucket.DeleteObject(objectName, options...)
  2823. c.Assert(err, IsNil)
  2824. c.Assert(GetVersionId(respHeader), Equals, markVersionIdAgain)
  2825. // delete versionId
  2826. bucket.DeleteObject(objectName, VersionId(versionIdV1))
  2827. bucket.DeleteObject(objectName, VersionId(versionIdV2))
  2828. forceDeleteBucket(client, bucketName, c)
  2829. }
  2830. func (s *OssBucketSuite) TestVersioningBatchDeleteVersionObjects(c *C) {
  2831. // create a bucket with default proprety
  2832. client, err := New(endpoint, accessID, accessKey)
  2833. c.Assert(err, IsNil)
  2834. bucketName := bucketNamePrefix + randLowStr(6)
  2835. err = client.CreateBucket(bucketName)
  2836. c.Assert(err, IsNil)
  2837. bucket, err := client.Bucket(bucketName)
  2838. // put bucket version:enabled
  2839. var versioningConfig VersioningConfig
  2840. versioningConfig.Status = string(VersionEnabled)
  2841. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2842. c.Assert(err, IsNil)
  2843. bucketResult, err := client.GetBucketInfo(bucketName)
  2844. c.Assert(err, IsNil)
  2845. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2846. // put object v1
  2847. objectName1 := objectNamePrefix + randStr(8)
  2848. contextV1 := randStr(100)
  2849. versionIdV1 := ""
  2850. var respHeader http.Header
  2851. err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2852. c.Assert(err, IsNil)
  2853. versionIdV1 = GetVersionId(respHeader)
  2854. c.Assert(len(versionIdV1) > 0, Equals, true)
  2855. // put object v2
  2856. objectName2 := objectNamePrefix + randStr(8)
  2857. contextV2 := randStr(200)
  2858. versionIdV2 := ""
  2859. err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2860. c.Assert(err, IsNil)
  2861. versionIdV2 = GetVersionId(respHeader)
  2862. c.Assert(len(versionIdV2) > 0, Equals, true)
  2863. // check v1 and v2
  2864. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2865. //batch delete objects
  2866. versionIds := []DeleteObject{DeleteObject{Key: objectName1, VersionId: versionIdV1},
  2867. DeleteObject{Key: objectName2, VersionId: versionIdV2}}
  2868. deleteResult, err := bucket.DeleteObjectVersions(versionIds)
  2869. c.Assert(err, IsNil)
  2870. c.Assert(len(deleteResult.DeletedObjectsDetail), Equals, 2)
  2871. // check delete detail info:key
  2872. deleteMap := map[string]string{}
  2873. deleteMap[deleteResult.DeletedObjectsDetail[0].Key] = deleteResult.DeletedObjectsDetail[0].VersionId
  2874. deleteMap[deleteResult.DeletedObjectsDetail[1].Key] = deleteResult.DeletedObjectsDetail[1].VersionId
  2875. id1, ok := deleteMap[objectName1]
  2876. c.Assert(ok, Equals, true)
  2877. c.Assert(id1, Equals, versionIdV1)
  2878. id2, ok := deleteMap[objectName2]
  2879. c.Assert(ok, Equals, true)
  2880. c.Assert(id2, Equals, versionIdV2)
  2881. // list bucket versions
  2882. listResult, err := bucket.ListObjectVersions()
  2883. c.Assert(err, IsNil)
  2884. c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 0)
  2885. c.Assert(len(listResult.ObjectVersions), Equals, 0)
  2886. forceDeleteBucket(client, bucketName, c)
  2887. }
  2888. func (s *OssBucketSuite) TestVersioningBatchDeleteDefaultVersionObjects(c *C) {
  2889. // create a bucket with default proprety
  2890. client, err := New(endpoint, accessID, accessKey)
  2891. c.Assert(err, IsNil)
  2892. bucketName := bucketNamePrefix + randLowStr(6)
  2893. err = client.CreateBucket(bucketName)
  2894. c.Assert(err, IsNil)
  2895. bucket, err := client.Bucket(bucketName)
  2896. // put bucket version:enabled
  2897. var versioningConfig VersioningConfig
  2898. versioningConfig.Status = string(VersionEnabled)
  2899. err = client.SetBucketVersioning(bucketName, versioningConfig)
  2900. c.Assert(err, IsNil)
  2901. bucketResult, err := client.GetBucketInfo(bucketName)
  2902. c.Assert(err, IsNil)
  2903. c.Assert(bucketResult.BucketInfo.Versioning, Equals, string(VersionEnabled))
  2904. // put object v1
  2905. objectName1 := objectNamePrefix + randStr(8)
  2906. contextV1 := randStr(100)
  2907. versionIdV1 := ""
  2908. var respHeader http.Header
  2909. err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2910. c.Assert(err, IsNil)
  2911. versionIdV1 = GetVersionId(respHeader)
  2912. c.Assert(len(versionIdV1) > 0, Equals, true)
  2913. // put object v2
  2914. objectName2 := objectNamePrefix + randStr(8)
  2915. contextV2 := randStr(200)
  2916. versionIdV2 := ""
  2917. err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2918. c.Assert(err, IsNil)
  2919. versionIdV2 = GetVersionId(respHeader)
  2920. c.Assert(len(versionIdV2) > 0, Equals, true)
  2921. // check v1 and v2
  2922. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  2923. //batch delete objects
  2924. versionIds := []DeleteObject{DeleteObject{Key: objectName1, VersionId: ""},
  2925. DeleteObject{Key: objectName2, VersionId: ""}}
  2926. deleteResult, err := bucket.DeleteObjectVersions(versionIds)
  2927. c.Assert(err, IsNil)
  2928. // check delete detail info:key
  2929. deleteDetailMap := map[string]DeletedKeyInfo{}
  2930. deleteDetailMap[deleteResult.DeletedObjectsDetail[0].Key] = deleteResult.DeletedObjectsDetail[0]
  2931. deleteDetailMap[deleteResult.DeletedObjectsDetail[1].Key] = deleteResult.DeletedObjectsDetail[1]
  2932. keyInfo1, ok := deleteDetailMap[objectName1]
  2933. c.Assert(ok, Equals, true)
  2934. c.Assert(keyInfo1.Key, Equals, objectName1)
  2935. c.Assert(keyInfo1.VersionId, Equals, "")
  2936. c.Assert(keyInfo1.DeleteMarker, Equals, true)
  2937. c.Assert(keyInfo1.DeleteMarkerVersionId != versionIdV1, Equals, true)
  2938. keyInfo2, ok := deleteDetailMap[objectName2]
  2939. c.Assert(ok, Equals, true)
  2940. c.Assert(keyInfo2.Key, Equals, objectName2)
  2941. c.Assert(keyInfo2.VersionId, Equals, "")
  2942. c.Assert(keyInfo2.DeleteMarker, Equals, true)
  2943. c.Assert(keyInfo2.DeleteMarkerVersionId != versionIdV2, Equals, true)
  2944. // list bucket versions
  2945. listResult, err := bucket.ListObjectVersions()
  2946. c.Assert(err, IsNil)
  2947. c.Assert(len(listResult.ObjectDeleteMarkers), Equals, 2)
  2948. c.Assert(len(listResult.ObjectVersions), Equals, 2)
  2949. // delete version object
  2950. versionIds = []DeleteObject{DeleteObject{Key: objectName1, VersionId: versionIdV1},
  2951. DeleteObject{Key: objectName2, VersionId: versionIdV2}}
  2952. deleteResult, err = bucket.DeleteObjectVersions(versionIds)
  2953. c.Assert(err, IsNil)
  2954. // delete deleteMark object
  2955. versionIds = []DeleteObject{DeleteObject{Key: objectName1, VersionId: keyInfo1.DeleteMarkerVersionId},
  2956. DeleteObject{Key: objectName2, VersionId: keyInfo2.DeleteMarkerVersionId}}
  2957. deleteResult, err = bucket.DeleteObjectVersions(versionIds)
  2958. c.Assert(err, IsNil)
  2959. forceDeleteBucket(client, bucketName, c)
  2960. }
  2961. // bucket has no versioning flag
  2962. func (s *OssBucketSuite) TestVersioningBatchDeleteNormalObjects(c *C) {
  2963. // create a bucket with default proprety
  2964. client, err := New(endpoint, accessID, accessKey)
  2965. c.Assert(err, IsNil)
  2966. bucketName := bucketNamePrefix + randLowStr(6)
  2967. err = client.CreateBucket(bucketName)
  2968. c.Assert(err, IsNil)
  2969. // not put bucket versioning
  2970. bucket, err := client.Bucket(bucketName)
  2971. // put object v1
  2972. objectName1 := objectNamePrefix + randStr(8)
  2973. contextV1 := randStr(100)
  2974. versionIdV1 := ""
  2975. var respHeader http.Header
  2976. err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  2977. c.Assert(err, IsNil)
  2978. versionIdV1 = GetVersionId(respHeader)
  2979. c.Assert(len(versionIdV1), Equals, 0)
  2980. // put object v2
  2981. objectName2 := objectNamePrefix + randStr(8)
  2982. contextV2 := randStr(200)
  2983. versionIdV2 := ""
  2984. err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  2985. c.Assert(err, IsNil)
  2986. versionIdV2 = GetVersionId(respHeader)
  2987. c.Assert(len(versionIdV2), Equals, 0)
  2988. //batch delete objects
  2989. keys := []string{objectName1, objectName2}
  2990. deleteResult, err := bucket.DeleteObjects(keys)
  2991. c.Assert(len(deleteResult.DeletedObjects), Equals, 2)
  2992. // check delete info
  2993. deleteMap := map[string]string{}
  2994. deleteMap[deleteResult.DeletedObjects[0]] = deleteResult.DeletedObjects[0]
  2995. deleteMap[deleteResult.DeletedObjects[1]] = deleteResult.DeletedObjects[1]
  2996. _, ok := deleteMap[objectName1]
  2997. c.Assert(ok, Equals, true)
  2998. _, ok = deleteMap[objectName2]
  2999. c.Assert(ok, Equals, true)
  3000. forceDeleteBucket(client, bucketName, c)
  3001. c.Assert(err, IsNil)
  3002. }
  3003. func (s *OssBucketSuite) TestVersioningSymlink(c *C) {
  3004. // create a bucket with default proprety
  3005. client, err := New(endpoint, accessID, accessKey)
  3006. c.Assert(err, IsNil)
  3007. bucketName := bucketNamePrefix + randLowStr(6)
  3008. err = client.CreateBucket(bucketName)
  3009. c.Assert(err, IsNil)
  3010. bucket, err := client.Bucket(bucketName)
  3011. // put bucket version:enabled
  3012. var versioningConfig VersioningConfig
  3013. versioningConfig.Status = string(VersionEnabled)
  3014. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3015. c.Assert(err, IsNil)
  3016. // put object 1
  3017. objectName1 := objectNamePrefix + randStr(8)
  3018. contextV1 := randStr(100)
  3019. versionIdV1 := ""
  3020. var respHeader http.Header
  3021. err = bucket.PutObject(objectName1, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3022. c.Assert(err, IsNil)
  3023. versionIdV1 = GetVersionId(respHeader)
  3024. c.Assert(len(versionIdV1) > 0, Equals, true)
  3025. // put object 2
  3026. objectName2 := objectNamePrefix + randStr(8)
  3027. contextV2 := randStr(200)
  3028. versionIdV2 := ""
  3029. err = bucket.PutObject(objectName2, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3030. c.Assert(err, IsNil)
  3031. versionIdV2 = GetVersionId(respHeader)
  3032. c.Assert(len(versionIdV2) > 0, Equals, true)
  3033. // check v1 and v2
  3034. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3035. // put symlink for object 1
  3036. linkName := objectNamePrefix + randStr(8)
  3037. err = bucket.PutSymlink(linkName, objectName1, GetResponseHeader(&respHeader))
  3038. c.Assert(err, IsNil)
  3039. linkVersionIdV1 := GetVersionId(respHeader)
  3040. // PutSymlink for object 2
  3041. err = bucket.PutSymlink(linkName, objectName2, GetResponseHeader(&respHeader))
  3042. c.Assert(err, IsNil)
  3043. linkVersionIdV2 := GetVersionId(respHeader)
  3044. // check v1 and v2
  3045. c.Assert(linkVersionIdV1 != linkVersionIdV2, Equals, true)
  3046. // GetSymlink for object1
  3047. getResult, err := bucket.GetSymlink(linkName, VersionId(linkVersionIdV1))
  3048. c.Assert(err, IsNil)
  3049. c.Assert(getResult.Get("x-oss-symlink-target"), Equals, objectName1)
  3050. // GetSymlink for object2
  3051. getResult, err = bucket.GetSymlink(linkName, VersionId(linkVersionIdV2))
  3052. c.Assert(err, IsNil)
  3053. c.Assert(getResult.Get("x-oss-symlink-target"), Equals, objectName2)
  3054. bucket.DeleteObject(linkName)
  3055. bucket.DeleteObject(objectName1)
  3056. bucket.DeleteObject(objectName2)
  3057. forceDeleteBucket(client, bucketName, c)
  3058. }
  3059. func (s *OssBucketSuite) TestVersioningObjectAcl(c *C) {
  3060. // create a bucket with default proprety
  3061. client, err := New(endpoint, accessID, accessKey)
  3062. c.Assert(err, IsNil)
  3063. bucketName := bucketNamePrefix + randLowStr(6)
  3064. err = client.CreateBucket(bucketName)
  3065. c.Assert(err, IsNil)
  3066. bucket, err := client.Bucket(bucketName)
  3067. // put bucket version:enabled
  3068. var versioningConfig VersioningConfig
  3069. versioningConfig.Status = string(VersionEnabled)
  3070. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3071. c.Assert(err, IsNil)
  3072. // put object v1
  3073. objectName := objectNamePrefix + randStr(8)
  3074. contextV1 := randStr(100)
  3075. versionIdV1 := ""
  3076. var respHeader http.Header
  3077. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3078. c.Assert(err, IsNil)
  3079. versionIdV1 = GetVersionId(respHeader)
  3080. c.Assert(len(versionIdV1) > 0, Equals, true)
  3081. // put object v2
  3082. contextV2 := randStr(200)
  3083. versionIdV2 := ""
  3084. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3085. c.Assert(err, IsNil)
  3086. versionIdV2 = GetVersionId(respHeader)
  3087. c.Assert(len(versionIdV2) > 0, Equals, true)
  3088. // check v1 and v2
  3089. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3090. // put Acl for v1
  3091. err = bucket.SetObjectACL(objectName, ACLPublicRead, VersionId(versionIdV1))
  3092. c.Assert(err, IsNil)
  3093. // put Acl for v2
  3094. err = bucket.SetObjectACL(objectName, ACLPublicReadWrite, VersionId(versionIdV2))
  3095. c.Assert(err, IsNil)
  3096. // GetAcl for v1
  3097. getResult, err := bucket.GetObjectACL(objectName, VersionId(versionIdV1))
  3098. c.Assert(err, IsNil)
  3099. c.Assert(getResult.ACL, Equals, string(ACLPublicRead))
  3100. // GetAcl for v2
  3101. getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV2))
  3102. c.Assert(err, IsNil)
  3103. c.Assert(getResult.ACL, Equals, string(ACLPublicReadWrite))
  3104. // delete default version
  3105. err = bucket.DeleteObject(objectName, GetResponseHeader(&respHeader))
  3106. c.Assert(len(GetVersionId(respHeader)) > 0, Equals, true)
  3107. c.Assert(respHeader.Get("x-oss-delete-marker"), Equals, "true")
  3108. // GetAcl for v1 agagin
  3109. getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV1))
  3110. c.Assert(err, IsNil)
  3111. c.Assert(getResult.ACL, Equals, string(ACLPublicRead))
  3112. // GetAcl for v2 again
  3113. getResult, err = bucket.GetObjectACL(objectName, VersionId(versionIdV2))
  3114. c.Assert(err, IsNil)
  3115. c.Assert(getResult.ACL, Equals, string(ACLPublicReadWrite))
  3116. // GetAcl for default failure
  3117. getResult, err = bucket.GetObjectACL(objectName)
  3118. c.Assert(err, NotNil)
  3119. bucket.DeleteObject(objectName)
  3120. forceDeleteBucket(client, bucketName, c)
  3121. }
  3122. func (s *OssBucketSuite) TestVersioningAppendObject(c *C) {
  3123. // create a bucket with default proprety
  3124. client, err := New(endpoint, accessID, accessKey)
  3125. c.Assert(err, IsNil)
  3126. bucketName := bucketNamePrefix + randLowStr(6)
  3127. err = client.CreateBucket(bucketName)
  3128. c.Assert(err, IsNil)
  3129. bucket, err := client.Bucket(bucketName)
  3130. // put bucket version:enabled
  3131. var versioningConfig VersioningConfig
  3132. versioningConfig.Status = string(VersionEnabled)
  3133. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3134. c.Assert(err, IsNil)
  3135. // append object
  3136. var nextPos int64 = 0
  3137. var respHeader http.Header
  3138. objectName := objectNamePrefix + randStr(8)
  3139. nextPos, err = bucket.AppendObject(objectName, strings.NewReader("123"), nextPos, GetResponseHeader(&respHeader))
  3140. c.Assert(err, IsNil)
  3141. c.Assert(GetVersionId(respHeader), Equals, NullVersion)
  3142. nextPos, err = bucket.AppendObject(objectName, strings.NewReader("456"), nextPos, GetResponseHeader(&respHeader))
  3143. c.Assert(err, IsNil)
  3144. c.Assert(GetVersionId(respHeader), Equals, NullVersion)
  3145. // delete object
  3146. err = bucket.DeleteObject(objectName, GetResponseHeader(&respHeader))
  3147. markVersionId := GetVersionId(respHeader)
  3148. // get default object failure
  3149. _, err = bucket.GetObject(objectName)
  3150. c.Assert(err, NotNil)
  3151. // get null version success
  3152. body, err := bucket.GetObject(objectName, VersionId(NullVersion))
  3153. c.Assert(err, IsNil)
  3154. str, err := readBody(body)
  3155. c.Assert(err, IsNil)
  3156. c.Assert(str, Equals, "123456")
  3157. // append object again:failure
  3158. nextPos, err = bucket.AppendObject(objectName, strings.NewReader("789"), nextPos, GetResponseHeader(&respHeader))
  3159. c.Assert(err, NotNil)
  3160. // delete deletemark
  3161. options := []Option{VersionId(markVersionId), GetResponseHeader(&respHeader)}
  3162. err = bucket.DeleteObject(objectName, options...)
  3163. c.Assert(markVersionId, Equals, GetVersionId(respHeader))
  3164. // append object again:success
  3165. nextPos, err = bucket.AppendObject(objectName, strings.NewReader("789"), nextPos, GetResponseHeader(&respHeader))
  3166. c.Assert(err, IsNil)
  3167. c.Assert(int(nextPos), Equals, 9)
  3168. bucket.DeleteObject(objectName)
  3169. forceDeleteBucket(client, bucketName, c)
  3170. }
  3171. func (s *OssBucketSuite) TestVersioningCopyObject(c *C) {
  3172. // create a bucket with default proprety
  3173. client, err := New(endpoint, accessID, accessKey)
  3174. c.Assert(err, IsNil)
  3175. bucketName := bucketNamePrefix + randLowStr(6)
  3176. err = client.CreateBucket(bucketName)
  3177. c.Assert(err, IsNil)
  3178. bucket, err := client.Bucket(bucketName)
  3179. // put bucket version:enabled
  3180. var versioningConfig VersioningConfig
  3181. versioningConfig.Status = string(VersionEnabled)
  3182. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3183. c.Assert(err, IsNil)
  3184. // put object v1
  3185. objectName := objectNamePrefix + randStr(8)
  3186. contextV1 := randStr(100)
  3187. versionIdV1 := ""
  3188. var respHeader http.Header
  3189. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3190. c.Assert(err, IsNil)
  3191. versionIdV1 = GetVersionId(respHeader)
  3192. c.Assert(len(versionIdV1) > 0, Equals, true)
  3193. // put object v2
  3194. contextV2 := randStr(200)
  3195. versionIdV2 := ""
  3196. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3197. c.Assert(err, IsNil)
  3198. versionIdV2 = GetVersionId(respHeader)
  3199. c.Assert(len(versionIdV2) > 0, Equals, true)
  3200. // check v1 and v2
  3201. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3202. destObjectKey := objectNamePrefix + randStr(8)
  3203. // copyobject default
  3204. _, err = bucket.CopyObject(objectName, destObjectKey, GetResponseHeader(&respHeader))
  3205. c.Assert(err, IsNil)
  3206. srcVersionId := GetCopySrcVersionId(respHeader)
  3207. c.Assert(srcVersionId, Equals, versionIdV2)
  3208. body, err := bucket.GetObject(destObjectKey)
  3209. c.Assert(err, IsNil)
  3210. str, err := readBody(body)
  3211. c.Assert(err, IsNil)
  3212. c.Assert(str, Equals, contextV2)
  3213. // copyobject v1
  3214. options := []Option{VersionId(versionIdV1), GetResponseHeader(&respHeader)}
  3215. _, err = bucket.CopyObject(objectName, destObjectKey, options...)
  3216. c.Assert(err, IsNil)
  3217. srcVersionId = GetCopySrcVersionId(respHeader)
  3218. c.Assert(srcVersionId, Equals, versionIdV1)
  3219. body, err = bucket.GetObject(destObjectKey)
  3220. c.Assert(err, IsNil)
  3221. str, err = readBody(body)
  3222. c.Assert(err, IsNil)
  3223. c.Assert(str, Equals, contextV1)
  3224. // delete object
  3225. err = bucket.DeleteObject(objectName)
  3226. c.Assert(err, IsNil)
  3227. // default copyobject again,failuer
  3228. _, err = bucket.CopyObject(objectName, destObjectKey, GetResponseHeader(&respHeader))
  3229. c.Assert(err, NotNil)
  3230. bucket.DeleteObject(objectName)
  3231. forceDeleteBucket(client, bucketName, c)
  3232. }
  3233. func (s *OssBucketSuite) TestVersioningCompleteMultipartUpload(c *C) {
  3234. // create a bucket with default proprety
  3235. client, err := New(endpoint, accessID, accessKey)
  3236. c.Assert(err, IsNil)
  3237. bucketName := bucketNamePrefix + randLowStr(6)
  3238. err = client.CreateBucket(bucketName)
  3239. c.Assert(err, IsNil)
  3240. bucket, err := client.Bucket(bucketName)
  3241. // put bucket version:enabled
  3242. var versioningConfig VersioningConfig
  3243. versioningConfig.Status = string(VersionEnabled)
  3244. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3245. c.Assert(err, IsNil)
  3246. objectName := objectNamePrefix + randStr(8)
  3247. var fileName = "test-file-" + randStr(8)
  3248. content := randStr(500 * 1024)
  3249. createFile(fileName, content, c)
  3250. chunks, err := SplitFileByPartNum(fileName, 3)
  3251. c.Assert(err, IsNil)
  3252. options := []Option{
  3253. Expires(futureDate), Meta("my", "myprop"),
  3254. }
  3255. fd, err := os.Open(fileName)
  3256. c.Assert(err, IsNil)
  3257. defer fd.Close()
  3258. imur, err := bucket.InitiateMultipartUpload(objectName, options...)
  3259. c.Assert(err, IsNil)
  3260. var parts []UploadPart
  3261. for _, chunk := range chunks {
  3262. fd.Seek(chunk.Offset, os.SEEK_SET)
  3263. part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number)
  3264. c.Assert(err, IsNil)
  3265. parts = append(parts, part)
  3266. }
  3267. var respHeader http.Header
  3268. _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
  3269. c.Assert(err, IsNil)
  3270. //get versionId
  3271. versionIdV1 := GetVersionId(respHeader)
  3272. c.Assert(len(versionIdV1) > 0, Equals, true)
  3273. meta, err := bucket.GetObjectDetailedMeta(objectName)
  3274. c.Assert(err, IsNil)
  3275. c.Assert(meta.Get("X-Oss-Meta-My"), Equals, "myprop")
  3276. c.Assert(meta.Get("Expires"), Equals, futureDate.Format(http.TimeFormat))
  3277. c.Assert(meta.Get("X-Oss-Object-Type"), Equals, "Multipart")
  3278. // put object agagin
  3279. err = bucket.PutObject(objectName, strings.NewReader(""), GetResponseHeader(&respHeader))
  3280. c.Assert(err, IsNil)
  3281. versionIdV2 := GetVersionId(respHeader)
  3282. c.Assert(versionIdV1 == versionIdV2, Equals, false)
  3283. // get meta v1
  3284. meta, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV1))
  3285. c.Assert(err, IsNil)
  3286. c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(content)))
  3287. // get meta v2
  3288. meta, err = bucket.GetObjectDetailedMeta(objectName, VersionId(versionIdV2))
  3289. c.Assert(err, IsNil)
  3290. c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(0))
  3291. os.Remove(fileName)
  3292. bucket.DeleteObject(objectName)
  3293. forceDeleteBucket(client, bucketName, c)
  3294. }
  3295. func (s *OssBucketSuite) TestVersioningUploadPartCopy(c *C) {
  3296. // create a bucket with default proprety
  3297. client, err := New(endpoint, accessID, accessKey)
  3298. c.Assert(err, IsNil)
  3299. bucketName := bucketNamePrefix + randLowStr(6)
  3300. err = client.CreateBucket(bucketName)
  3301. c.Assert(err, IsNil)
  3302. bucket, err := client.Bucket(bucketName)
  3303. // put bucket version:enabled
  3304. var versioningConfig VersioningConfig
  3305. versioningConfig.Status = string(VersionEnabled)
  3306. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3307. c.Assert(err, IsNil)
  3308. // put object v1
  3309. objectName := objectNamePrefix + randStr(8)
  3310. contextV1 := randStr(100)
  3311. versionIdV1 := ""
  3312. var respHeader http.Header
  3313. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3314. c.Assert(err, IsNil)
  3315. versionIdV1 = GetVersionId(respHeader)
  3316. c.Assert(len(versionIdV1) > 0, Equals, true)
  3317. // put object v2
  3318. contextV2 := randStr(200)
  3319. versionIdV2 := ""
  3320. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3321. c.Assert(err, IsNil)
  3322. versionIdV2 = GetVersionId(respHeader)
  3323. c.Assert(len(versionIdV2) > 0, Equals, true)
  3324. // upload mutlipart object with v1
  3325. multiName := objectNamePrefix + randStr(8)
  3326. var parts []UploadPart
  3327. imur, err := bucket.InitiateMultipartUpload(multiName)
  3328. c.Assert(err, IsNil)
  3329. part, err := bucket.UploadPartCopy(imur, bucketName, objectName, 0, int64(len(contextV1)), 1, VersionId(versionIdV1))
  3330. parts = []UploadPart{part}
  3331. c.Assert(err, IsNil)
  3332. _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
  3333. c.Assert(err, IsNil)
  3334. //get versionId
  3335. partVersionIdV1 := GetVersionId(respHeader)
  3336. c.Assert(len(partVersionIdV1) > 0, Equals, true)
  3337. // get meta v1
  3338. meta, err := bucket.GetObjectDetailedMeta(multiName, VersionId(partVersionIdV1))
  3339. c.Assert(err, IsNil)
  3340. c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(contextV1)))
  3341. // upload mutlipart object with v2
  3342. imur, err = bucket.InitiateMultipartUpload(multiName)
  3343. part, err = bucket.UploadPartCopy(imur, bucketName, objectName, 0, int64(len(contextV2)), 1, VersionId(versionIdV2))
  3344. parts = []UploadPart{part}
  3345. _, err = bucket.CompleteMultipartUpload(imur, parts, GetResponseHeader(&respHeader))
  3346. c.Assert(err, IsNil)
  3347. //get versionId
  3348. partVersionIdV2 := GetVersionId(respHeader)
  3349. c.Assert(len(partVersionIdV2) > 0, Equals, true)
  3350. // get meta v2
  3351. meta, err = bucket.GetObjectDetailedMeta(multiName, VersionId(partVersionIdV2))
  3352. c.Assert(err, IsNil)
  3353. c.Assert(meta.Get("content-length"), Equals, strconv.Itoa(len(contextV2)))
  3354. bucket.DeleteObject(objectName)
  3355. bucket.DeleteObject(multiName)
  3356. forceDeleteBucket(client, bucketName, c)
  3357. }
  3358. func (s *OssBucketSuite) TestVersioningRestoreObject(c *C) {
  3359. // create a bucket with default proprety
  3360. client, err := New(endpoint, accessID, accessKey)
  3361. c.Assert(err, IsNil)
  3362. bucketName := bucketNamePrefix + randLowStr(6)
  3363. err = client.CreateBucket(bucketName, StorageClass(StorageArchive))
  3364. c.Assert(err, IsNil)
  3365. bucket, err := client.Bucket(bucketName)
  3366. // put bucket version:enabled
  3367. var versioningConfig VersioningConfig
  3368. versioningConfig.Status = string(VersionEnabled)
  3369. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3370. c.Assert(err, IsNil)
  3371. // put object v1
  3372. objectName := objectNamePrefix + randStr(8)
  3373. contextV1 := randStr(100)
  3374. versionIdV1 := ""
  3375. var respHeader http.Header
  3376. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3377. c.Assert(err, IsNil)
  3378. versionIdV1 = GetVersionId(respHeader)
  3379. c.Assert(len(versionIdV1) > 0, Equals, true)
  3380. // put object v2
  3381. contextV2 := randStr(200)
  3382. versionIdV2 := ""
  3383. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3384. c.Assert(err, IsNil)
  3385. versionIdV2 = GetVersionId(respHeader)
  3386. c.Assert(len(versionIdV2) > 0, Equals, true)
  3387. // RestoreObject v1
  3388. options := []Option{GetResponseHeader(&respHeader), VersionId(versionIdV1)}
  3389. err = bucket.RestoreObject(objectName, options...)
  3390. c.Assert(err, IsNil)
  3391. c.Assert(GetVersionId(respHeader), Equals, versionIdV1)
  3392. // RestoreObject v2
  3393. options = []Option{GetResponseHeader(&respHeader), VersionId(versionIdV2)}
  3394. err = bucket.RestoreObject(objectName, options...)
  3395. c.Assert(err, IsNil)
  3396. c.Assert(GetVersionId(respHeader), Equals, versionIdV2)
  3397. bucket.DeleteObject(objectName)
  3398. forceDeleteBucket(client, bucketName, c)
  3399. }
  3400. func (s *OssBucketSuite) TestVersioningObjectTagging(c *C) {
  3401. // create a bucket with default proprety
  3402. client, err := New(endpoint, accessID, accessKey)
  3403. c.Assert(err, IsNil)
  3404. bucketName := bucketNamePrefix + randLowStr(6)
  3405. err = client.CreateBucket(bucketName, StorageClass(StorageArchive))
  3406. c.Assert(err, IsNil)
  3407. bucket, err := client.Bucket(bucketName)
  3408. // put bucket version:enabled
  3409. var versioningConfig VersioningConfig
  3410. versioningConfig.Status = string(VersionEnabled)
  3411. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3412. c.Assert(err, IsNil)
  3413. // put object v1
  3414. objectName := objectNamePrefix + randStr(8)
  3415. contextV1 := randStr(100)
  3416. versionIdV1 := ""
  3417. var respHeader http.Header
  3418. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3419. c.Assert(err, IsNil)
  3420. versionIdV1 = GetVersionId(respHeader)
  3421. c.Assert(len(versionIdV1) > 0, Equals, true)
  3422. // put object v2
  3423. contextV2 := randStr(200)
  3424. versionIdV2 := ""
  3425. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3426. c.Assert(err, IsNil)
  3427. versionIdV2 = GetVersionId(respHeader)
  3428. c.Assert(len(versionIdV2) > 0, Equals, true)
  3429. // ObjectTagging v1
  3430. var tagging1 Tagging
  3431. tagging1.Tags = []Tag{Tag{Key: "testkey1", Value: "testvalue1"}}
  3432. err = bucket.PutObjectTagging(objectName, tagging1, VersionId(versionIdV1))
  3433. c.Assert(err, IsNil)
  3434. getResult, err := bucket.GetObjectTagging(objectName, VersionId(versionIdV1))
  3435. c.Assert(err, IsNil)
  3436. c.Assert(getResult.Tags[0].Key, Equals, tagging1.Tags[0].Key)
  3437. c.Assert(getResult.Tags[0].Value, Equals, tagging1.Tags[0].Value)
  3438. // ObjectTagging v2
  3439. var tagging2 Tagging
  3440. tagging2.Tags = []Tag{Tag{Key: "testkey2", Value: "testvalue2"}}
  3441. err = bucket.PutObjectTagging(objectName, tagging2, VersionId(versionIdV2))
  3442. c.Assert(err, IsNil)
  3443. getResult, err = bucket.GetObjectTagging(objectName, VersionId(versionIdV2))
  3444. c.Assert(err, IsNil)
  3445. c.Assert(getResult.Tags[0].Key, Equals, tagging2.Tags[0].Key)
  3446. c.Assert(getResult.Tags[0].Value, Equals, tagging2.Tags[0].Value)
  3447. // delete ObjectTagging v2
  3448. err = bucket.DeleteObjectTagging(objectName, VersionId(versionIdV2))
  3449. c.Assert(err, IsNil)
  3450. getResult, err = bucket.GetObjectTagging(objectName, VersionId(versionIdV2))
  3451. c.Assert(err, IsNil)
  3452. c.Assert(len(getResult.Tags), Equals, 0)
  3453. bucket.DeleteObject(objectName)
  3454. forceDeleteBucket(client, bucketName, c)
  3455. }
  3456. func (s *OssBucketSuite) TestVersioningIsObjectExist(c *C) {
  3457. // create a bucket with default proprety
  3458. client, err := New(endpoint, accessID, accessKey)
  3459. c.Assert(err, IsNil)
  3460. bucketName := bucketNamePrefix + randLowStr(6)
  3461. err = client.CreateBucket(bucketName)
  3462. c.Assert(err, IsNil)
  3463. bucket, err := client.Bucket(bucketName)
  3464. // put bucket version:enabled
  3465. var versioningConfig VersioningConfig
  3466. versioningConfig.Status = string(VersionEnabled)
  3467. err = client.SetBucketVersioning(bucketName, versioningConfig)
  3468. c.Assert(err, IsNil)
  3469. // put object v1
  3470. objectName := objectNamePrefix + randStr(8)
  3471. contextV1 := randStr(100)
  3472. versionIdV1 := ""
  3473. var respHeader http.Header
  3474. err = bucket.PutObject(objectName, strings.NewReader(contextV1), GetResponseHeader(&respHeader))
  3475. c.Assert(err, IsNil)
  3476. versionIdV1 = GetVersionId(respHeader)
  3477. c.Assert(len(versionIdV1) > 0, Equals, true)
  3478. // put object v2
  3479. contextV2 := randStr(200)
  3480. versionIdV2 := ""
  3481. err = bucket.PutObject(objectName, strings.NewReader(contextV2), GetResponseHeader(&respHeader))
  3482. c.Assert(err, IsNil)
  3483. versionIdV2 = GetVersionId(respHeader)
  3484. c.Assert(len(versionIdV2) > 0, Equals, true)
  3485. // check v1 and v2
  3486. c.Assert(versionIdV1 != versionIdV2, Equals, true)
  3487. // check default exist
  3488. exist, err := bucket.IsObjectExist(objectName)
  3489. c.Assert(err, IsNil)
  3490. c.Assert(exist, Equals, true)
  3491. // check object v1 exist
  3492. exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV1))
  3493. c.Assert(err, IsNil)
  3494. c.Assert(exist, Equals, true)
  3495. // check object v2 exist
  3496. exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV2))
  3497. c.Assert(err, IsNil)
  3498. c.Assert(exist, Equals, true)
  3499. // rm v2
  3500. err = bucket.DeleteObject(objectName, VersionId(versionIdV2))
  3501. c.Assert(err, IsNil)
  3502. // check object v2 not exist
  3503. exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV2))
  3504. c.Assert(err, IsNil)
  3505. c.Assert(exist, Equals, false)
  3506. // rm default
  3507. err = bucket.DeleteObject(objectName)
  3508. c.Assert(err, IsNil)
  3509. // check default exist
  3510. exist, err = bucket.IsObjectExist(objectName)
  3511. c.Assert(err, IsNil)
  3512. c.Assert(exist, Equals, false)
  3513. // check v1 exist
  3514. exist, err = bucket.IsObjectExist(objectName, VersionId(versionIdV1))
  3515. c.Assert(err, IsNil)
  3516. c.Assert(exist, Equals, true)
  3517. forceDeleteBucket(client, bucketName, c)
  3518. }
  3519. func (s *OssBucketSuite) TestOptionsMethod(c *C) {
  3520. // create a bucket with default proprety
  3521. client, err := New(endpoint, accessID, accessKey)
  3522. c.Assert(err, IsNil)
  3523. bucketName := bucketNamePrefix + randLowStr(6)
  3524. err = client.CreateBucket(bucketName)
  3525. c.Assert(err, IsNil)
  3526. bucket, err := client.Bucket(bucketName)
  3527. // put bucket cors
  3528. var rule = CORSRule{
  3529. AllowedOrigin: []string{"www.aliyun.com"},
  3530. AllowedMethod: []string{"PUT", "GET", "POST"},
  3531. AllowedHeader: []string{"x-oss-meta-author"},
  3532. ExposeHeader: []string{"x-oss-meta-name"},
  3533. MaxAgeSeconds: 100,
  3534. }
  3535. // set cors
  3536. err = client.SetBucketCORS(bucketName, []CORSRule{rule})
  3537. c.Assert(err, IsNil)
  3538. // bucket options success
  3539. options := []Option{}
  3540. originOption := Origin("www.aliyun.com")
  3541. acMethodOption := ACReqMethod("PUT")
  3542. acHeadersOption := ACReqHeaders("x-oss-meta-author")
  3543. options = append(options, originOption)
  3544. options = append(options, acMethodOption)
  3545. options = append(options, acHeadersOption)
  3546. _, err = bucket.OptionsMethod("", options...)
  3547. c.Assert(err, IsNil)
  3548. // options failure
  3549. options = []Option{}
  3550. originOption = Origin("www.aliyun.com")
  3551. acMethodOption = ACReqMethod("PUT")
  3552. acHeadersOption = ACReqHeaders("x-oss-meta-author-1")
  3553. options = append(options, originOption)
  3554. options = append(options, acMethodOption)
  3555. options = append(options, acHeadersOption)
  3556. _, err = bucket.OptionsMethod("", options...)
  3557. c.Assert(err, NotNil)
  3558. // put object
  3559. objectName := objectNamePrefix + randStr(8)
  3560. context := randStr(100)
  3561. err = bucket.PutObject(objectName, strings.NewReader(context))
  3562. c.Assert(err, IsNil)
  3563. // object options success
  3564. options = []Option{}
  3565. originOption = Origin("www.aliyun.com")
  3566. acMethodOption = ACReqMethod("PUT")
  3567. acHeadersOption = ACReqHeaders("x-oss-meta-author")
  3568. options = append(options, originOption)
  3569. options = append(options, acMethodOption)
  3570. options = append(options, acHeadersOption)
  3571. _, err = bucket.OptionsMethod("", options...)
  3572. c.Assert(err, IsNil)
  3573. // options failure
  3574. options = []Option{}
  3575. originOption = Origin("www.aliyun.com")
  3576. acMethodOption = ACReqMethod("PUT")
  3577. acHeadersOption = ACReqHeaders("x-oss-meta-author-1")
  3578. options = append(options, originOption)
  3579. options = append(options, acMethodOption)
  3580. options = append(options, acHeadersOption)
  3581. _, err = bucket.OptionsMethod("", options...)
  3582. c.Assert(err, NotNil)
  3583. bucket.DeleteObject(objectName)
  3584. forceDeleteBucket(client, bucketName, c)
  3585. }
  3586. func (s *OssBucketSuite) TestBucketTrafficLimitObject(c *C) {
  3587. // create a bucket with default proprety
  3588. client, err := New(endpoint, accessID, accessKey)
  3589. c.Assert(err, IsNil)
  3590. bucketName := bucketNamePrefix + randLowStr(6)
  3591. err = client.CreateBucket(bucketName)
  3592. c.Assert(err, IsNil)
  3593. bucket, err := client.Bucket(bucketName)
  3594. var respHeader http.Header
  3595. var qosDelayTime string
  3596. var traffic int64 = 819220 // 100KB
  3597. maxTraffic := traffic * 120 / 100
  3598. objectName := objectNamePrefix + randStr(8)
  3599. localFile := "../sample/BingWallpaper-2015-11-07.jpg"
  3600. fd, err := os.Open(localFile)
  3601. c.Assert(err, IsNil)
  3602. defer fd.Close()
  3603. tryGetFileSize := func(f *os.File) int64 {
  3604. fInfo, _ := f.Stat()
  3605. return fInfo.Size()
  3606. }
  3607. contentLength := tryGetFileSize(fd) * 8
  3608. // put object
  3609. start := time.Now().UnixNano() / 1000 / 1000
  3610. err = bucket.PutObject(objectName, fd, TrafficLimitHeader(traffic), GetResponseHeader(&respHeader))
  3611. c.Assert(err, IsNil)
  3612. endingTime := time.Now().UnixNano() / 1000 / 1000
  3613. costT := endingTime - start
  3614. costV := contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3615. c.Assert((costV < maxTraffic), Equals, true)
  3616. qosDelayTime = GetQosDelayTime(respHeader)
  3617. c.Assert(len(qosDelayTime) > 0, Equals, true)
  3618. // putobject without TrafficLimit
  3619. //
  3620. // fd, err = os.Open(localFile)
  3621. // c.Assert(err, IsNil)
  3622. // defer fd.Close()
  3623. // start = time.Now().UnixNano() / 1000 / 1000
  3624. // err = bucket.PutObject(objectName, fd)
  3625. // c.Assert(err, IsNil)
  3626. // endingTime = time.Now().UnixNano() / 1000 / 1000
  3627. // costT = endingTime - start
  3628. // costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3629. // testLogger.Println(traffic, maxTraffic, contentLength, costT, costV)
  3630. // c.Assert((costV < maxTraffic), Equals, true)
  3631. // get object to file
  3632. newFile := "test-file-" + randStr(10)
  3633. start = time.Now().UnixNano() / 1000 / 1000
  3634. err = bucket.GetObjectToFile(objectName, newFile, TrafficLimitHeader(traffic))
  3635. c.Assert(err, IsNil)
  3636. endingTime = time.Now().UnixNano() / 1000 / 1000
  3637. costT = endingTime - start
  3638. costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3639. c.Assert((costV < maxTraffic), Equals, true)
  3640. os.Remove(newFile)
  3641. // append object
  3642. newFile = "test-file-" + randStr(10)
  3643. objectKey := objectNamePrefix + randStr(8)
  3644. var nextPos int64
  3645. fd, err = os.Open(localFile)
  3646. c.Assert(err, IsNil)
  3647. defer fd.Close()
  3648. start = time.Now().UnixNano() / 1000 / 1000
  3649. nextPos, err = bucket.AppendObject(objectKey, strings.NewReader(randStr(18)), nextPos)
  3650. c.Assert(err, IsNil)
  3651. var respAppendHeader http.Header
  3652. nextPos, err = bucket.AppendObject(objectKey, fd, nextPos, TrafficLimitHeader(traffic), GetResponseHeader(&respAppendHeader))
  3653. c.Assert(err, IsNil)
  3654. endingTime = time.Now().UnixNano() / 1000 / 1000
  3655. costT = endingTime - start
  3656. costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3657. c.Assert((costV < maxTraffic), Equals, true)
  3658. qosDelayTime = GetQosDelayTime(respAppendHeader)
  3659. c.Assert(len(qosDelayTime) > 0, Equals, true)
  3660. err = bucket.GetObjectToFile(objectKey, newFile, TrafficLimitHeader(traffic))
  3661. c.Assert(err, IsNil)
  3662. err = bucket.DeleteObject(objectKey)
  3663. c.Assert(err, IsNil)
  3664. os.Remove(newFile)
  3665. // put object with url
  3666. fd, err = os.Open(localFile)
  3667. c.Assert(err, IsNil)
  3668. defer fd.Close()
  3669. strURL, err := bucket.SignURL(objectName, HTTPPut, 60, TrafficLimitParam(traffic))
  3670. start = time.Now().UnixNano() / 1000 / 1000
  3671. err = bucket.PutObjectWithURL(strURL, fd)
  3672. c.Assert(err, IsNil)
  3673. endingTime = time.Now().UnixNano() / 1000 / 1000
  3674. costT = endingTime - start
  3675. costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3676. c.Assert((costV < maxTraffic), Equals, true)
  3677. // get object with url
  3678. newFile = "test-file-" + randStr(10)
  3679. strURL, err = bucket.SignURL(objectName, HTTPGet, 60, TrafficLimitParam(traffic))
  3680. c.Assert(err, IsNil)
  3681. start = time.Now().UnixNano() / 1000 / 1000
  3682. err = bucket.GetObjectToFileWithURL(strURL, newFile)
  3683. c.Assert(err, IsNil)
  3684. endingTime = time.Now().UnixNano() / 1000 / 1000
  3685. costT = endingTime - start
  3686. costV = contentLength * 1000 / costT // bit * 1000 / Millisecond = bit/s
  3687. c.Assert((costV < maxTraffic), Equals, true)
  3688. os.Remove(newFile)
  3689. // copy object
  3690. destObjectName := objectNamePrefix + randStr(8)
  3691. _, err = bucket.CopyObject(objectName, destObjectName, TrafficLimitHeader(traffic))
  3692. c.Assert(err, IsNil)
  3693. err = bucket.DeleteObject(destObjectName)
  3694. c.Assert(err, IsNil)
  3695. forceDeleteBucket(client, bucketName, c)
  3696. }
  3697. func (s *OssBucketSuite) TestBucketTrafficLimitUpload(c *C) {
  3698. // create a bucket with default proprety
  3699. client, err := New(endpoint, accessID, accessKey)
  3700. c.Assert(err, IsNil)
  3701. bucketName := bucketNamePrefix + randLowStr(6)
  3702. err = client.CreateBucket(bucketName)
  3703. c.Assert(err, IsNil)
  3704. bucket, err := client.Bucket(bucketName)
  3705. var traffic int64 = 819220 // 100KB
  3706. maxTraffic := traffic * 120 / 100
  3707. contentLength := 500 * 1024
  3708. var fileName = "test-file-" + randStr(8)
  3709. objectName := objectNamePrefix + randStr(8)
  3710. content := randStr(contentLength)
  3711. createFile(fileName, content, c)
  3712. chunks, err := SplitFileByPartNum(fileName, 3)
  3713. c.Assert(err, IsNil)
  3714. options := []Option{
  3715. Expires(futureDate), Meta("my", "myprop"),
  3716. }
  3717. fd, err := os.Open(fileName)
  3718. c.Assert(err, IsNil)
  3719. defer fd.Close()
  3720. imur, err := bucket.InitiateMultipartUpload(objectName, options...)
  3721. c.Assert(err, IsNil)
  3722. var parts []UploadPart
  3723. start := time.Now().UnixNano() / 1000 / 1000
  3724. for _, chunk := range chunks {
  3725. fd.Seek(chunk.Offset, os.SEEK_SET)
  3726. part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number, TrafficLimitHeader(traffic))
  3727. c.Assert(err, IsNil)
  3728. parts = append(parts, part)
  3729. }
  3730. _, err = bucket.CompleteMultipartUpload(imur, parts)
  3731. c.Assert(err, IsNil)
  3732. endingTime := time.Now().UnixNano() / 1000 / 1000
  3733. costT := endingTime - start
  3734. costV := int64(contentLength) * 8 * 1000 / costT // B * 8 * 1000 / Millisecond = bit/s
  3735. c.Assert((costV < maxTraffic), Equals, true)
  3736. os.Remove(fileName)
  3737. forceDeleteBucket(client, bucketName, c)
  3738. }
  3739. func (s *OssBucketSuite) TestPutObjectWithForbidOverWrite(c *C) {
  3740. // create a bucket with default proprety
  3741. client, err := New(endpoint, accessID, accessKey)
  3742. c.Assert(err, IsNil)
  3743. bucketName := bucketNamePrefix + randLowStr(6)
  3744. err = client.CreateBucket(bucketName)
  3745. c.Assert(err, IsNil)
  3746. bucket, err := client.Bucket(bucketName)
  3747. contentLength := 1024
  3748. objectName := objectNamePrefix + randStr(8)
  3749. content := randStr(contentLength)
  3750. // first put success
  3751. err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(true))
  3752. c.Assert(err, IsNil)
  3753. // second put failure with ForbidOverWrite true
  3754. var respHeader http.Header
  3755. err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(true), GetResponseHeader(&respHeader))
  3756. c.Assert(err, NotNil)
  3757. // third put success with ForbidOverWrite false
  3758. err = bucket.PutObject(objectName, strings.NewReader(content), ForbidOverWrite(false))
  3759. c.Assert(err, IsNil)
  3760. forceDeleteBucket(client, bucketName, c)
  3761. }
  3762. func (s *OssBucketSuite) TestCopyObjectWithForbidOverWrite(c *C) {
  3763. // create a bucket with default proprety
  3764. client, err := New(endpoint, accessID, accessKey)
  3765. c.Assert(err, IsNil)
  3766. bucketName := bucketNamePrefix + randLowStr(6)
  3767. err = client.CreateBucket(bucketName)
  3768. c.Assert(err, IsNil)
  3769. bucket, err := client.Bucket(bucketName)
  3770. contentLength := 1024
  3771. objectName := objectNamePrefix + randStr(8)
  3772. content := randStr(contentLength)
  3773. err = bucket.PutObject(objectName, strings.NewReader(content))
  3774. c.Assert(err, IsNil)
  3775. // first copy success
  3776. copyObjectName := objectName + "-copy"
  3777. _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(true))
  3778. c.Assert(err, IsNil)
  3779. // second copy failure with ForbidOverWrite true
  3780. var respHeader http.Header
  3781. _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(true), GetResponseHeader(&respHeader))
  3782. c.Assert(err, NotNil)
  3783. // third copy success with ForbidOverWrite false
  3784. _, err = bucket.CopyObject(objectName, copyObjectName, ForbidOverWrite(false))
  3785. c.Assert(err, IsNil)
  3786. forceDeleteBucket(client, bucketName, c)
  3787. }
  3788. func (s *OssBucketSuite) TestDeleteObjectsWithSpecialCharacter(c *C) {
  3789. // create a bucket with default proprety
  3790. client, err := New(endpoint, accessID, accessKey)
  3791. c.Assert(err, IsNil)
  3792. bucketName := bucketNamePrefix + randLowStr(6)
  3793. err = client.CreateBucket(bucketName)
  3794. c.Assert(err, IsNil)
  3795. bucket, err := client.Bucket(bucketName)
  3796. contentLength := 100
  3797. objectName1 := objectNamePrefix + randStr(8) + "<-->+&*\r%%"
  3798. objectName2 := objectNamePrefix + randStr(8) + "\r&*\r%%"
  3799. //objectName2 := objectNamePrefix + randStr(8) + "%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2F%C0%AE%C0%AE%2Fetc%2Fprofile"
  3800. //objectName2, err = url.QueryUnescape(objectName2)
  3801. c.Assert(err, IsNil)
  3802. content := randStr(contentLength)
  3803. err = bucket.PutObject(objectName1, strings.NewReader(content))
  3804. c.Assert(err, IsNil)
  3805. err = bucket.PutObject(objectName2, strings.NewReader(content))
  3806. c.Assert(err, IsNil)
  3807. // delete objectName1 objectName2
  3808. objectKeys := []string{objectName1, objectName2}
  3809. _, err = bucket.DeleteObjects(objectKeys)
  3810. c.Assert(err, IsNil)
  3811. // objectName1 is not exist
  3812. exist, err := bucket.IsObjectExist(objectName1)
  3813. c.Assert(err, IsNil)
  3814. c.Assert(exist, Equals, false)
  3815. // objectName2 is not exist
  3816. exist, err = bucket.IsObjectExist(objectName2)
  3817. c.Assert(err, IsNil)
  3818. c.Assert(exist, Equals, false)
  3819. forceDeleteBucket(client, bucketName, c)
  3820. }