client_test.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package v2http
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/json"
  19. "errors"
  20. "io/ioutil"
  21. "net/http"
  22. "net/http/httptest"
  23. "net/url"
  24. "path"
  25. "reflect"
  26. "strings"
  27. "testing"
  28. "time"
  29. etcdErr "github.com/coreos/etcd/error"
  30. "github.com/coreos/etcd/etcdserver"
  31. "github.com/coreos/etcd/etcdserver/api"
  32. "github.com/coreos/etcd/etcdserver/api/v2http/httptypes"
  33. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  34. "github.com/coreos/etcd/etcdserver/membership"
  35. "github.com/coreos/etcd/pkg/testutil"
  36. "github.com/coreos/etcd/pkg/types"
  37. "github.com/coreos/etcd/raft/raftpb"
  38. "github.com/coreos/etcd/store"
  39. "github.com/coreos/go-semver/semver"
  40. "github.com/jonboulle/clockwork"
  41. )
  42. func mustMarshalEvent(t *testing.T, ev *store.Event) string {
  43. b := new(bytes.Buffer)
  44. if err := json.NewEncoder(b).Encode(ev); err != nil {
  45. t.Fatalf("error marshalling event %#v: %v", ev, err)
  46. }
  47. return b.String()
  48. }
  49. // mustNewForm takes a set of Values and constructs a PUT *http.Request,
  50. // with a URL constructed from appending the given path to the standard keysPrefix
  51. func mustNewForm(t *testing.T, p string, vals url.Values) *http.Request {
  52. u := testutil.MustNewURL(t, path.Join(keysPrefix, p))
  53. req, err := http.NewRequest("PUT", u.String(), strings.NewReader(vals.Encode()))
  54. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  55. if err != nil {
  56. t.Fatalf("error creating new request: %v", err)
  57. }
  58. return req
  59. }
  60. // mustNewPostForm takes a set of Values and constructs a POST *http.Request,
  61. // with a URL constructed from appending the given path to the standard keysPrefix
  62. func mustNewPostForm(t *testing.T, p string, vals url.Values) *http.Request {
  63. u := testutil.MustNewURL(t, path.Join(keysPrefix, p))
  64. req, err := http.NewRequest("POST", u.String(), strings.NewReader(vals.Encode()))
  65. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  66. if err != nil {
  67. t.Fatalf("error creating new request: %v", err)
  68. }
  69. return req
  70. }
  71. // mustNewRequest takes a path, appends it to the standard keysPrefix, and constructs
  72. // a GET *http.Request referencing the resulting URL
  73. func mustNewRequest(t *testing.T, p string) *http.Request {
  74. return mustNewMethodRequest(t, "GET", p)
  75. }
  76. func mustNewMethodRequest(t *testing.T, m, p string) *http.Request {
  77. return &http.Request{
  78. Method: m,
  79. URL: testutil.MustNewURL(t, path.Join(keysPrefix, p)),
  80. }
  81. }
  82. type fakeServer struct {
  83. dummyRaftTimer
  84. dummyStats
  85. }
  86. func (s *fakeServer) Leader() types.ID { return types.ID(1) }
  87. func (s *fakeServer) Alarms() []*etcdserverpb.AlarmMember { return nil }
  88. func (s *fakeServer) Cluster() api.Cluster { return nil }
  89. func (s *fakeServer) ClusterVersion() *semver.Version { return nil }
  90. func (s *fakeServer) RaftHandler() http.Handler { return nil }
  91. func (s *fakeServer) Do(ctx context.Context, r etcdserverpb.Request) (rr etcdserver.Response, err error) {
  92. return
  93. }
  94. func (s *fakeServer) ClientCertAuthEnabled() bool { return false }
  95. type serverRecorder struct {
  96. fakeServer
  97. actions []action
  98. }
  99. func (s *serverRecorder) Do(_ context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
  100. s.actions = append(s.actions, action{name: "Do", params: []interface{}{r}})
  101. return etcdserver.Response{}, nil
  102. }
  103. func (s *serverRecorder) Process(_ context.Context, m raftpb.Message) error {
  104. s.actions = append(s.actions, action{name: "Process", params: []interface{}{m}})
  105. return nil
  106. }
  107. func (s *serverRecorder) AddMember(_ context.Context, m membership.Member) ([]*membership.Member, error) {
  108. s.actions = append(s.actions, action{name: "AddMember", params: []interface{}{m}})
  109. return nil, nil
  110. }
  111. func (s *serverRecorder) RemoveMember(_ context.Context, id uint64) ([]*membership.Member, error) {
  112. s.actions = append(s.actions, action{name: "RemoveMember", params: []interface{}{id}})
  113. return nil, nil
  114. }
  115. func (s *serverRecorder) UpdateMember(_ context.Context, m membership.Member) ([]*membership.Member, error) {
  116. s.actions = append(s.actions, action{name: "UpdateMember", params: []interface{}{m}})
  117. return nil, nil
  118. }
  119. type action struct {
  120. name string
  121. params []interface{}
  122. }
  123. // flushingRecorder provides a channel to allow users to block until the Recorder is Flushed()
  124. type flushingRecorder struct {
  125. *httptest.ResponseRecorder
  126. ch chan struct{}
  127. }
  128. func (fr *flushingRecorder) Flush() {
  129. fr.ResponseRecorder.Flush()
  130. fr.ch <- struct{}{}
  131. }
  132. // resServer implements the etcd.Server interface for testing.
  133. // It returns the given response from any Do calls, and nil error
  134. type resServer struct {
  135. fakeServer
  136. res etcdserver.Response
  137. }
  138. func (rs *resServer) Do(_ context.Context, _ etcdserverpb.Request) (etcdserver.Response, error) {
  139. return rs.res, nil
  140. }
  141. func (rs *resServer) Process(_ context.Context, _ raftpb.Message) error { return nil }
  142. func (rs *resServer) AddMember(_ context.Context, _ membership.Member) ([]*membership.Member, error) {
  143. return nil, nil
  144. }
  145. func (rs *resServer) RemoveMember(_ context.Context, _ uint64) ([]*membership.Member, error) {
  146. return nil, nil
  147. }
  148. func (rs *resServer) UpdateMember(_ context.Context, _ membership.Member) ([]*membership.Member, error) {
  149. return nil, nil
  150. }
  151. func boolp(b bool) *bool { return &b }
  152. type dummyRaftTimer struct{}
  153. func (drt dummyRaftTimer) Index() uint64 { return uint64(100) }
  154. func (drt dummyRaftTimer) Term() uint64 { return uint64(5) }
  155. type dummyWatcher struct {
  156. echan chan *store.Event
  157. sidx uint64
  158. }
  159. func (w *dummyWatcher) EventChan() chan *store.Event {
  160. return w.echan
  161. }
  162. func (w *dummyWatcher) StartIndex() uint64 { return w.sidx }
  163. func (w *dummyWatcher) Remove() {}
  164. func TestBadRefreshRequest(t *testing.T) {
  165. tests := []struct {
  166. in *http.Request
  167. wcode int
  168. }{
  169. {
  170. mustNewRequest(t, "foo?refresh=true&value=test"),
  171. etcdErr.EcodeRefreshValue,
  172. },
  173. {
  174. mustNewRequest(t, "foo?refresh=true&value=10"),
  175. etcdErr.EcodeRefreshValue,
  176. },
  177. {
  178. mustNewRequest(t, "foo?refresh=true"),
  179. etcdErr.EcodeRefreshTTLRequired,
  180. },
  181. {
  182. mustNewRequest(t, "foo?refresh=true&ttl="),
  183. etcdErr.EcodeRefreshTTLRequired,
  184. },
  185. }
  186. for i, tt := range tests {
  187. got, _, err := parseKeyRequest(tt.in, clockwork.NewFakeClock())
  188. if err == nil {
  189. t.Errorf("#%d: unexpected nil error!", i)
  190. continue
  191. }
  192. ee, ok := err.(*etcdErr.Error)
  193. if !ok {
  194. t.Errorf("#%d: err is not etcd.Error!", i)
  195. continue
  196. }
  197. if ee.ErrorCode != tt.wcode {
  198. t.Errorf("#%d: code=%d, want %v", i, ee.ErrorCode, tt.wcode)
  199. t.Logf("cause: %#v", ee.Cause)
  200. }
  201. if !reflect.DeepEqual(got, etcdserverpb.Request{}) {
  202. t.Errorf("#%d: unexpected non-empty Request: %#v", i, got)
  203. }
  204. }
  205. }
  206. func TestBadParseRequest(t *testing.T) {
  207. tests := []struct {
  208. in *http.Request
  209. wcode int
  210. }{
  211. {
  212. // parseForm failure
  213. &http.Request{
  214. Body: nil,
  215. Method: "PUT",
  216. },
  217. etcdErr.EcodeInvalidForm,
  218. },
  219. {
  220. // bad key prefix
  221. &http.Request{
  222. URL: testutil.MustNewURL(t, "/badprefix/"),
  223. },
  224. etcdErr.EcodeInvalidForm,
  225. },
  226. // bad values for prevIndex, waitIndex, ttl
  227. {
  228. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"garbage"}}),
  229. etcdErr.EcodeIndexNaN,
  230. },
  231. {
  232. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"1.5"}}),
  233. etcdErr.EcodeIndexNaN,
  234. },
  235. {
  236. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"-1"}}),
  237. etcdErr.EcodeIndexNaN,
  238. },
  239. {
  240. mustNewForm(t, "foo", url.Values{"waitIndex": []string{"garbage"}}),
  241. etcdErr.EcodeIndexNaN,
  242. },
  243. {
  244. mustNewForm(t, "foo", url.Values{"waitIndex": []string{"??"}}),
  245. etcdErr.EcodeIndexNaN,
  246. },
  247. {
  248. mustNewForm(t, "foo", url.Values{"ttl": []string{"-1"}}),
  249. etcdErr.EcodeTTLNaN,
  250. },
  251. // bad values for recursive, sorted, wait, prevExist, dir, stream
  252. {
  253. mustNewForm(t, "foo", url.Values{"recursive": []string{"hahaha"}}),
  254. etcdErr.EcodeInvalidField,
  255. },
  256. {
  257. mustNewForm(t, "foo", url.Values{"recursive": []string{"1234"}}),
  258. etcdErr.EcodeInvalidField,
  259. },
  260. {
  261. mustNewForm(t, "foo", url.Values{"recursive": []string{"?"}}),
  262. etcdErr.EcodeInvalidField,
  263. },
  264. {
  265. mustNewForm(t, "foo", url.Values{"sorted": []string{"?"}}),
  266. etcdErr.EcodeInvalidField,
  267. },
  268. {
  269. mustNewForm(t, "foo", url.Values{"sorted": []string{"x"}}),
  270. etcdErr.EcodeInvalidField,
  271. },
  272. {
  273. mustNewForm(t, "foo", url.Values{"wait": []string{"?!"}}),
  274. etcdErr.EcodeInvalidField,
  275. },
  276. {
  277. mustNewForm(t, "foo", url.Values{"wait": []string{"yes"}}),
  278. etcdErr.EcodeInvalidField,
  279. },
  280. {
  281. mustNewForm(t, "foo", url.Values{"prevExist": []string{"yes"}}),
  282. etcdErr.EcodeInvalidField,
  283. },
  284. {
  285. mustNewForm(t, "foo", url.Values{"prevExist": []string{"#2"}}),
  286. etcdErr.EcodeInvalidField,
  287. },
  288. {
  289. mustNewForm(t, "foo", url.Values{"dir": []string{"no"}}),
  290. etcdErr.EcodeInvalidField,
  291. },
  292. {
  293. mustNewForm(t, "foo", url.Values{"dir": []string{"file"}}),
  294. etcdErr.EcodeInvalidField,
  295. },
  296. {
  297. mustNewForm(t, "foo", url.Values{"quorum": []string{"no"}}),
  298. etcdErr.EcodeInvalidField,
  299. },
  300. {
  301. mustNewForm(t, "foo", url.Values{"quorum": []string{"file"}}),
  302. etcdErr.EcodeInvalidField,
  303. },
  304. {
  305. mustNewForm(t, "foo", url.Values{"stream": []string{"zzz"}}),
  306. etcdErr.EcodeInvalidField,
  307. },
  308. {
  309. mustNewForm(t, "foo", url.Values{"stream": []string{"something"}}),
  310. etcdErr.EcodeInvalidField,
  311. },
  312. // prevValue cannot be empty
  313. {
  314. mustNewForm(t, "foo", url.Values{"prevValue": []string{""}}),
  315. etcdErr.EcodePrevValueRequired,
  316. },
  317. // wait is only valid with GET requests
  318. {
  319. mustNewMethodRequest(t, "HEAD", "foo?wait=true"),
  320. etcdErr.EcodeInvalidField,
  321. },
  322. // query values are considered
  323. {
  324. mustNewRequest(t, "foo?prevExist=wrong"),
  325. etcdErr.EcodeInvalidField,
  326. },
  327. {
  328. mustNewRequest(t, "foo?ttl=wrong"),
  329. etcdErr.EcodeTTLNaN,
  330. },
  331. // but body takes precedence if both are specified
  332. {
  333. mustNewForm(
  334. t,
  335. "foo?ttl=12",
  336. url.Values{"ttl": []string{"garbage"}},
  337. ),
  338. etcdErr.EcodeTTLNaN,
  339. },
  340. {
  341. mustNewForm(
  342. t,
  343. "foo?prevExist=false",
  344. url.Values{"prevExist": []string{"yes"}},
  345. ),
  346. etcdErr.EcodeInvalidField,
  347. },
  348. }
  349. for i, tt := range tests {
  350. got, _, err := parseKeyRequest(tt.in, clockwork.NewFakeClock())
  351. if err == nil {
  352. t.Errorf("#%d: unexpected nil error!", i)
  353. continue
  354. }
  355. ee, ok := err.(*etcdErr.Error)
  356. if !ok {
  357. t.Errorf("#%d: err is not etcd.Error!", i)
  358. continue
  359. }
  360. if ee.ErrorCode != tt.wcode {
  361. t.Errorf("#%d: code=%d, want %v", i, ee.ErrorCode, tt.wcode)
  362. t.Logf("cause: %#v", ee.Cause)
  363. }
  364. if !reflect.DeepEqual(got, etcdserverpb.Request{}) {
  365. t.Errorf("#%d: unexpected non-empty Request: %#v", i, got)
  366. }
  367. }
  368. }
  369. func TestGoodParseRequest(t *testing.T) {
  370. fc := clockwork.NewFakeClock()
  371. fc.Advance(1111)
  372. tests := []struct {
  373. in *http.Request
  374. w etcdserverpb.Request
  375. noValue bool
  376. }{
  377. {
  378. // good prefix, all other values default
  379. mustNewRequest(t, "foo"),
  380. etcdserverpb.Request{
  381. Method: "GET",
  382. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  383. },
  384. false,
  385. },
  386. {
  387. // value specified
  388. mustNewForm(
  389. t,
  390. "foo",
  391. url.Values{"value": []string{"some_value"}},
  392. ),
  393. etcdserverpb.Request{
  394. Method: "PUT",
  395. Val: "some_value",
  396. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  397. },
  398. false,
  399. },
  400. {
  401. // prevIndex specified
  402. mustNewForm(
  403. t,
  404. "foo",
  405. url.Values{"prevIndex": []string{"98765"}},
  406. ),
  407. etcdserverpb.Request{
  408. Method: "PUT",
  409. PrevIndex: 98765,
  410. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  411. },
  412. false,
  413. },
  414. {
  415. // recursive specified
  416. mustNewForm(
  417. t,
  418. "foo",
  419. url.Values{"recursive": []string{"true"}},
  420. ),
  421. etcdserverpb.Request{
  422. Method: "PUT",
  423. Recursive: true,
  424. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  425. },
  426. false,
  427. },
  428. {
  429. // sorted specified
  430. mustNewForm(
  431. t,
  432. "foo",
  433. url.Values{"sorted": []string{"true"}},
  434. ),
  435. etcdserverpb.Request{
  436. Method: "PUT",
  437. Sorted: true,
  438. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  439. },
  440. false,
  441. },
  442. {
  443. // quorum specified
  444. mustNewForm(
  445. t,
  446. "foo",
  447. url.Values{"quorum": []string{"true"}},
  448. ),
  449. etcdserverpb.Request{
  450. Method: "PUT",
  451. Quorum: true,
  452. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  453. },
  454. false,
  455. },
  456. {
  457. // wait specified
  458. mustNewRequest(t, "foo?wait=true"),
  459. etcdserverpb.Request{
  460. Method: "GET",
  461. Wait: true,
  462. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  463. },
  464. false,
  465. },
  466. {
  467. // empty TTL specified
  468. mustNewRequest(t, "foo?ttl="),
  469. etcdserverpb.Request{
  470. Method: "GET",
  471. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  472. Expiration: 0,
  473. },
  474. false,
  475. },
  476. {
  477. // non-empty TTL specified
  478. mustNewRequest(t, "foo?ttl=5678"),
  479. etcdserverpb.Request{
  480. Method: "GET",
  481. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  482. Expiration: fc.Now().Add(5678 * time.Second).UnixNano(),
  483. },
  484. false,
  485. },
  486. {
  487. // zero TTL specified
  488. mustNewRequest(t, "foo?ttl=0"),
  489. etcdserverpb.Request{
  490. Method: "GET",
  491. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  492. Expiration: fc.Now().UnixNano(),
  493. },
  494. false,
  495. },
  496. {
  497. // dir specified
  498. mustNewRequest(t, "foo?dir=true"),
  499. etcdserverpb.Request{
  500. Method: "GET",
  501. Dir: true,
  502. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  503. },
  504. false,
  505. },
  506. {
  507. // dir specified negatively
  508. mustNewRequest(t, "foo?dir=false"),
  509. etcdserverpb.Request{
  510. Method: "GET",
  511. Dir: false,
  512. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  513. },
  514. false,
  515. },
  516. {
  517. // prevExist should be non-null if specified
  518. mustNewForm(
  519. t,
  520. "foo",
  521. url.Values{"prevExist": []string{"true"}},
  522. ),
  523. etcdserverpb.Request{
  524. Method: "PUT",
  525. PrevExist: boolp(true),
  526. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  527. },
  528. false,
  529. },
  530. {
  531. // prevExist should be non-null if specified
  532. mustNewForm(
  533. t,
  534. "foo",
  535. url.Values{"prevExist": []string{"false"}},
  536. ),
  537. etcdserverpb.Request{
  538. Method: "PUT",
  539. PrevExist: boolp(false),
  540. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  541. },
  542. false,
  543. },
  544. // mix various fields
  545. {
  546. mustNewForm(
  547. t,
  548. "foo",
  549. url.Values{
  550. "value": []string{"some value"},
  551. "prevExist": []string{"true"},
  552. "prevValue": []string{"previous value"},
  553. },
  554. ),
  555. etcdserverpb.Request{
  556. Method: "PUT",
  557. PrevExist: boolp(true),
  558. PrevValue: "previous value",
  559. Val: "some value",
  560. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  561. },
  562. false,
  563. },
  564. // query parameters should be used if given
  565. {
  566. mustNewForm(
  567. t,
  568. "foo?prevValue=woof",
  569. url.Values{},
  570. ),
  571. etcdserverpb.Request{
  572. Method: "PUT",
  573. PrevValue: "woof",
  574. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  575. },
  576. false,
  577. },
  578. // but form values should take precedence over query parameters
  579. {
  580. mustNewForm(
  581. t,
  582. "foo?prevValue=woof",
  583. url.Values{
  584. "prevValue": []string{"miaow"},
  585. },
  586. ),
  587. etcdserverpb.Request{
  588. Method: "PUT",
  589. PrevValue: "miaow",
  590. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  591. },
  592. false,
  593. },
  594. {
  595. // noValueOnSuccess specified
  596. mustNewForm(
  597. t,
  598. "foo",
  599. url.Values{"noValueOnSuccess": []string{"true"}},
  600. ),
  601. etcdserverpb.Request{
  602. Method: "PUT",
  603. Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
  604. },
  605. true,
  606. },
  607. }
  608. for i, tt := range tests {
  609. got, noValueOnSuccess, err := parseKeyRequest(tt.in, fc)
  610. if err != nil {
  611. t.Errorf("#%d: err = %v, want %v", i, err, nil)
  612. }
  613. if noValueOnSuccess != tt.noValue {
  614. t.Errorf("#%d: noValue=%t, want %t", i, noValueOnSuccess, tt.noValue)
  615. }
  616. if !reflect.DeepEqual(got, tt.w) {
  617. t.Errorf("#%d: request=%#v, want %#v", i, got, tt.w)
  618. }
  619. }
  620. }
  621. func TestServeMembers(t *testing.T) {
  622. memb1 := membership.Member{ID: 12, Attributes: membership.Attributes{ClientURLs: []string{"http://localhost:8080"}}}
  623. memb2 := membership.Member{ID: 13, Attributes: membership.Attributes{ClientURLs: []string{"http://localhost:8081"}}}
  624. cluster := &fakeCluster{
  625. id: 1,
  626. members: map[uint64]*membership.Member{1: &memb1, 2: &memb2},
  627. }
  628. h := &membersHandler{
  629. server: &serverRecorder{},
  630. clock: clockwork.NewFakeClock(),
  631. cluster: cluster,
  632. }
  633. wmc := string(`{"members":[{"id":"c","name":"","peerURLs":[],"clientURLs":["http://localhost:8080"]},{"id":"d","name":"","peerURLs":[],"clientURLs":["http://localhost:8081"]}]}`)
  634. tests := []struct {
  635. path string
  636. wcode int
  637. wct string
  638. wbody string
  639. }{
  640. {membersPrefix, http.StatusOK, "application/json", wmc + "\n"},
  641. {membersPrefix + "/", http.StatusOK, "application/json", wmc + "\n"},
  642. {path.Join(membersPrefix, "100"), http.StatusNotFound, "application/json", `{"message":"Not found"}`},
  643. {path.Join(membersPrefix, "foobar"), http.StatusNotFound, "application/json", `{"message":"Not found"}`},
  644. }
  645. for i, tt := range tests {
  646. req, err := http.NewRequest("GET", testutil.MustNewURL(t, tt.path).String(), nil)
  647. if err != nil {
  648. t.Fatal(err)
  649. }
  650. rw := httptest.NewRecorder()
  651. h.ServeHTTP(rw, req)
  652. if rw.Code != tt.wcode {
  653. t.Errorf("#%d: code=%d, want %d", i, rw.Code, tt.wcode)
  654. }
  655. if gct := rw.Header().Get("Content-Type"); gct != tt.wct {
  656. t.Errorf("#%d: content-type = %s, want %s", i, gct, tt.wct)
  657. }
  658. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  659. wcid := cluster.ID().String()
  660. if gcid != wcid {
  661. t.Errorf("#%d: cid = %s, want %s", i, gcid, wcid)
  662. }
  663. if rw.Body.String() != tt.wbody {
  664. t.Errorf("#%d: body = %q, want %q", i, rw.Body.String(), tt.wbody)
  665. }
  666. }
  667. }
  668. // TODO: consolidate **ALL** fake server implementations and add no leader test case.
  669. func TestServeLeader(t *testing.T) {
  670. memb1 := membership.Member{ID: 1, Attributes: membership.Attributes{ClientURLs: []string{"http://localhost:8080"}}}
  671. memb2 := membership.Member{ID: 2, Attributes: membership.Attributes{ClientURLs: []string{"http://localhost:8081"}}}
  672. cluster := &fakeCluster{
  673. id: 1,
  674. members: map[uint64]*membership.Member{1: &memb1, 2: &memb2},
  675. }
  676. h := &membersHandler{
  677. server: &serverRecorder{},
  678. clock: clockwork.NewFakeClock(),
  679. cluster: cluster,
  680. }
  681. wmc := string(`{"id":"1","name":"","peerURLs":[],"clientURLs":["http://localhost:8080"]}`)
  682. tests := []struct {
  683. path string
  684. wcode int
  685. wct string
  686. wbody string
  687. }{
  688. {membersPrefix + "leader", http.StatusOK, "application/json", wmc + "\n"},
  689. // TODO: add no leader case
  690. }
  691. for i, tt := range tests {
  692. req, err := http.NewRequest("GET", testutil.MustNewURL(t, tt.path).String(), nil)
  693. if err != nil {
  694. t.Fatal(err)
  695. }
  696. rw := httptest.NewRecorder()
  697. h.ServeHTTP(rw, req)
  698. if rw.Code != tt.wcode {
  699. t.Errorf("#%d: code=%d, want %d", i, rw.Code, tt.wcode)
  700. }
  701. if gct := rw.Header().Get("Content-Type"); gct != tt.wct {
  702. t.Errorf("#%d: content-type = %s, want %s", i, gct, tt.wct)
  703. }
  704. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  705. wcid := cluster.ID().String()
  706. if gcid != wcid {
  707. t.Errorf("#%d: cid = %s, want %s", i, gcid, wcid)
  708. }
  709. if rw.Body.String() != tt.wbody {
  710. t.Errorf("#%d: body = %q, want %q", i, rw.Body.String(), tt.wbody)
  711. }
  712. }
  713. }
  714. func TestServeMembersCreate(t *testing.T) {
  715. u := testutil.MustNewURL(t, membersPrefix)
  716. b := []byte(`{"peerURLs":["http://127.0.0.1:1"]}`)
  717. req, err := http.NewRequest("POST", u.String(), bytes.NewReader(b))
  718. if err != nil {
  719. t.Fatal(err)
  720. }
  721. req.Header.Set("Content-Type", "application/json")
  722. s := &serverRecorder{}
  723. h := &membersHandler{
  724. server: s,
  725. clock: clockwork.NewFakeClock(),
  726. cluster: &fakeCluster{id: 1},
  727. }
  728. rw := httptest.NewRecorder()
  729. h.ServeHTTP(rw, req)
  730. wcode := http.StatusCreated
  731. if rw.Code != wcode {
  732. t.Errorf("code=%d, want %d", rw.Code, wcode)
  733. }
  734. wct := "application/json"
  735. if gct := rw.Header().Get("Content-Type"); gct != wct {
  736. t.Errorf("content-type = %s, want %s", gct, wct)
  737. }
  738. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  739. wcid := h.cluster.ID().String()
  740. if gcid != wcid {
  741. t.Errorf("cid = %s, want %s", gcid, wcid)
  742. }
  743. wb := `{"id":"c29b431f04be0bc7","name":"","peerURLs":["http://127.0.0.1:1"],"clientURLs":[]}` + "\n"
  744. g := rw.Body.String()
  745. if g != wb {
  746. t.Errorf("got body=%q, want %q", g, wb)
  747. }
  748. wm := membership.Member{
  749. ID: 14022875665250782151,
  750. RaftAttributes: membership.RaftAttributes{
  751. PeerURLs: []string{"http://127.0.0.1:1"},
  752. },
  753. }
  754. wactions := []action{{name: "AddMember", params: []interface{}{wm}}}
  755. if !reflect.DeepEqual(s.actions, wactions) {
  756. t.Errorf("actions = %+v, want %+v", s.actions, wactions)
  757. }
  758. }
  759. func TestServeMembersDelete(t *testing.T) {
  760. req := &http.Request{
  761. Method: "DELETE",
  762. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "BEEF")),
  763. }
  764. s := &serverRecorder{}
  765. h := &membersHandler{
  766. server: s,
  767. cluster: &fakeCluster{id: 1},
  768. }
  769. rw := httptest.NewRecorder()
  770. h.ServeHTTP(rw, req)
  771. wcode := http.StatusNoContent
  772. if rw.Code != wcode {
  773. t.Errorf("code=%d, want %d", rw.Code, wcode)
  774. }
  775. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  776. wcid := h.cluster.ID().String()
  777. if gcid != wcid {
  778. t.Errorf("cid = %s, want %s", gcid, wcid)
  779. }
  780. g := rw.Body.String()
  781. if g != "" {
  782. t.Errorf("got body=%q, want %q", g, "")
  783. }
  784. wactions := []action{{name: "RemoveMember", params: []interface{}{uint64(0xBEEF)}}}
  785. if !reflect.DeepEqual(s.actions, wactions) {
  786. t.Errorf("actions = %+v, want %+v", s.actions, wactions)
  787. }
  788. }
  789. func TestServeMembersUpdate(t *testing.T) {
  790. u := testutil.MustNewURL(t, path.Join(membersPrefix, "1"))
  791. b := []byte(`{"peerURLs":["http://127.0.0.1:1"]}`)
  792. req, err := http.NewRequest("PUT", u.String(), bytes.NewReader(b))
  793. if err != nil {
  794. t.Fatal(err)
  795. }
  796. req.Header.Set("Content-Type", "application/json")
  797. s := &serverRecorder{}
  798. h := &membersHandler{
  799. server: s,
  800. clock: clockwork.NewFakeClock(),
  801. cluster: &fakeCluster{id: 1},
  802. }
  803. rw := httptest.NewRecorder()
  804. h.ServeHTTP(rw, req)
  805. wcode := http.StatusNoContent
  806. if rw.Code != wcode {
  807. t.Errorf("code=%d, want %d", rw.Code, wcode)
  808. }
  809. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  810. wcid := h.cluster.ID().String()
  811. if gcid != wcid {
  812. t.Errorf("cid = %s, want %s", gcid, wcid)
  813. }
  814. wm := membership.Member{
  815. ID: 1,
  816. RaftAttributes: membership.RaftAttributes{
  817. PeerURLs: []string{"http://127.0.0.1:1"},
  818. },
  819. }
  820. wactions := []action{{name: "UpdateMember", params: []interface{}{wm}}}
  821. if !reflect.DeepEqual(s.actions, wactions) {
  822. t.Errorf("actions = %+v, want %+v", s.actions, wactions)
  823. }
  824. }
  825. func TestServeMembersFail(t *testing.T) {
  826. tests := []struct {
  827. req *http.Request
  828. server etcdserver.ServerV2
  829. wcode int
  830. }{
  831. {
  832. // bad method
  833. &http.Request{
  834. Method: "CONNECT",
  835. },
  836. &resServer{},
  837. http.StatusMethodNotAllowed,
  838. },
  839. {
  840. // bad method
  841. &http.Request{
  842. Method: "TRACE",
  843. },
  844. &resServer{},
  845. http.StatusMethodNotAllowed,
  846. },
  847. {
  848. // parse body error
  849. &http.Request{
  850. URL: testutil.MustNewURL(t, membersPrefix),
  851. Method: "POST",
  852. Body: ioutil.NopCloser(strings.NewReader("bad json")),
  853. Header: map[string][]string{"Content-Type": {"application/json"}},
  854. },
  855. &resServer{},
  856. http.StatusBadRequest,
  857. },
  858. {
  859. // bad content type
  860. &http.Request{
  861. URL: testutil.MustNewURL(t, membersPrefix),
  862. Method: "POST",
  863. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
  864. Header: map[string][]string{"Content-Type": {"application/bad"}},
  865. },
  866. &errServer{},
  867. http.StatusUnsupportedMediaType,
  868. },
  869. {
  870. // bad url
  871. &http.Request{
  872. URL: testutil.MustNewURL(t, membersPrefix),
  873. Method: "POST",
  874. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://a"]}`)),
  875. Header: map[string][]string{"Content-Type": {"application/json"}},
  876. },
  877. &errServer{},
  878. http.StatusBadRequest,
  879. },
  880. {
  881. // etcdserver.AddMember error
  882. &http.Request{
  883. URL: testutil.MustNewURL(t, membersPrefix),
  884. Method: "POST",
  885. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
  886. Header: map[string][]string{"Content-Type": {"application/json"}},
  887. },
  888. &errServer{
  889. err: errors.New("Error while adding a member"),
  890. },
  891. http.StatusInternalServerError,
  892. },
  893. {
  894. // etcdserver.AddMember error
  895. &http.Request{
  896. URL: testutil.MustNewURL(t, membersPrefix),
  897. Method: "POST",
  898. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
  899. Header: map[string][]string{"Content-Type": {"application/json"}},
  900. },
  901. &errServer{
  902. err: membership.ErrIDExists,
  903. },
  904. http.StatusConflict,
  905. },
  906. {
  907. // etcdserver.AddMember error
  908. &http.Request{
  909. URL: testutil.MustNewURL(t, membersPrefix),
  910. Method: "POST",
  911. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
  912. Header: map[string][]string{"Content-Type": {"application/json"}},
  913. },
  914. &errServer{
  915. err: membership.ErrPeerURLexists,
  916. },
  917. http.StatusConflict,
  918. },
  919. {
  920. // etcdserver.RemoveMember error with arbitrary server error
  921. &http.Request{
  922. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "1")),
  923. Method: "DELETE",
  924. },
  925. &errServer{
  926. err: errors.New("Error while removing member"),
  927. },
  928. http.StatusInternalServerError,
  929. },
  930. {
  931. // etcdserver.RemoveMember error with previously removed ID
  932. &http.Request{
  933. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
  934. Method: "DELETE",
  935. },
  936. &errServer{
  937. err: membership.ErrIDRemoved,
  938. },
  939. http.StatusGone,
  940. },
  941. {
  942. // etcdserver.RemoveMember error with nonexistent ID
  943. &http.Request{
  944. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
  945. Method: "DELETE",
  946. },
  947. &errServer{
  948. err: membership.ErrIDNotFound,
  949. },
  950. http.StatusNotFound,
  951. },
  952. {
  953. // etcdserver.RemoveMember error with badly formed ID
  954. &http.Request{
  955. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "bad_id")),
  956. Method: "DELETE",
  957. },
  958. nil,
  959. http.StatusNotFound,
  960. },
  961. {
  962. // etcdserver.RemoveMember with no ID
  963. &http.Request{
  964. URL: testutil.MustNewURL(t, membersPrefix),
  965. Method: "DELETE",
  966. },
  967. nil,
  968. http.StatusMethodNotAllowed,
  969. },
  970. {
  971. // parse body error
  972. &http.Request{
  973. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
  974. Method: "PUT",
  975. Body: ioutil.NopCloser(strings.NewReader("bad json")),
  976. Header: map[string][]string{"Content-Type": {"application/json"}},
  977. },
  978. &resServer{},
  979. http.StatusBadRequest,
  980. },
  981. {
  982. // bad content type
  983. &http.Request{
  984. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
  985. Method: "PUT",
  986. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
  987. Header: map[string][]string{"Content-Type": {"application/bad"}},
  988. },
  989. &errServer{},
  990. http.StatusUnsupportedMediaType,
  991. },
  992. {
  993. // bad url
  994. &http.Request{
  995. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
  996. Method: "PUT",
  997. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://a"]}`)),
  998. Header: map[string][]string{"Content-Type": {"application/json"}},
  999. },
  1000. &errServer{},
  1001. http.StatusBadRequest,
  1002. },
  1003. {
  1004. // etcdserver.UpdateMember error
  1005. &http.Request{
  1006. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
  1007. Method: "PUT",
  1008. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
  1009. Header: map[string][]string{"Content-Type": {"application/json"}},
  1010. },
  1011. &errServer{
  1012. err: errors.New("blah"),
  1013. },
  1014. http.StatusInternalServerError,
  1015. },
  1016. {
  1017. // etcdserver.UpdateMember error
  1018. &http.Request{
  1019. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
  1020. Method: "PUT",
  1021. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
  1022. Header: map[string][]string{"Content-Type": {"application/json"}},
  1023. },
  1024. &errServer{
  1025. err: membership.ErrPeerURLexists,
  1026. },
  1027. http.StatusConflict,
  1028. },
  1029. {
  1030. // etcdserver.UpdateMember error
  1031. &http.Request{
  1032. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
  1033. Method: "PUT",
  1034. Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
  1035. Header: map[string][]string{"Content-Type": {"application/json"}},
  1036. },
  1037. &errServer{
  1038. err: membership.ErrIDNotFound,
  1039. },
  1040. http.StatusNotFound,
  1041. },
  1042. {
  1043. // etcdserver.UpdateMember error with badly formed ID
  1044. &http.Request{
  1045. URL: testutil.MustNewURL(t, path.Join(membersPrefix, "bad_id")),
  1046. Method: "PUT",
  1047. },
  1048. nil,
  1049. http.StatusNotFound,
  1050. },
  1051. {
  1052. // etcdserver.UpdateMember with no ID
  1053. &http.Request{
  1054. URL: testutil.MustNewURL(t, membersPrefix),
  1055. Method: "PUT",
  1056. },
  1057. nil,
  1058. http.StatusMethodNotAllowed,
  1059. },
  1060. }
  1061. for i, tt := range tests {
  1062. h := &membersHandler{
  1063. server: tt.server,
  1064. cluster: &fakeCluster{id: 1},
  1065. clock: clockwork.NewFakeClock(),
  1066. }
  1067. rw := httptest.NewRecorder()
  1068. h.ServeHTTP(rw, tt.req)
  1069. if rw.Code != tt.wcode {
  1070. t.Errorf("#%d: code=%d, want %d", i, rw.Code, tt.wcode)
  1071. }
  1072. if rw.Code != http.StatusMethodNotAllowed {
  1073. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  1074. wcid := h.cluster.ID().String()
  1075. if gcid != wcid {
  1076. t.Errorf("#%d: cid = %s, want %s", i, gcid, wcid)
  1077. }
  1078. }
  1079. }
  1080. }
  1081. func TestWriteEvent(t *testing.T) {
  1082. // nil event should not panic
  1083. rec := httptest.NewRecorder()
  1084. writeKeyEvent(rec, etcdserver.Response{}, false)
  1085. h := rec.Header()
  1086. if len(h) > 0 {
  1087. t.Fatalf("unexpected non-empty headers: %#v", h)
  1088. }
  1089. b := rec.Body.String()
  1090. if len(b) > 0 {
  1091. t.Fatalf("unexpected non-empty body: %q", b)
  1092. }
  1093. tests := []struct {
  1094. ev *store.Event
  1095. noValue bool
  1096. idx string
  1097. // TODO(jonboulle): check body as well as just status code
  1098. code int
  1099. err error
  1100. }{
  1101. // standard case, standard 200 response
  1102. {
  1103. &store.Event{
  1104. Action: store.Get,
  1105. Node: &store.NodeExtern{},
  1106. PrevNode: &store.NodeExtern{},
  1107. },
  1108. false,
  1109. "0",
  1110. http.StatusOK,
  1111. nil,
  1112. },
  1113. // check new nodes return StatusCreated
  1114. {
  1115. &store.Event{
  1116. Action: store.Create,
  1117. Node: &store.NodeExtern{},
  1118. PrevNode: &store.NodeExtern{},
  1119. },
  1120. false,
  1121. "0",
  1122. http.StatusCreated,
  1123. nil,
  1124. },
  1125. }
  1126. for i, tt := range tests {
  1127. rw := httptest.NewRecorder()
  1128. resp := etcdserver.Response{Event: tt.ev, Term: 5, Index: 100}
  1129. writeKeyEvent(rw, resp, tt.noValue)
  1130. if gct := rw.Header().Get("Content-Type"); gct != "application/json" {
  1131. t.Errorf("case %d: bad Content-Type: got %q, want application/json", i, gct)
  1132. }
  1133. if gri := rw.Header().Get("X-Raft-Index"); gri != "100" {
  1134. t.Errorf("case %d: bad X-Raft-Index header: got %s, want %s", i, gri, "100")
  1135. }
  1136. if grt := rw.Header().Get("X-Raft-Term"); grt != "5" {
  1137. t.Errorf("case %d: bad X-Raft-Term header: got %s, want %s", i, grt, "5")
  1138. }
  1139. if gei := rw.Header().Get("X-Etcd-Index"); gei != tt.idx {
  1140. t.Errorf("case %d: bad X-Etcd-Index header: got %s, want %s", i, gei, tt.idx)
  1141. }
  1142. if rw.Code != tt.code {
  1143. t.Errorf("case %d: bad response code: got %d, want %v", i, rw.Code, tt.code)
  1144. }
  1145. }
  1146. }
  1147. func TestV2DMachinesEndpoint(t *testing.T) {
  1148. tests := []struct {
  1149. method string
  1150. wcode int
  1151. }{
  1152. {"GET", http.StatusOK},
  1153. {"HEAD", http.StatusOK},
  1154. {"POST", http.StatusMethodNotAllowed},
  1155. }
  1156. m := &machinesHandler{cluster: &fakeCluster{}}
  1157. s := httptest.NewServer(m)
  1158. defer s.Close()
  1159. for _, tt := range tests {
  1160. req, err := http.NewRequest(tt.method, s.URL+machinesPrefix, nil)
  1161. if err != nil {
  1162. t.Fatal(err)
  1163. }
  1164. resp, err := http.DefaultClient.Do(req)
  1165. if err != nil {
  1166. t.Fatal(err)
  1167. }
  1168. if resp.StatusCode != tt.wcode {
  1169. t.Errorf("StatusCode = %d, expected %d", resp.StatusCode, tt.wcode)
  1170. }
  1171. }
  1172. }
  1173. func TestServeMachines(t *testing.T) {
  1174. cluster := &fakeCluster{
  1175. clientURLs: []string{"http://localhost:8080", "http://localhost:8081", "http://localhost:8082"},
  1176. }
  1177. writer := httptest.NewRecorder()
  1178. req, err := http.NewRequest("GET", "", nil)
  1179. if err != nil {
  1180. t.Fatal(err)
  1181. }
  1182. h := &machinesHandler{cluster: cluster}
  1183. h.ServeHTTP(writer, req)
  1184. w := "http://localhost:8080, http://localhost:8081, http://localhost:8082"
  1185. if g := writer.Body.String(); g != w {
  1186. t.Errorf("body = %s, want %s", g, w)
  1187. }
  1188. if writer.Code != http.StatusOK {
  1189. t.Errorf("code = %d, want %d", writer.Code, http.StatusOK)
  1190. }
  1191. }
  1192. func TestGetID(t *testing.T) {
  1193. tests := []struct {
  1194. path string
  1195. wok bool
  1196. wid types.ID
  1197. wcode int
  1198. }{
  1199. {
  1200. "123",
  1201. true, 0x123, http.StatusOK,
  1202. },
  1203. {
  1204. "bad_id",
  1205. false, 0, http.StatusNotFound,
  1206. },
  1207. {
  1208. "",
  1209. false, 0, http.StatusMethodNotAllowed,
  1210. },
  1211. }
  1212. for i, tt := range tests {
  1213. w := httptest.NewRecorder()
  1214. id, ok := getID(tt.path, w)
  1215. if id != tt.wid {
  1216. t.Errorf("#%d: id = %d, want %d", i, id, tt.wid)
  1217. }
  1218. if ok != tt.wok {
  1219. t.Errorf("#%d: ok = %t, want %t", i, ok, tt.wok)
  1220. }
  1221. if w.Code != tt.wcode {
  1222. t.Errorf("#%d code = %d, want %d", i, w.Code, tt.wcode)
  1223. }
  1224. }
  1225. }
  1226. type dummyStats struct {
  1227. data []byte
  1228. }
  1229. func (ds *dummyStats) SelfStats() []byte { return ds.data }
  1230. func (ds *dummyStats) LeaderStats() []byte { return ds.data }
  1231. func (ds *dummyStats) StoreStats() []byte { return ds.data }
  1232. func (ds *dummyStats) UpdateRecvApp(_ types.ID, _ int64) {}
  1233. func TestServeSelfStats(t *testing.T) {
  1234. wb := []byte("some statistics")
  1235. w := string(wb)
  1236. sh := &statsHandler{
  1237. stats: &dummyStats{data: wb},
  1238. }
  1239. rw := httptest.NewRecorder()
  1240. sh.serveSelf(rw, &http.Request{Method: "GET"})
  1241. if rw.Code != http.StatusOK {
  1242. t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
  1243. }
  1244. wct := "application/json"
  1245. if gct := rw.Header().Get("Content-Type"); gct != wct {
  1246. t.Errorf("Content-Type = %q, want %q", gct, wct)
  1247. }
  1248. if g := rw.Body.String(); g != w {
  1249. t.Errorf("body = %s, want %s", g, w)
  1250. }
  1251. }
  1252. func TestSelfServeStatsBad(t *testing.T) {
  1253. for _, m := range []string{"PUT", "POST", "DELETE"} {
  1254. sh := &statsHandler{}
  1255. rw := httptest.NewRecorder()
  1256. sh.serveSelf(
  1257. rw,
  1258. &http.Request{
  1259. Method: m,
  1260. },
  1261. )
  1262. if rw.Code != http.StatusMethodNotAllowed {
  1263. t.Errorf("method %s: code=%d, want %d", m, rw.Code, http.StatusMethodNotAllowed)
  1264. }
  1265. }
  1266. }
  1267. func TestLeaderServeStatsBad(t *testing.T) {
  1268. for _, m := range []string{"PUT", "POST", "DELETE"} {
  1269. sh := &statsHandler{}
  1270. rw := httptest.NewRecorder()
  1271. sh.serveLeader(
  1272. rw,
  1273. &http.Request{
  1274. Method: m,
  1275. },
  1276. )
  1277. if rw.Code != http.StatusMethodNotAllowed {
  1278. t.Errorf("method %s: code=%d, want %d", m, rw.Code, http.StatusMethodNotAllowed)
  1279. }
  1280. }
  1281. }
  1282. func TestServeLeaderStats(t *testing.T) {
  1283. wb := []byte("some statistics")
  1284. w := string(wb)
  1285. sh := &statsHandler{
  1286. stats: &dummyStats{data: wb},
  1287. }
  1288. rw := httptest.NewRecorder()
  1289. sh.serveLeader(rw, &http.Request{Method: "GET"})
  1290. if rw.Code != http.StatusOK {
  1291. t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
  1292. }
  1293. wct := "application/json"
  1294. if gct := rw.Header().Get("Content-Type"); gct != wct {
  1295. t.Errorf("Content-Type = %q, want %q", gct, wct)
  1296. }
  1297. if g := rw.Body.String(); g != w {
  1298. t.Errorf("body = %s, want %s", g, w)
  1299. }
  1300. }
  1301. func TestServeStoreStats(t *testing.T) {
  1302. wb := []byte("some statistics")
  1303. w := string(wb)
  1304. sh := &statsHandler{
  1305. stats: &dummyStats{data: wb},
  1306. }
  1307. rw := httptest.NewRecorder()
  1308. sh.serveStore(rw, &http.Request{Method: "GET"})
  1309. if rw.Code != http.StatusOK {
  1310. t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
  1311. }
  1312. wct := "application/json"
  1313. if gct := rw.Header().Get("Content-Type"); gct != wct {
  1314. t.Errorf("Content-Type = %q, want %q", gct, wct)
  1315. }
  1316. if g := rw.Body.String(); g != w {
  1317. t.Errorf("body = %s, want %s", g, w)
  1318. }
  1319. }
  1320. func TestBadServeKeys(t *testing.T) {
  1321. testBadCases := []struct {
  1322. req *http.Request
  1323. server etcdserver.ServerV2
  1324. wcode int
  1325. wbody string
  1326. }{
  1327. {
  1328. // bad method
  1329. &http.Request{
  1330. Method: "CONNECT",
  1331. },
  1332. &resServer{},
  1333. http.StatusMethodNotAllowed,
  1334. "Method Not Allowed",
  1335. },
  1336. {
  1337. // bad method
  1338. &http.Request{
  1339. Method: "TRACE",
  1340. },
  1341. &resServer{},
  1342. http.StatusMethodNotAllowed,
  1343. "Method Not Allowed",
  1344. },
  1345. {
  1346. // parseRequest error
  1347. &http.Request{
  1348. Body: nil,
  1349. Method: "PUT",
  1350. },
  1351. &resServer{},
  1352. http.StatusBadRequest,
  1353. `{"errorCode":210,"message":"Invalid POST form","cause":"missing form body","index":0}`,
  1354. },
  1355. {
  1356. // etcdserver.Server error
  1357. mustNewRequest(t, "foo"),
  1358. &errServer{
  1359. err: errors.New("Internal Server Error"),
  1360. },
  1361. http.StatusInternalServerError,
  1362. `{"errorCode":300,"message":"Raft Internal Error","cause":"Internal Server Error","index":0}`,
  1363. },
  1364. {
  1365. // etcdserver.Server etcd error
  1366. mustNewRequest(t, "foo"),
  1367. &errServer{
  1368. err: etcdErr.NewError(etcdErr.EcodeKeyNotFound, "/1/pant", 0),
  1369. },
  1370. http.StatusNotFound,
  1371. `{"errorCode":100,"message":"Key not found","cause":"/pant","index":0}`,
  1372. },
  1373. {
  1374. // non-event/watcher response from etcdserver.Server
  1375. mustNewRequest(t, "foo"),
  1376. &resServer{
  1377. res: etcdserver.Response{},
  1378. },
  1379. http.StatusInternalServerError,
  1380. `{"errorCode":300,"message":"Raft Internal Error","cause":"received response with no Event/Watcher!","index":0}`,
  1381. },
  1382. }
  1383. for i, tt := range testBadCases {
  1384. h := &keysHandler{
  1385. timeout: 0, // context times out immediately
  1386. server: tt.server,
  1387. cluster: &fakeCluster{id: 1},
  1388. }
  1389. rw := httptest.NewRecorder()
  1390. h.ServeHTTP(rw, tt.req)
  1391. if rw.Code != tt.wcode {
  1392. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  1393. }
  1394. if rw.Code != http.StatusMethodNotAllowed {
  1395. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  1396. wcid := h.cluster.ID().String()
  1397. if gcid != wcid {
  1398. t.Errorf("#%d: cid = %s, want %s", i, gcid, wcid)
  1399. }
  1400. }
  1401. if g := strings.TrimSuffix(rw.Body.String(), "\n"); g != tt.wbody {
  1402. t.Errorf("#%d: body = %s, want %s", i, g, tt.wbody)
  1403. }
  1404. }
  1405. }
  1406. func TestServeKeysGood(t *testing.T) {
  1407. tests := []struct {
  1408. req *http.Request
  1409. wcode int
  1410. }{
  1411. {
  1412. mustNewMethodRequest(t, "HEAD", "foo"),
  1413. http.StatusOK,
  1414. },
  1415. {
  1416. mustNewMethodRequest(t, "GET", "foo"),
  1417. http.StatusOK,
  1418. },
  1419. {
  1420. mustNewForm(t, "foo", url.Values{"value": []string{"bar"}}),
  1421. http.StatusOK,
  1422. },
  1423. {
  1424. mustNewMethodRequest(t, "DELETE", "foo"),
  1425. http.StatusOK,
  1426. },
  1427. {
  1428. mustNewPostForm(t, "foo", url.Values{"value": []string{"bar"}}),
  1429. http.StatusOK,
  1430. },
  1431. }
  1432. server := &resServer{
  1433. res: etcdserver.Response{
  1434. Event: &store.Event{
  1435. Action: store.Get,
  1436. Node: &store.NodeExtern{},
  1437. },
  1438. },
  1439. }
  1440. for i, tt := range tests {
  1441. h := &keysHandler{
  1442. timeout: time.Hour,
  1443. server: server,
  1444. cluster: &fakeCluster{id: 1},
  1445. }
  1446. rw := httptest.NewRecorder()
  1447. h.ServeHTTP(rw, tt.req)
  1448. if rw.Code != tt.wcode {
  1449. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  1450. }
  1451. }
  1452. }
  1453. func TestServeKeysEvent(t *testing.T) {
  1454. tests := []struct {
  1455. req *http.Request
  1456. rsp etcdserver.Response
  1457. wcode int
  1458. event *store.Event
  1459. }{
  1460. {
  1461. mustNewRequest(t, "foo"),
  1462. etcdserver.Response{
  1463. Event: &store.Event{
  1464. Action: store.Get,
  1465. Node: &store.NodeExtern{},
  1466. },
  1467. },
  1468. http.StatusOK,
  1469. &store.Event{
  1470. Action: store.Get,
  1471. Node: &store.NodeExtern{},
  1472. },
  1473. },
  1474. {
  1475. mustNewForm(
  1476. t,
  1477. "foo",
  1478. url.Values{"noValueOnSuccess": []string{"true"}},
  1479. ),
  1480. etcdserver.Response{
  1481. Event: &store.Event{
  1482. Action: store.CompareAndSwap,
  1483. Node: &store.NodeExtern{},
  1484. },
  1485. },
  1486. http.StatusOK,
  1487. &store.Event{
  1488. Action: store.CompareAndSwap,
  1489. Node: nil,
  1490. },
  1491. },
  1492. }
  1493. server := &resServer{}
  1494. h := &keysHandler{
  1495. timeout: time.Hour,
  1496. server: server,
  1497. cluster: &fakeCluster{id: 1},
  1498. }
  1499. for _, tt := range tests {
  1500. server.res = tt.rsp
  1501. rw := httptest.NewRecorder()
  1502. h.ServeHTTP(rw, tt.req)
  1503. wbody := mustMarshalEvent(
  1504. t,
  1505. tt.event,
  1506. )
  1507. if rw.Code != tt.wcode {
  1508. t.Errorf("got code=%d, want %d", rw.Code, tt.wcode)
  1509. }
  1510. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  1511. wcid := h.cluster.ID().String()
  1512. if gcid != wcid {
  1513. t.Errorf("cid = %s, want %s", gcid, wcid)
  1514. }
  1515. g := rw.Body.String()
  1516. if g != wbody {
  1517. t.Errorf("got body=%#v, want %#v", g, wbody)
  1518. }
  1519. }
  1520. }
  1521. func TestServeKeysWatch(t *testing.T) {
  1522. req := mustNewRequest(t, "/foo/bar")
  1523. ec := make(chan *store.Event)
  1524. dw := &dummyWatcher{
  1525. echan: ec,
  1526. }
  1527. server := &resServer{
  1528. res: etcdserver.Response{
  1529. Watcher: dw,
  1530. },
  1531. }
  1532. h := &keysHandler{
  1533. timeout: time.Hour,
  1534. server: server,
  1535. cluster: &fakeCluster{id: 1},
  1536. }
  1537. go func() {
  1538. ec <- &store.Event{
  1539. Action: store.Get,
  1540. Node: &store.NodeExtern{},
  1541. }
  1542. }()
  1543. rw := httptest.NewRecorder()
  1544. h.ServeHTTP(rw, req)
  1545. wcode := http.StatusOK
  1546. wbody := mustMarshalEvent(
  1547. t,
  1548. &store.Event{
  1549. Action: store.Get,
  1550. Node: &store.NodeExtern{},
  1551. },
  1552. )
  1553. if rw.Code != wcode {
  1554. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1555. }
  1556. gcid := rw.Header().Get("X-Etcd-Cluster-ID")
  1557. wcid := h.cluster.ID().String()
  1558. if gcid != wcid {
  1559. t.Errorf("cid = %s, want %s", gcid, wcid)
  1560. }
  1561. g := rw.Body.String()
  1562. if g != wbody {
  1563. t.Errorf("got body=%#v, want %#v", g, wbody)
  1564. }
  1565. }
  1566. type recordingCloseNotifier struct {
  1567. *httptest.ResponseRecorder
  1568. cn chan bool
  1569. }
  1570. func (rcn *recordingCloseNotifier) CloseNotify() <-chan bool {
  1571. return rcn.cn
  1572. }
  1573. func TestHandleWatch(t *testing.T) {
  1574. defaultRwRr := func() (http.ResponseWriter, *httptest.ResponseRecorder) {
  1575. r := httptest.NewRecorder()
  1576. return r, r
  1577. }
  1578. noopEv := func(chan *store.Event) {}
  1579. tests := []struct {
  1580. getCtx func() context.Context
  1581. getRwRr func() (http.ResponseWriter, *httptest.ResponseRecorder)
  1582. doToChan func(chan *store.Event)
  1583. wbody string
  1584. }{
  1585. {
  1586. // Normal case: one event
  1587. context.Background,
  1588. defaultRwRr,
  1589. func(ch chan *store.Event) {
  1590. ch <- &store.Event{
  1591. Action: store.Get,
  1592. Node: &store.NodeExtern{},
  1593. }
  1594. },
  1595. mustMarshalEvent(
  1596. t,
  1597. &store.Event{
  1598. Action: store.Get,
  1599. Node: &store.NodeExtern{},
  1600. },
  1601. ),
  1602. },
  1603. {
  1604. // Channel is closed, no event
  1605. context.Background,
  1606. defaultRwRr,
  1607. func(ch chan *store.Event) {
  1608. close(ch)
  1609. },
  1610. "",
  1611. },
  1612. {
  1613. // Simulate a timed-out context
  1614. func() context.Context {
  1615. ctx, cancel := context.WithCancel(context.Background())
  1616. cancel()
  1617. return ctx
  1618. },
  1619. defaultRwRr,
  1620. noopEv,
  1621. "",
  1622. },
  1623. {
  1624. // Close-notifying request
  1625. context.Background,
  1626. func() (http.ResponseWriter, *httptest.ResponseRecorder) {
  1627. rw := &recordingCloseNotifier{
  1628. ResponseRecorder: httptest.NewRecorder(),
  1629. cn: make(chan bool, 1),
  1630. }
  1631. rw.cn <- true
  1632. return rw, rw.ResponseRecorder
  1633. },
  1634. noopEv,
  1635. "",
  1636. },
  1637. }
  1638. for i, tt := range tests {
  1639. rw, rr := tt.getRwRr()
  1640. wa := &dummyWatcher{
  1641. echan: make(chan *store.Event, 1),
  1642. sidx: 10,
  1643. }
  1644. tt.doToChan(wa.echan)
  1645. resp := etcdserver.Response{Term: 5, Index: 100, Watcher: wa}
  1646. handleKeyWatch(tt.getCtx(), rw, resp, false)
  1647. wcode := http.StatusOK
  1648. wct := "application/json"
  1649. wei := "10"
  1650. wri := "100"
  1651. wrt := "5"
  1652. if rr.Code != wcode {
  1653. t.Errorf("#%d: got code=%d, want %d", i, rr.Code, wcode)
  1654. }
  1655. h := rr.Header()
  1656. if ct := h.Get("Content-Type"); ct != wct {
  1657. t.Errorf("#%d: Content-Type=%q, want %q", i, ct, wct)
  1658. }
  1659. if ei := h.Get("X-Etcd-Index"); ei != wei {
  1660. t.Errorf("#%d: X-Etcd-Index=%q, want %q", i, ei, wei)
  1661. }
  1662. if ri := h.Get("X-Raft-Index"); ri != wri {
  1663. t.Errorf("#%d: X-Raft-Index=%q, want %q", i, ri, wri)
  1664. }
  1665. if rt := h.Get("X-Raft-Term"); rt != wrt {
  1666. t.Errorf("#%d: X-Raft-Term=%q, want %q", i, rt, wrt)
  1667. }
  1668. g := rr.Body.String()
  1669. if g != tt.wbody {
  1670. t.Errorf("#%d: got body=%#v, want %#v", i, g, tt.wbody)
  1671. }
  1672. }
  1673. }
  1674. func TestHandleWatchStreaming(t *testing.T) {
  1675. rw := &flushingRecorder{
  1676. httptest.NewRecorder(),
  1677. make(chan struct{}, 1),
  1678. }
  1679. wa := &dummyWatcher{
  1680. echan: make(chan *store.Event),
  1681. }
  1682. // Launch the streaming handler in the background with a cancellable context
  1683. ctx, cancel := context.WithCancel(context.Background())
  1684. done := make(chan struct{})
  1685. go func() {
  1686. resp := etcdserver.Response{Watcher: wa}
  1687. handleKeyWatch(ctx, rw, resp, true)
  1688. close(done)
  1689. }()
  1690. // Expect one Flush for the headers etc.
  1691. select {
  1692. case <-rw.ch:
  1693. case <-time.After(time.Second):
  1694. t.Fatalf("timed out waiting for flush")
  1695. }
  1696. // Expect headers but no body
  1697. wcode := http.StatusOK
  1698. wct := "application/json"
  1699. wbody := ""
  1700. if rw.Code != wcode {
  1701. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1702. }
  1703. h := rw.Header()
  1704. if ct := h.Get("Content-Type"); ct != wct {
  1705. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1706. }
  1707. g := rw.Body.String()
  1708. if g != wbody {
  1709. t.Errorf("got body=%#v, want %#v", g, wbody)
  1710. }
  1711. // Now send the first event
  1712. select {
  1713. case wa.echan <- &store.Event{
  1714. Action: store.Get,
  1715. Node: &store.NodeExtern{},
  1716. }:
  1717. case <-time.After(time.Second):
  1718. t.Fatal("timed out waiting for send")
  1719. }
  1720. // Wait for it to be flushed...
  1721. select {
  1722. case <-rw.ch:
  1723. case <-time.After(time.Second):
  1724. t.Fatalf("timed out waiting for flush")
  1725. }
  1726. // And check the body is as expected
  1727. wbody = mustMarshalEvent(
  1728. t,
  1729. &store.Event{
  1730. Action: store.Get,
  1731. Node: &store.NodeExtern{},
  1732. },
  1733. )
  1734. g = rw.Body.String()
  1735. if g != wbody {
  1736. t.Errorf("got body=%#v, want %#v", g, wbody)
  1737. }
  1738. // Rinse and repeat
  1739. select {
  1740. case wa.echan <- &store.Event{
  1741. Action: store.Get,
  1742. Node: &store.NodeExtern{},
  1743. }:
  1744. case <-time.After(time.Second):
  1745. t.Fatal("timed out waiting for send")
  1746. }
  1747. select {
  1748. case <-rw.ch:
  1749. case <-time.After(time.Second):
  1750. t.Fatalf("timed out waiting for flush")
  1751. }
  1752. // This time, we expect to see both events
  1753. wbody = wbody + wbody
  1754. g = rw.Body.String()
  1755. if g != wbody {
  1756. t.Errorf("got body=%#v, want %#v", g, wbody)
  1757. }
  1758. // Finally, time out the connection and ensure the serving goroutine returns
  1759. cancel()
  1760. select {
  1761. case <-done:
  1762. case <-time.After(time.Second):
  1763. t.Fatalf("timed out waiting for done")
  1764. }
  1765. }
  1766. func TestTrimEventPrefix(t *testing.T) {
  1767. pre := "/abc"
  1768. tests := []struct {
  1769. ev *store.Event
  1770. wev *store.Event
  1771. }{
  1772. {
  1773. nil,
  1774. nil,
  1775. },
  1776. {
  1777. &store.Event{},
  1778. &store.Event{},
  1779. },
  1780. {
  1781. &store.Event{Node: &store.NodeExtern{Key: "/abc/def"}},
  1782. &store.Event{Node: &store.NodeExtern{Key: "/def"}},
  1783. },
  1784. {
  1785. &store.Event{PrevNode: &store.NodeExtern{Key: "/abc/ghi"}},
  1786. &store.Event{PrevNode: &store.NodeExtern{Key: "/ghi"}},
  1787. },
  1788. {
  1789. &store.Event{
  1790. Node: &store.NodeExtern{Key: "/abc/def"},
  1791. PrevNode: &store.NodeExtern{Key: "/abc/ghi"},
  1792. },
  1793. &store.Event{
  1794. Node: &store.NodeExtern{Key: "/def"},
  1795. PrevNode: &store.NodeExtern{Key: "/ghi"},
  1796. },
  1797. },
  1798. }
  1799. for i, tt := range tests {
  1800. ev := trimEventPrefix(tt.ev, pre)
  1801. if !reflect.DeepEqual(ev, tt.wev) {
  1802. t.Errorf("#%d: event = %+v, want %+v", i, ev, tt.wev)
  1803. }
  1804. }
  1805. }
  1806. func TestTrimNodeExternPrefix(t *testing.T) {
  1807. pre := "/abc"
  1808. tests := []struct {
  1809. n *store.NodeExtern
  1810. wn *store.NodeExtern
  1811. }{
  1812. {
  1813. nil,
  1814. nil,
  1815. },
  1816. {
  1817. &store.NodeExtern{Key: "/abc/def"},
  1818. &store.NodeExtern{Key: "/def"},
  1819. },
  1820. {
  1821. &store.NodeExtern{
  1822. Key: "/abc/def",
  1823. Nodes: []*store.NodeExtern{
  1824. {Key: "/abc/def/1"},
  1825. {Key: "/abc/def/2"},
  1826. },
  1827. },
  1828. &store.NodeExtern{
  1829. Key: "/def",
  1830. Nodes: []*store.NodeExtern{
  1831. {Key: "/def/1"},
  1832. {Key: "/def/2"},
  1833. },
  1834. },
  1835. },
  1836. }
  1837. for i, tt := range tests {
  1838. trimNodeExternPrefix(tt.n, pre)
  1839. if !reflect.DeepEqual(tt.n, tt.wn) {
  1840. t.Errorf("#%d: node = %+v, want %+v", i, tt.n, tt.wn)
  1841. }
  1842. }
  1843. }
  1844. func TestTrimPrefix(t *testing.T) {
  1845. tests := []struct {
  1846. in string
  1847. prefix string
  1848. w string
  1849. }{
  1850. {"/v2/members", "/v2/members", ""},
  1851. {"/v2/members/", "/v2/members", ""},
  1852. {"/v2/members/foo", "/v2/members", "foo"},
  1853. }
  1854. for i, tt := range tests {
  1855. if g := trimPrefix(tt.in, tt.prefix); g != tt.w {
  1856. t.Errorf("#%d: trimPrefix = %q, want %q", i, g, tt.w)
  1857. }
  1858. }
  1859. }
  1860. func TestNewMemberCollection(t *testing.T) {
  1861. fixture := []*membership.Member{
  1862. {
  1863. ID: 12,
  1864. Attributes: membership.Attributes{ClientURLs: []string{"http://localhost:8080", "http://localhost:8081"}},
  1865. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:8082", "http://localhost:8083"}},
  1866. },
  1867. {
  1868. ID: 13,
  1869. Attributes: membership.Attributes{ClientURLs: []string{"http://localhost:9090", "http://localhost:9091"}},
  1870. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:9092", "http://localhost:9093"}},
  1871. },
  1872. }
  1873. got := newMemberCollection(fixture)
  1874. want := httptypes.MemberCollection([]httptypes.Member{
  1875. {
  1876. ID: "c",
  1877. ClientURLs: []string{"http://localhost:8080", "http://localhost:8081"},
  1878. PeerURLs: []string{"http://localhost:8082", "http://localhost:8083"},
  1879. },
  1880. {
  1881. ID: "d",
  1882. ClientURLs: []string{"http://localhost:9090", "http://localhost:9091"},
  1883. PeerURLs: []string{"http://localhost:9092", "http://localhost:9093"},
  1884. },
  1885. })
  1886. if !reflect.DeepEqual(&want, got) {
  1887. t.Fatalf("newMemberCollection failure: want=%#v, got=%#v", &want, got)
  1888. }
  1889. }
  1890. func TestNewMember(t *testing.T) {
  1891. fixture := &membership.Member{
  1892. ID: 12,
  1893. Attributes: membership.Attributes{ClientURLs: []string{"http://localhost:8080", "http://localhost:8081"}},
  1894. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:8082", "http://localhost:8083"}},
  1895. }
  1896. got := newMember(fixture)
  1897. want := httptypes.Member{
  1898. ID: "c",
  1899. ClientURLs: []string{"http://localhost:8080", "http://localhost:8081"},
  1900. PeerURLs: []string{"http://localhost:8082", "http://localhost:8083"},
  1901. }
  1902. if !reflect.DeepEqual(want, got) {
  1903. t.Fatalf("newMember failure: want=%#v, got=%#v", want, got)
  1904. }
  1905. }