client_test.go 49 KB

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