http_test.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  1. package etcdhttp
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "net/http/httptest"
  10. "net/url"
  11. "path"
  12. "reflect"
  13. "strings"
  14. "testing"
  15. "time"
  16. "github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
  17. etcdErr "github.com/coreos/etcd/error"
  18. "github.com/coreos/etcd/etcdserver"
  19. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  20. "github.com/coreos/etcd/etcdserver/stats"
  21. "github.com/coreos/etcd/raft/raftpb"
  22. "github.com/coreos/etcd/store"
  23. )
  24. func boolp(b bool) *bool { return &b }
  25. func mustNewURL(t *testing.T, s string) *url.URL {
  26. u, err := url.Parse(s)
  27. if err != nil {
  28. t.Fatalf("error creating URL from %q: %v", s, err)
  29. }
  30. return u
  31. }
  32. // mustNewRequest takes a path, appends it to the standard keysPrefix, and constructs
  33. // a GET *http.Request referencing the resulting URL
  34. func mustNewRequest(t *testing.T, p string) *http.Request {
  35. return mustNewMethodRequest(t, "GET", p)
  36. }
  37. func mustNewMethodRequest(t *testing.T, m, p string) *http.Request {
  38. return &http.Request{
  39. Method: m,
  40. URL: mustNewURL(t, path.Join(keysPrefix, p)),
  41. }
  42. }
  43. // mustNewForm takes a set of Values and constructs a PUT *http.Request,
  44. // with a URL constructed from appending the given path to the standard keysPrefix
  45. func mustNewForm(t *testing.T, p string, vals url.Values) *http.Request {
  46. u := mustNewURL(t, path.Join(keysPrefix, p))
  47. req, err := http.NewRequest("PUT", u.String(), strings.NewReader(vals.Encode()))
  48. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  49. if err != nil {
  50. t.Fatalf("error creating new request: %v", err)
  51. }
  52. return req
  53. }
  54. func TestBadParseRequest(t *testing.T) {
  55. tests := []struct {
  56. in *http.Request
  57. wcode int
  58. }{
  59. {
  60. // parseForm failure
  61. &http.Request{
  62. Body: nil,
  63. Method: "PUT",
  64. },
  65. etcdErr.EcodeInvalidForm,
  66. },
  67. {
  68. // bad key prefix
  69. &http.Request{
  70. URL: mustNewURL(t, "/badprefix/"),
  71. },
  72. etcdErr.EcodeInvalidForm,
  73. },
  74. // bad values for prevIndex, waitIndex, ttl
  75. {
  76. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"garbage"}}),
  77. etcdErr.EcodeIndexNaN,
  78. },
  79. {
  80. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"1.5"}}),
  81. etcdErr.EcodeIndexNaN,
  82. },
  83. {
  84. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"-1"}}),
  85. etcdErr.EcodeIndexNaN,
  86. },
  87. {
  88. mustNewForm(t, "foo", url.Values{"waitIndex": []string{"garbage"}}),
  89. etcdErr.EcodeIndexNaN,
  90. },
  91. {
  92. mustNewForm(t, "foo", url.Values{"waitIndex": []string{"??"}}),
  93. etcdErr.EcodeIndexNaN,
  94. },
  95. {
  96. mustNewForm(t, "foo", url.Values{"ttl": []string{"-1"}}),
  97. etcdErr.EcodeTTLNaN,
  98. },
  99. // bad values for recursive, sorted, wait, prevExist, dir, stream
  100. {
  101. mustNewForm(t, "foo", url.Values{"recursive": []string{"hahaha"}}),
  102. etcdErr.EcodeInvalidField,
  103. },
  104. {
  105. mustNewForm(t, "foo", url.Values{"recursive": []string{"1234"}}),
  106. etcdErr.EcodeInvalidField,
  107. },
  108. {
  109. mustNewForm(t, "foo", url.Values{"recursive": []string{"?"}}),
  110. etcdErr.EcodeInvalidField,
  111. },
  112. {
  113. mustNewForm(t, "foo", url.Values{"sorted": []string{"?"}}),
  114. etcdErr.EcodeInvalidField,
  115. },
  116. {
  117. mustNewForm(t, "foo", url.Values{"sorted": []string{"x"}}),
  118. etcdErr.EcodeInvalidField,
  119. },
  120. {
  121. mustNewForm(t, "foo", url.Values{"wait": []string{"?!"}}),
  122. etcdErr.EcodeInvalidField,
  123. },
  124. {
  125. mustNewForm(t, "foo", url.Values{"wait": []string{"yes"}}),
  126. etcdErr.EcodeInvalidField,
  127. },
  128. {
  129. mustNewForm(t, "foo", url.Values{"prevExist": []string{"yes"}}),
  130. etcdErr.EcodeInvalidField,
  131. },
  132. {
  133. mustNewForm(t, "foo", url.Values{"prevExist": []string{"#2"}}),
  134. etcdErr.EcodeInvalidField,
  135. },
  136. {
  137. mustNewForm(t, "foo", url.Values{"dir": []string{"no"}}),
  138. etcdErr.EcodeInvalidField,
  139. },
  140. {
  141. mustNewForm(t, "foo", url.Values{"dir": []string{"file"}}),
  142. etcdErr.EcodeInvalidField,
  143. },
  144. {
  145. mustNewForm(t, "foo", url.Values{"stream": []string{"zzz"}}),
  146. etcdErr.EcodeInvalidField,
  147. },
  148. {
  149. mustNewForm(t, "foo", url.Values{"stream": []string{"something"}}),
  150. etcdErr.EcodeInvalidField,
  151. },
  152. // prevValue cannot be empty
  153. {
  154. mustNewForm(t, "foo", url.Values{"prevValue": []string{""}}),
  155. etcdErr.EcodeInvalidField,
  156. },
  157. // wait is only valid with GET requests
  158. {
  159. mustNewMethodRequest(t, "HEAD", "foo?wait=true"),
  160. etcdErr.EcodeInvalidField,
  161. },
  162. // query values are considered
  163. {
  164. mustNewRequest(t, "foo?prevExist=wrong"),
  165. etcdErr.EcodeInvalidField,
  166. },
  167. {
  168. mustNewRequest(t, "foo?ttl=wrong"),
  169. etcdErr.EcodeTTLNaN,
  170. },
  171. // but body takes precedence if both are specified
  172. {
  173. mustNewForm(
  174. t,
  175. "foo?ttl=12",
  176. url.Values{"ttl": []string{"garbage"}},
  177. ),
  178. etcdErr.EcodeTTLNaN,
  179. },
  180. {
  181. mustNewForm(
  182. t,
  183. "foo?prevExist=false",
  184. url.Values{"prevExist": []string{"yes"}},
  185. ),
  186. etcdErr.EcodeInvalidField,
  187. },
  188. }
  189. for i, tt := range tests {
  190. got, err := parseRequest(tt.in, 1234)
  191. if err == nil {
  192. t.Errorf("#%d: unexpected nil error!", i)
  193. continue
  194. }
  195. ee, ok := err.(*etcdErr.Error)
  196. if !ok {
  197. t.Errorf("#%d: err is not etcd.Error!", i)
  198. continue
  199. }
  200. if ee.ErrorCode != tt.wcode {
  201. t.Errorf("#%d: code=%d, want %v", i, ee.ErrorCode, tt.wcode)
  202. t.Logf("cause: %#v", ee.Cause)
  203. }
  204. if !reflect.DeepEqual(got, etcdserverpb.Request{}) {
  205. t.Errorf("#%d: unexpected non-empty Request: %#v", i, got)
  206. }
  207. }
  208. }
  209. func TestGoodParseRequest(t *testing.T) {
  210. tests := []struct {
  211. in *http.Request
  212. w etcdserverpb.Request
  213. }{
  214. {
  215. // good prefix, all other values default
  216. mustNewRequest(t, "foo"),
  217. etcdserverpb.Request{
  218. ID: 1234,
  219. Method: "GET",
  220. Path: "/foo",
  221. },
  222. },
  223. {
  224. // value specified
  225. mustNewForm(
  226. t,
  227. "foo",
  228. url.Values{"value": []string{"some_value"}},
  229. ),
  230. etcdserverpb.Request{
  231. ID: 1234,
  232. Method: "PUT",
  233. Val: "some_value",
  234. Path: "/foo",
  235. },
  236. },
  237. {
  238. // prevIndex specified
  239. mustNewForm(
  240. t,
  241. "foo",
  242. url.Values{"prevIndex": []string{"98765"}},
  243. ),
  244. etcdserverpb.Request{
  245. ID: 1234,
  246. Method: "PUT",
  247. PrevIndex: 98765,
  248. Path: "/foo",
  249. },
  250. },
  251. {
  252. // recursive specified
  253. mustNewForm(
  254. t,
  255. "foo",
  256. url.Values{"recursive": []string{"true"}},
  257. ),
  258. etcdserverpb.Request{
  259. ID: 1234,
  260. Method: "PUT",
  261. Recursive: true,
  262. Path: "/foo",
  263. },
  264. },
  265. {
  266. // sorted specified
  267. mustNewForm(
  268. t,
  269. "foo",
  270. url.Values{"sorted": []string{"true"}},
  271. ),
  272. etcdserverpb.Request{
  273. ID: 1234,
  274. Method: "PUT",
  275. Sorted: true,
  276. Path: "/foo",
  277. },
  278. },
  279. {
  280. // wait specified
  281. mustNewRequest(t, "foo?wait=true"),
  282. etcdserverpb.Request{
  283. ID: 1234,
  284. Method: "GET",
  285. Wait: true,
  286. Path: "/foo",
  287. },
  288. },
  289. {
  290. // empty TTL specified
  291. mustNewRequest(t, "foo?ttl="),
  292. etcdserverpb.Request{
  293. ID: 1234,
  294. Method: "GET",
  295. Path: "/foo",
  296. Expiration: 0,
  297. },
  298. },
  299. {
  300. // dir specified
  301. mustNewRequest(t, "foo?dir=true"),
  302. etcdserverpb.Request{
  303. ID: 1234,
  304. Method: "GET",
  305. Dir: true,
  306. Path: "/foo",
  307. },
  308. },
  309. {
  310. // dir specified negatively
  311. mustNewRequest(t, "foo?dir=false"),
  312. etcdserverpb.Request{
  313. ID: 1234,
  314. Method: "GET",
  315. Dir: false,
  316. Path: "/foo",
  317. },
  318. },
  319. {
  320. // prevExist should be non-null if specified
  321. mustNewForm(
  322. t,
  323. "foo",
  324. url.Values{"prevExist": []string{"true"}},
  325. ),
  326. etcdserverpb.Request{
  327. ID: 1234,
  328. Method: "PUT",
  329. PrevExist: boolp(true),
  330. Path: "/foo",
  331. },
  332. },
  333. {
  334. // prevExist should be non-null if specified
  335. mustNewForm(
  336. t,
  337. "foo",
  338. url.Values{"prevExist": []string{"false"}},
  339. ),
  340. etcdserverpb.Request{
  341. ID: 1234,
  342. Method: "PUT",
  343. PrevExist: boolp(false),
  344. Path: "/foo",
  345. },
  346. },
  347. // mix various fields
  348. {
  349. mustNewForm(
  350. t,
  351. "foo",
  352. url.Values{
  353. "value": []string{"some value"},
  354. "prevExist": []string{"true"},
  355. "prevValue": []string{"previous value"},
  356. },
  357. ),
  358. etcdserverpb.Request{
  359. ID: 1234,
  360. Method: "PUT",
  361. PrevExist: boolp(true),
  362. PrevValue: "previous value",
  363. Val: "some value",
  364. Path: "/foo",
  365. },
  366. },
  367. // query parameters should be used if given
  368. {
  369. mustNewForm(
  370. t,
  371. "foo?prevValue=woof",
  372. url.Values{},
  373. ),
  374. etcdserverpb.Request{
  375. ID: 1234,
  376. Method: "PUT",
  377. PrevValue: "woof",
  378. Path: "/foo",
  379. },
  380. },
  381. // but form values should take precedence over query parameters
  382. {
  383. mustNewForm(
  384. t,
  385. "foo?prevValue=woof",
  386. url.Values{
  387. "prevValue": []string{"miaow"},
  388. },
  389. ),
  390. etcdserverpb.Request{
  391. ID: 1234,
  392. Method: "PUT",
  393. PrevValue: "miaow",
  394. Path: "/foo",
  395. },
  396. },
  397. }
  398. for i, tt := range tests {
  399. got, err := parseRequest(tt.in, 1234)
  400. if err != nil {
  401. t.Errorf("#%d: err = %v, want %v", i, err, nil)
  402. }
  403. if !reflect.DeepEqual(got, tt.w) {
  404. t.Errorf("#%d: request=%#v, want %#v", i, got, tt.w)
  405. }
  406. }
  407. // Test TTL separately until we don't rely on the time module...
  408. now := time.Now().UnixNano()
  409. req := mustNewForm(t, "foo", url.Values{"ttl": []string{"100"}})
  410. got, err := parseRequest(req, 1234)
  411. if err != nil {
  412. t.Fatalf("err = %v, want nil", err)
  413. }
  414. if got.Expiration <= now {
  415. t.Fatalf("expiration = %v, wanted > %v", got.Expiration, now)
  416. }
  417. // ensure TTL=0 results in an expiration time
  418. req = mustNewForm(t, "foo", url.Values{"ttl": []string{"0"}})
  419. got, err = parseRequest(req, 1234)
  420. if err != nil {
  421. t.Fatalf("err = %v, want nil", err)
  422. }
  423. if got.Expiration <= now {
  424. t.Fatalf("expiration = %v, wanted > %v", got.Expiration, now)
  425. }
  426. }
  427. // eventingWatcher immediately returns a simple event of the given action on its channel
  428. type eventingWatcher struct {
  429. action string
  430. }
  431. func (w *eventingWatcher) EventChan() chan *store.Event {
  432. ch := make(chan *store.Event)
  433. go func() {
  434. ch <- &store.Event{
  435. Action: w.action,
  436. Node: &store.NodeExtern{},
  437. }
  438. }()
  439. return ch
  440. }
  441. func (w *eventingWatcher) Remove() {}
  442. func TestWriteError(t *testing.T) {
  443. // nil error should not panic
  444. rw := httptest.NewRecorder()
  445. writeError(rw, nil)
  446. h := rw.Header()
  447. if len(h) > 0 {
  448. t.Fatalf("unexpected non-empty headers: %#v", h)
  449. }
  450. b := rw.Body.String()
  451. if len(b) > 0 {
  452. t.Fatalf("unexpected non-empty body: %q", b)
  453. }
  454. tests := []struct {
  455. err error
  456. wcode int
  457. wi string
  458. }{
  459. {
  460. etcdErr.NewError(etcdErr.EcodeKeyNotFound, "/foo/bar", 123),
  461. http.StatusNotFound,
  462. "123",
  463. },
  464. {
  465. etcdErr.NewError(etcdErr.EcodeTestFailed, "/foo/bar", 456),
  466. http.StatusPreconditionFailed,
  467. "456",
  468. },
  469. {
  470. err: errors.New("something went wrong"),
  471. wcode: http.StatusInternalServerError,
  472. },
  473. }
  474. for i, tt := range tests {
  475. rw := httptest.NewRecorder()
  476. writeError(rw, tt.err)
  477. if code := rw.Code; code != tt.wcode {
  478. t.Errorf("#%d: code=%d, want %d", i, code, tt.wcode)
  479. }
  480. if idx := rw.Header().Get("X-Etcd-Index"); idx != tt.wi {
  481. t.Errorf("#%d: X-Etcd-Index=%q, want %q", i, idx, tt.wi)
  482. }
  483. }
  484. }
  485. type dummyRaftTimer struct{}
  486. func (drt dummyRaftTimer) Index() uint64 { return uint64(100) }
  487. func (drt dummyRaftTimer) Term() uint64 { return uint64(5) }
  488. func TestWriteEvent(t *testing.T) {
  489. // nil event should not panic
  490. rw := httptest.NewRecorder()
  491. writeEvent(rw, nil, dummyRaftTimer{})
  492. h := rw.Header()
  493. if len(h) > 0 {
  494. t.Fatalf("unexpected non-empty headers: %#v", h)
  495. }
  496. b := rw.Body.String()
  497. if len(b) > 0 {
  498. t.Fatalf("unexpected non-empty body: %q", b)
  499. }
  500. tests := []struct {
  501. ev *store.Event
  502. idx string
  503. // TODO(jonboulle): check body as well as just status code
  504. code int
  505. err error
  506. }{
  507. // standard case, standard 200 response
  508. {
  509. &store.Event{
  510. Action: store.Get,
  511. Node: &store.NodeExtern{},
  512. PrevNode: &store.NodeExtern{},
  513. },
  514. "0",
  515. http.StatusOK,
  516. nil,
  517. },
  518. // check new nodes return StatusCreated
  519. {
  520. &store.Event{
  521. Action: store.Create,
  522. Node: &store.NodeExtern{},
  523. PrevNode: &store.NodeExtern{},
  524. },
  525. "0",
  526. http.StatusCreated,
  527. nil,
  528. },
  529. }
  530. for i, tt := range tests {
  531. rw := httptest.NewRecorder()
  532. writeEvent(rw, tt.ev, dummyRaftTimer{})
  533. if gct := rw.Header().Get("Content-Type"); gct != "application/json" {
  534. t.Errorf("case %d: bad Content-Type: got %q, want application/json", i, gct)
  535. }
  536. if gri := rw.Header().Get("X-Raft-Index"); gri != "100" {
  537. t.Errorf("case %d: bad X-Raft-Index header: got %s, want %s", i, gri, "100")
  538. }
  539. if grt := rw.Header().Get("X-Raft-Term"); grt != "5" {
  540. t.Errorf("case %d: bad X-Raft-Term header: got %s, want %s", i, grt, "5")
  541. }
  542. if gei := rw.Header().Get("X-Etcd-Index"); gei != tt.idx {
  543. t.Errorf("case %d: bad X-Etcd-Index header: got %s, want %s", i, gei, tt.idx)
  544. }
  545. if rw.Code != tt.code {
  546. t.Errorf("case %d: bad response code: got %d, want %v", i, rw.Code, tt.code)
  547. }
  548. }
  549. }
  550. type dummyWatcher struct {
  551. echan chan *store.Event
  552. sidx uint64
  553. }
  554. func (w *dummyWatcher) EventChan() chan *store.Event {
  555. return w.echan
  556. }
  557. func (w *dummyWatcher) StartIndex() uint64 { return w.sidx }
  558. func (w *dummyWatcher) Remove() {}
  559. func TestV2DeprecatedMachinesEndpoint(t *testing.T) {
  560. tests := []struct {
  561. method string
  562. wcode int
  563. }{
  564. {"GET", http.StatusOK},
  565. {"HEAD", http.StatusOK},
  566. {"POST", http.StatusMethodNotAllowed},
  567. }
  568. m := NewClientHandler(&etcdserver.EtcdServer{ClusterStore: &fakeCluster{}})
  569. s := httptest.NewServer(m)
  570. defer s.Close()
  571. for _, tt := range tests {
  572. req, err := http.NewRequest(tt.method, s.URL+deprecatedMachinesPrefix, nil)
  573. if err != nil {
  574. t.Fatal(err)
  575. }
  576. resp, err := http.DefaultClient.Do(req)
  577. if err != nil {
  578. t.Fatal(err)
  579. }
  580. if resp.StatusCode != tt.wcode {
  581. t.Errorf("StatusCode = %d, expected %d", resp.StatusCode, tt.wcode)
  582. }
  583. }
  584. }
  585. func TestServeMachines(t *testing.T) {
  586. cluster := &fakeCluster{
  587. members: []etcdserver.Member{
  588. {ID: 0xBEEF0, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8080"}}},
  589. {ID: 0xBEEF1, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8081"}}},
  590. {ID: 0xBEEF2, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8082"}}},
  591. },
  592. }
  593. writer := httptest.NewRecorder()
  594. req, err := http.NewRequest("GET", "", nil)
  595. if err != nil {
  596. t.Fatal(err)
  597. }
  598. h := &serverHandler{clusterStore: cluster}
  599. h.serveMachines(writer, req)
  600. w := "http://localhost:8080, http://localhost:8081, http://localhost:8082"
  601. if g := writer.Body.String(); g != w {
  602. t.Errorf("body = %s, want %s", g, w)
  603. }
  604. if writer.Code != http.StatusOK {
  605. t.Errorf("code = %d, want %d", writer.Code, http.StatusOK)
  606. }
  607. }
  608. type dummyServerStats struct {
  609. js []byte
  610. ls *stats.LeaderStats
  611. }
  612. func (dss *dummyServerStats) SelfStatsJSON() []byte { return dss.js }
  613. func (dss *dummyServerStats) SelfStats() *stats.ServerStats { return nil }
  614. func (dss *dummyServerStats) LeaderStats() *stats.LeaderStats { return dss.ls }
  615. func TestServeSelfStats(t *testing.T) {
  616. ss := &stats.ServerStats{
  617. Name: "foobar",
  618. RecvingPkgRate: 123.4,
  619. }
  620. w, err := json.Marshal(ss)
  621. if err != nil {
  622. t.Fatal("error marshaling: %v", err)
  623. }
  624. sh := &serverHandler{
  625. stats: &dummyServerStats{
  626. js: w,
  627. },
  628. }
  629. rw := httptest.NewRecorder()
  630. sh.serveSelfStats(rw, &http.Request{Method: "GET"})
  631. if rw.Code != http.StatusOK {
  632. t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
  633. }
  634. wct := "application/json"
  635. if gct := rw.Header().Get("Content-Type"); gct != wct {
  636. t.Errorf("Content-Type = %q, want %q", gct, wct)
  637. }
  638. if g := rw.Body.String(); g != string(w) {
  639. t.Errorf("body = %s, want %s", g, string(w))
  640. }
  641. }
  642. func TestSelfServeStatsBad(t *testing.T) {
  643. for _, m := range []string{"PUT", "POST", "DELETE"} {
  644. sh := &serverHandler{}
  645. rw := httptest.NewRecorder()
  646. sh.serveSelfStats(
  647. rw,
  648. &http.Request{
  649. Method: m,
  650. },
  651. )
  652. if rw.Code != http.StatusMethodNotAllowed {
  653. t.Errorf("method %s: code=%d, want %d", m, http.StatusMethodNotAllowed)
  654. }
  655. }
  656. }
  657. func TestLeaderServeStatsBad(t *testing.T) {
  658. for _, m := range []string{"PUT", "POST", "DELETE"} {
  659. sh := &serverHandler{}
  660. rw := httptest.NewRecorder()
  661. sh.serveLeaderStats(
  662. rw,
  663. &http.Request{
  664. Method: m,
  665. },
  666. )
  667. if rw.Code != http.StatusMethodNotAllowed {
  668. t.Errorf("method %s: code=%d, want %d", m, http.StatusMethodNotAllowed)
  669. }
  670. }
  671. }
  672. func TestServeLeaderStats(t *testing.T) {
  673. ls := &stats.LeaderStats{
  674. Leader: "foobar",
  675. }
  676. w, err := json.Marshal(ls)
  677. if err != nil {
  678. t.Fatal("error marshaling: %v", err)
  679. }
  680. sh := &serverHandler{
  681. stats: &dummyServerStats{
  682. ls: ls,
  683. },
  684. }
  685. rw := httptest.NewRecorder()
  686. sh.serveLeaderStats(rw, &http.Request{Method: "GET"})
  687. if rw.Code != http.StatusOK {
  688. t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
  689. }
  690. wct := "application/json"
  691. if gct := rw.Header().Get("Content-Type"); gct != wct {
  692. t.Errorf("Content-Type = %q, want %q", gct, wct)
  693. }
  694. if g := rw.Body.String(); g != string(w) {
  695. t.Errorf("body = %s, want %s", g, string(w))
  696. }
  697. }
  698. type dummyStoreStats struct {
  699. data []byte
  700. }
  701. func (dss *dummyStoreStats) StoreStatsJSON() []byte { return dss.data }
  702. func TestServeStoreStats(t *testing.T) {
  703. w := "foobarbaz"
  704. sh := &serverHandler{
  705. storestats: &dummyStoreStats{data: []byte(w)},
  706. }
  707. rw := httptest.NewRecorder()
  708. sh.serveStoreStats(rw, &http.Request{Method: "GET"})
  709. if rw.Code != http.StatusOK {
  710. t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
  711. }
  712. wct := "application/json"
  713. if gct := rw.Header().Get("Content-Type"); gct != wct {
  714. t.Errorf("Content-Type = %q, want %q", gct, wct)
  715. }
  716. if g := rw.Body.String(); g != w {
  717. t.Errorf("body = %s, want %s", g, w)
  718. }
  719. }
  720. func TestAllowMethod(t *testing.T) {
  721. tests := []struct {
  722. m string
  723. ms []string
  724. w bool
  725. wh string
  726. }{
  727. // Accepted methods
  728. {
  729. m: "GET",
  730. ms: []string{"GET", "POST", "PUT"},
  731. w: true,
  732. },
  733. {
  734. m: "POST",
  735. ms: []string{"POST"},
  736. w: true,
  737. },
  738. // Made-up methods no good
  739. {
  740. m: "FAKE",
  741. ms: []string{"GET", "POST", "PUT"},
  742. w: false,
  743. wh: "GET,POST,PUT",
  744. },
  745. // Empty methods no good
  746. {
  747. m: "",
  748. ms: []string{"GET", "POST"},
  749. w: false,
  750. wh: "GET,POST",
  751. },
  752. // Empty accepted methods no good
  753. {
  754. m: "GET",
  755. ms: []string{""},
  756. w: false,
  757. wh: "",
  758. },
  759. // No methods accepted
  760. {
  761. m: "GET",
  762. ms: []string{},
  763. w: false,
  764. wh: "",
  765. },
  766. }
  767. for i, tt := range tests {
  768. rw := httptest.NewRecorder()
  769. g := allowMethod(rw, tt.m, tt.ms...)
  770. if g != tt.w {
  771. t.Errorf("#%d: got allowMethod()=%t, want %t", i, g, tt.w)
  772. }
  773. if !tt.w {
  774. if rw.Code != http.StatusMethodNotAllowed {
  775. t.Errorf("#%d: code=%d, want %d", i, rw.Code, http.StatusMethodNotAllowed)
  776. }
  777. gh := rw.Header().Get("Allow")
  778. if gh != tt.wh {
  779. t.Errorf("#%d: Allow header=%q, want %q", i, gh, tt.wh)
  780. }
  781. }
  782. }
  783. }
  784. // errServer implements the etcd.Server interface for testing.
  785. // It returns the given error from any Do/Process/AddMember/RemoveMember calls.
  786. type errServer struct {
  787. err error
  788. }
  789. func (fs *errServer) Do(ctx context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
  790. return etcdserver.Response{}, fs.err
  791. }
  792. func (fs *errServer) Process(ctx context.Context, m raftpb.Message) error {
  793. return fs.err
  794. }
  795. func (fs *errServer) Start() {}
  796. func (fs *errServer) Stop() {}
  797. func (fs *errServer) AddMember(ctx context.Context, m etcdserver.Member) error {
  798. return fs.err
  799. }
  800. func (fs *errServer) RemoveMember(ctx context.Context, id uint64) error {
  801. return fs.err
  802. }
  803. // errReader implements io.Reader to facilitate a broken request.
  804. type errReader struct{}
  805. func (er *errReader) Read(_ []byte) (int, error) { return 0, errors.New("some error") }
  806. func mustMarshalMsg(t *testing.T, m raftpb.Message) []byte {
  807. json, err := m.Marshal()
  808. if err != nil {
  809. t.Fatalf("error marshalling raft Message: %#v", err)
  810. }
  811. return json
  812. }
  813. func TestServeRaft(t *testing.T) {
  814. testCases := []struct {
  815. method string
  816. body io.Reader
  817. serverErr error
  818. wcode int
  819. }{
  820. {
  821. // bad method
  822. "GET",
  823. bytes.NewReader(
  824. mustMarshalMsg(
  825. t,
  826. raftpb.Message{},
  827. ),
  828. ),
  829. nil,
  830. http.StatusMethodNotAllowed,
  831. },
  832. {
  833. // bad method
  834. "PUT",
  835. bytes.NewReader(
  836. mustMarshalMsg(
  837. t,
  838. raftpb.Message{},
  839. ),
  840. ),
  841. nil,
  842. http.StatusMethodNotAllowed,
  843. },
  844. {
  845. // bad method
  846. "DELETE",
  847. bytes.NewReader(
  848. mustMarshalMsg(
  849. t,
  850. raftpb.Message{},
  851. ),
  852. ),
  853. nil,
  854. http.StatusMethodNotAllowed,
  855. },
  856. {
  857. // bad request body
  858. "POST",
  859. &errReader{},
  860. nil,
  861. http.StatusBadRequest,
  862. },
  863. {
  864. // bad request protobuf
  865. "POST",
  866. strings.NewReader("malformed garbage"),
  867. nil,
  868. http.StatusBadRequest,
  869. },
  870. {
  871. // good request, etcdserver.Server error
  872. "POST",
  873. bytes.NewReader(
  874. mustMarshalMsg(
  875. t,
  876. raftpb.Message{},
  877. ),
  878. ),
  879. errors.New("some error"),
  880. http.StatusInternalServerError,
  881. },
  882. {
  883. // good request
  884. "POST",
  885. bytes.NewReader(
  886. mustMarshalMsg(
  887. t,
  888. raftpb.Message{},
  889. ),
  890. ),
  891. nil,
  892. http.StatusNoContent,
  893. },
  894. }
  895. for i, tt := range testCases {
  896. req, err := http.NewRequest(tt.method, "foo", tt.body)
  897. if err != nil {
  898. t.Fatalf("#%d: could not create request: %#v", i, err)
  899. }
  900. h := &serverHandler{
  901. timeout: time.Hour,
  902. server: &errServer{tt.serverErr},
  903. }
  904. rw := httptest.NewRecorder()
  905. h.serveRaft(rw, req)
  906. if rw.Code != tt.wcode {
  907. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  908. }
  909. }
  910. }
  911. // resServer implements the etcd.Server interface for testing.
  912. // It returns the given responsefrom any Do calls, and nil error
  913. type resServer struct {
  914. res etcdserver.Response
  915. }
  916. func (rs *resServer) Do(_ context.Context, _ etcdserverpb.Request) (etcdserver.Response, error) {
  917. return rs.res, nil
  918. }
  919. func (rs *resServer) Process(_ context.Context, _ raftpb.Message) error { return nil }
  920. func (rs *resServer) Start() {}
  921. func (rs *resServer) Stop() {}
  922. func (rs *resServer) AddMember(_ context.Context, _ etcdserver.Member) error { return nil }
  923. func (rs *resServer) RemoveMember(_ context.Context, _ uint64) error { return nil }
  924. func mustMarshalEvent(t *testing.T, ev *store.Event) string {
  925. b := new(bytes.Buffer)
  926. if err := json.NewEncoder(b).Encode(ev); err != nil {
  927. t.Fatalf("error marshalling event %#v: %v", ev, err)
  928. }
  929. return b.String()
  930. }
  931. func TestBadServeKeys(t *testing.T) {
  932. testBadCases := []struct {
  933. req *http.Request
  934. server etcdserver.Server
  935. wcode int
  936. }{
  937. {
  938. // bad method
  939. &http.Request{
  940. Method: "CONNECT",
  941. },
  942. &resServer{},
  943. http.StatusMethodNotAllowed,
  944. },
  945. {
  946. // bad method
  947. &http.Request{
  948. Method: "TRACE",
  949. },
  950. &resServer{},
  951. http.StatusMethodNotAllowed,
  952. },
  953. {
  954. // parseRequest error
  955. &http.Request{
  956. Body: nil,
  957. Method: "PUT",
  958. },
  959. &resServer{},
  960. http.StatusBadRequest,
  961. },
  962. {
  963. // etcdserver.Server error
  964. mustNewRequest(t, "foo"),
  965. &errServer{
  966. errors.New("blah"),
  967. },
  968. http.StatusInternalServerError,
  969. },
  970. {
  971. // non-event/watcher response from etcdserver.Server
  972. mustNewRequest(t, "foo"),
  973. &resServer{
  974. etcdserver.Response{},
  975. },
  976. http.StatusInternalServerError,
  977. },
  978. }
  979. for i, tt := range testBadCases {
  980. h := &serverHandler{
  981. timeout: 0, // context times out immediately
  982. server: tt.server,
  983. }
  984. rw := httptest.NewRecorder()
  985. h.serveKeys(rw, tt.req)
  986. if rw.Code != tt.wcode {
  987. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  988. }
  989. }
  990. }
  991. func TestServeKeysEvent(t *testing.T) {
  992. req := mustNewRequest(t, "foo")
  993. server := &resServer{
  994. etcdserver.Response{
  995. Event: &store.Event{
  996. Action: store.Get,
  997. Node: &store.NodeExtern{},
  998. },
  999. },
  1000. }
  1001. h := &serverHandler{
  1002. timeout: time.Hour,
  1003. server: server,
  1004. timer: &dummyRaftTimer{},
  1005. }
  1006. rw := httptest.NewRecorder()
  1007. h.serveKeys(rw, req)
  1008. wcode := http.StatusOK
  1009. wbody := mustMarshalEvent(
  1010. t,
  1011. &store.Event{
  1012. Action: store.Get,
  1013. Node: &store.NodeExtern{},
  1014. },
  1015. )
  1016. if rw.Code != wcode {
  1017. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1018. }
  1019. g := rw.Body.String()
  1020. if g != wbody {
  1021. t.Errorf("got body=%#v, want %#v", g, wbody)
  1022. }
  1023. }
  1024. func TestServeKeysWatch(t *testing.T) {
  1025. req := mustNewRequest(t, "/foo/bar")
  1026. ec := make(chan *store.Event)
  1027. dw := &dummyWatcher{
  1028. echan: ec,
  1029. }
  1030. server := &resServer{
  1031. etcdserver.Response{
  1032. Watcher: dw,
  1033. },
  1034. }
  1035. h := &serverHandler{
  1036. timeout: time.Hour,
  1037. server: server,
  1038. timer: &dummyRaftTimer{},
  1039. }
  1040. go func() {
  1041. ec <- &store.Event{
  1042. Action: store.Get,
  1043. Node: &store.NodeExtern{},
  1044. }
  1045. }()
  1046. rw := httptest.NewRecorder()
  1047. h.serveKeys(rw, req)
  1048. wcode := http.StatusOK
  1049. wbody := mustMarshalEvent(
  1050. t,
  1051. &store.Event{
  1052. Action: store.Get,
  1053. Node: &store.NodeExtern{},
  1054. },
  1055. )
  1056. if rw.Code != wcode {
  1057. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1058. }
  1059. g := rw.Body.String()
  1060. if g != wbody {
  1061. t.Errorf("got body=%#v, want %#v", g, wbody)
  1062. }
  1063. }
  1064. type recordingCloseNotifier struct {
  1065. *httptest.ResponseRecorder
  1066. cn chan bool
  1067. }
  1068. func (rcn *recordingCloseNotifier) CloseNotify() <-chan bool {
  1069. return rcn.cn
  1070. }
  1071. func TestHandleWatch(t *testing.T) {
  1072. defaultRwRr := func() (http.ResponseWriter, *httptest.ResponseRecorder) {
  1073. r := httptest.NewRecorder()
  1074. return r, r
  1075. }
  1076. noopEv := func(chan *store.Event) {}
  1077. tests := []struct {
  1078. getCtx func() context.Context
  1079. getRwRr func() (http.ResponseWriter, *httptest.ResponseRecorder)
  1080. doToChan func(chan *store.Event)
  1081. wbody string
  1082. }{
  1083. {
  1084. // Normal case: one event
  1085. context.Background,
  1086. defaultRwRr,
  1087. func(ch chan *store.Event) {
  1088. ch <- &store.Event{
  1089. Action: store.Get,
  1090. Node: &store.NodeExtern{},
  1091. }
  1092. },
  1093. mustMarshalEvent(
  1094. t,
  1095. &store.Event{
  1096. Action: store.Get,
  1097. Node: &store.NodeExtern{},
  1098. },
  1099. ),
  1100. },
  1101. {
  1102. // Channel is closed, no event
  1103. context.Background,
  1104. defaultRwRr,
  1105. func(ch chan *store.Event) {
  1106. close(ch)
  1107. },
  1108. "",
  1109. },
  1110. {
  1111. // Simulate a timed-out context
  1112. func() context.Context {
  1113. ctx, cancel := context.WithCancel(context.Background())
  1114. cancel()
  1115. return ctx
  1116. },
  1117. defaultRwRr,
  1118. noopEv,
  1119. "",
  1120. },
  1121. {
  1122. // Close-notifying request
  1123. context.Background,
  1124. func() (http.ResponseWriter, *httptest.ResponseRecorder) {
  1125. rw := &recordingCloseNotifier{
  1126. ResponseRecorder: httptest.NewRecorder(),
  1127. cn: make(chan bool, 1),
  1128. }
  1129. rw.cn <- true
  1130. return rw, rw.ResponseRecorder
  1131. },
  1132. noopEv,
  1133. "",
  1134. },
  1135. }
  1136. for i, tt := range tests {
  1137. rw, rr := tt.getRwRr()
  1138. wa := &dummyWatcher{
  1139. echan: make(chan *store.Event, 1),
  1140. sidx: 10,
  1141. }
  1142. tt.doToChan(wa.echan)
  1143. handleWatch(tt.getCtx(), rw, wa, false, dummyRaftTimer{})
  1144. wcode := http.StatusOK
  1145. wct := "application/json"
  1146. wei := "10"
  1147. wri := "100"
  1148. wrt := "5"
  1149. if rr.Code != wcode {
  1150. t.Errorf("#%d: got code=%d, want %d", rr.Code, wcode)
  1151. }
  1152. h := rr.Header()
  1153. if ct := h.Get("Content-Type"); ct != wct {
  1154. t.Errorf("#%d: Content-Type=%q, want %q", i, ct, wct)
  1155. }
  1156. if ei := h.Get("X-Etcd-Index"); ei != wei {
  1157. t.Errorf("#%d: X-Etcd-Index=%q, want %q", i, ei, wei)
  1158. }
  1159. if ri := h.Get("X-Raft-Index"); ri != wri {
  1160. t.Errorf("#%d: X-Raft-Index=%q, want %q", i, ri, wri)
  1161. }
  1162. if rt := h.Get("X-Raft-Term"); rt != wrt {
  1163. t.Errorf("#%d: X-Raft-Term=%q, want %q", i, rt, wrt)
  1164. }
  1165. g := rr.Body.String()
  1166. if g != tt.wbody {
  1167. t.Errorf("#%d: got body=%#v, want %#v", i, g, tt.wbody)
  1168. }
  1169. }
  1170. }
  1171. // flushingRecorder provides a channel to allow users to block until the Recorder is Flushed()
  1172. type flushingRecorder struct {
  1173. *httptest.ResponseRecorder
  1174. ch chan struct{}
  1175. }
  1176. func (fr *flushingRecorder) Flush() {
  1177. fr.ResponseRecorder.Flush()
  1178. fr.ch <- struct{}{}
  1179. }
  1180. func TestHandleWatchStreaming(t *testing.T) {
  1181. rw := &flushingRecorder{
  1182. httptest.NewRecorder(),
  1183. make(chan struct{}, 1),
  1184. }
  1185. wa := &dummyWatcher{
  1186. echan: make(chan *store.Event),
  1187. }
  1188. // Launch the streaming handler in the background with a cancellable context
  1189. ctx, cancel := context.WithCancel(context.Background())
  1190. done := make(chan struct{})
  1191. go func() {
  1192. handleWatch(ctx, rw, wa, true, dummyRaftTimer{})
  1193. close(done)
  1194. }()
  1195. // Expect one Flush for the headers etc.
  1196. select {
  1197. case <-rw.ch:
  1198. case <-time.After(time.Second):
  1199. t.Fatalf("timed out waiting for flush")
  1200. }
  1201. // Expect headers but no body
  1202. wcode := http.StatusOK
  1203. wct := "application/json"
  1204. wbody := ""
  1205. if rw.Code != wcode {
  1206. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1207. }
  1208. h := rw.Header()
  1209. if ct := h.Get("Content-Type"); ct != wct {
  1210. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1211. }
  1212. g := rw.Body.String()
  1213. if g != wbody {
  1214. t.Errorf("got body=%#v, want %#v", g, wbody)
  1215. }
  1216. // Now send the first event
  1217. select {
  1218. case wa.echan <- &store.Event{
  1219. Action: store.Get,
  1220. Node: &store.NodeExtern{},
  1221. }:
  1222. case <-time.After(time.Second):
  1223. t.Fatal("timed out waiting for send")
  1224. }
  1225. // Wait for it to be flushed...
  1226. select {
  1227. case <-rw.ch:
  1228. case <-time.After(time.Second):
  1229. t.Fatalf("timed out waiting for flush")
  1230. }
  1231. // And check the body is as expected
  1232. wbody = mustMarshalEvent(
  1233. t,
  1234. &store.Event{
  1235. Action: store.Get,
  1236. Node: &store.NodeExtern{},
  1237. },
  1238. )
  1239. g = rw.Body.String()
  1240. if g != wbody {
  1241. t.Errorf("got body=%#v, want %#v", g, wbody)
  1242. }
  1243. // Rinse and repeat
  1244. select {
  1245. case wa.echan <- &store.Event{
  1246. Action: store.Get,
  1247. Node: &store.NodeExtern{},
  1248. }:
  1249. case <-time.After(time.Second):
  1250. t.Fatal("timed out waiting for send")
  1251. }
  1252. select {
  1253. case <-rw.ch:
  1254. case <-time.After(time.Second):
  1255. t.Fatalf("timed out waiting for flush")
  1256. }
  1257. // This time, we expect to see both events
  1258. wbody = wbody + wbody
  1259. g = rw.Body.String()
  1260. if g != wbody {
  1261. t.Errorf("got body=%#v, want %#v", g, wbody)
  1262. }
  1263. // Finally, time out the connection and ensure the serving goroutine returns
  1264. cancel()
  1265. select {
  1266. case <-done:
  1267. case <-time.After(time.Second):
  1268. t.Fatalf("timed out waiting for done")
  1269. }
  1270. }
  1271. func TestServeAdminMembersFail(t *testing.T) {
  1272. tests := []struct {
  1273. req *http.Request
  1274. server etcdserver.Server
  1275. wcode int
  1276. }{
  1277. {
  1278. // bad method
  1279. &http.Request{
  1280. Method: "CONNECT",
  1281. },
  1282. &resServer{},
  1283. http.StatusMethodNotAllowed,
  1284. },
  1285. {
  1286. // bad method
  1287. &http.Request{
  1288. Method: "TRACE",
  1289. },
  1290. &resServer{},
  1291. http.StatusMethodNotAllowed,
  1292. },
  1293. {
  1294. // parse id error
  1295. &http.Request{
  1296. URL: mustNewURL(t, path.Join(adminMembersPrefix, "badID")),
  1297. Method: "PUT",
  1298. },
  1299. &resServer{},
  1300. http.StatusBadRequest,
  1301. },
  1302. {
  1303. // parse body error
  1304. &http.Request{
  1305. URL: mustNewURL(t, path.Join(adminMembersPrefix, "1")),
  1306. Method: "PUT",
  1307. },
  1308. &resServer{},
  1309. http.StatusBadRequest,
  1310. },
  1311. {
  1312. // etcdserver.AddMember error
  1313. &http.Request{
  1314. URL: mustNewURL(t, path.Join(adminMembersPrefix, "1")),
  1315. Method: "PUT",
  1316. Body: ioutil.NopCloser(strings.NewReader("")),
  1317. },
  1318. &errServer{
  1319. errors.New("blah"),
  1320. },
  1321. http.StatusInternalServerError,
  1322. },
  1323. {
  1324. // etcdserver.RemoveMember error
  1325. &http.Request{
  1326. URL: mustNewURL(t, path.Join(adminMembersPrefix, "1")),
  1327. Method: "DELETE",
  1328. },
  1329. &errServer{
  1330. errors.New("blah"),
  1331. },
  1332. http.StatusInternalServerError,
  1333. },
  1334. }
  1335. for i, tt := range tests {
  1336. h := &serverHandler{
  1337. server: tt.server,
  1338. }
  1339. rw := httptest.NewRecorder()
  1340. h.serveAdminMembers(rw, tt.req)
  1341. if rw.Code != tt.wcode {
  1342. t.Errorf("#%d: code=%d, want %d", i, rw.Code, tt.wcode)
  1343. }
  1344. }
  1345. }
  1346. type action struct {
  1347. name string
  1348. params []interface{}
  1349. }
  1350. type serverRecorder struct {
  1351. actions []action
  1352. }
  1353. func (s *serverRecorder) Do(_ context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
  1354. s.actions = append(s.actions, action{name: "Do", params: []interface{}{r}})
  1355. return etcdserver.Response{}, nil
  1356. }
  1357. func (s *serverRecorder) Process(_ context.Context, m raftpb.Message) error {
  1358. s.actions = append(s.actions, action{name: "Process", params: []interface{}{m}})
  1359. return nil
  1360. }
  1361. func (s *serverRecorder) Start() {}
  1362. func (s *serverRecorder) Stop() {}
  1363. func (s *serverRecorder) AddMember(_ context.Context, m etcdserver.Member) error {
  1364. s.actions = append(s.actions, action{name: "AddMember", params: []interface{}{m}})
  1365. return nil
  1366. }
  1367. func (s *serverRecorder) RemoveMember(_ context.Context, id uint64) error {
  1368. s.actions = append(s.actions, action{name: "RemoveMember", params: []interface{}{id}})
  1369. return nil
  1370. }
  1371. func TestServeAdminMembersPut(t *testing.T) {
  1372. u := mustNewURL(t, path.Join(adminMembersPrefix, "BEEF"))
  1373. form := url.Values{"PeerURLs": []string{"http://a", "http://b"}}
  1374. body := strings.NewReader(form.Encode())
  1375. req, err := http.NewRequest("PUT", u.String(), body)
  1376. if err != nil {
  1377. t.Fatal(err)
  1378. }
  1379. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1380. s := &serverRecorder{}
  1381. h := &serverHandler{
  1382. server: s,
  1383. }
  1384. rw := httptest.NewRecorder()
  1385. h.serveAdminMembers(rw, req)
  1386. wcode := http.StatusCreated
  1387. if rw.Code != wcode {
  1388. t.Errorf("code=%d, want %d", rw.Code, wcode)
  1389. }
  1390. g := rw.Body.String()
  1391. if g != "" {
  1392. t.Errorf("got body=%q, want %q", g, "")
  1393. }
  1394. wm := etcdserver.Member{
  1395. ID: 0xBEEF,
  1396. RaftAttributes: etcdserver.RaftAttributes{
  1397. PeerURLs: []string{"http://a", "http://b"},
  1398. },
  1399. }
  1400. wactions := []action{{name: "AddMember", params: []interface{}{wm}}}
  1401. if !reflect.DeepEqual(s.actions, wactions) {
  1402. t.Errorf("actions = %+v, want %+v", s.actions, wactions)
  1403. }
  1404. }
  1405. func TestServeAdminMembersDelete(t *testing.T) {
  1406. req := &http.Request{
  1407. Method: "DELETE",
  1408. URL: mustNewURL(t, path.Join(adminMembersPrefix, "BEEF")),
  1409. }
  1410. s := &serverRecorder{}
  1411. h := &serverHandler{
  1412. server: s,
  1413. }
  1414. rw := httptest.NewRecorder()
  1415. h.serveAdminMembers(rw, req)
  1416. wcode := http.StatusNoContent
  1417. if rw.Code != wcode {
  1418. t.Errorf("code=%d, want %d", rw.Code, wcode)
  1419. }
  1420. g := rw.Body.String()
  1421. if g != "" {
  1422. t.Errorf("got body=%q, want %q", g, "")
  1423. }
  1424. wactions := []action{{name: "RemoveMember", params: []interface{}{uint64(0xBEEF)}}}
  1425. if !reflect.DeepEqual(s.actions, wactions) {
  1426. t.Errorf("actions = %+v, want %+v", s.actions, wactions)
  1427. }
  1428. }
  1429. type fakeCluster struct {
  1430. members []etcdserver.Member
  1431. }
  1432. func (c *fakeCluster) Add(m etcdserver.Member) { return }
  1433. func (c *fakeCluster) Get() etcdserver.Cluster {
  1434. cl := &etcdserver.Cluster{}
  1435. cl.AddSlice(c.members)
  1436. return *cl
  1437. }
  1438. func (c *fakeCluster) Remove(id uint64) { return }