http_test.go 22 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. package etcdhttp
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "net/url"
  10. "path"
  11. "reflect"
  12. "strings"
  13. "sync"
  14. "testing"
  15. "time"
  16. etcdErr "github.com/coreos/etcd/error"
  17. "github.com/coreos/etcd/etcdserver"
  18. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  19. "github.com/coreos/etcd/raft/raftpb"
  20. "github.com/coreos/etcd/store"
  21. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  22. )
  23. func boolp(b bool) *bool { return &b }
  24. func mustNewURL(t *testing.T, s string) *url.URL {
  25. u, err := url.Parse(s)
  26. if err != nil {
  27. t.Fatalf("error creating URL from %q: %v", s, err)
  28. }
  29. return u
  30. }
  31. // mustNewRequest takes a path, appends it to the standard keysPrefix, and constructs
  32. // a GET *http.Request referencing the resulting URL
  33. func mustNewRequest(t *testing.T, p string) *http.Request {
  34. return &http.Request{
  35. Method: "GET",
  36. URL: mustNewURL(t, path.Join(keysPrefix, p)),
  37. }
  38. }
  39. // mustNewForm takes a set of Values and constructs a PUT *http.Request,
  40. // with a URL constructed from appending the given path to the standard keysPrefix
  41. func mustNewForm(t *testing.T, p string, vals url.Values) *http.Request {
  42. u := mustNewURL(t, path.Join(keysPrefix, p))
  43. req, err := http.NewRequest("PUT", u.String(), strings.NewReader(vals.Encode()))
  44. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  45. if err != nil {
  46. t.Fatalf("error creating new request: %v", err)
  47. }
  48. return req
  49. }
  50. func TestBadParseRequest(t *testing.T) {
  51. tests := []struct {
  52. in *http.Request
  53. wcode int
  54. }{
  55. {
  56. // parseForm failure
  57. &http.Request{
  58. Body: nil,
  59. Method: "PUT",
  60. },
  61. etcdErr.EcodeInvalidForm,
  62. },
  63. {
  64. // bad key prefix
  65. &http.Request{
  66. URL: mustNewURL(t, "/badprefix/"),
  67. },
  68. etcdErr.EcodeInvalidForm,
  69. },
  70. // bad values for prevIndex, waitIndex, ttl
  71. {
  72. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"garbage"}}),
  73. etcdErr.EcodeIndexNaN,
  74. },
  75. {
  76. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"1.5"}}),
  77. etcdErr.EcodeIndexNaN,
  78. },
  79. {
  80. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"-1"}}),
  81. etcdErr.EcodeIndexNaN,
  82. },
  83. {
  84. mustNewForm(t, "foo", url.Values{"waitIndex": []string{"garbage"}}),
  85. etcdErr.EcodeIndexNaN,
  86. },
  87. {
  88. mustNewForm(t, "foo", url.Values{"waitIndex": []string{"??"}}),
  89. etcdErr.EcodeIndexNaN,
  90. },
  91. {
  92. mustNewForm(t, "foo", url.Values{"ttl": []string{"-1"}}),
  93. etcdErr.EcodeTTLNaN,
  94. },
  95. // bad values for recursive, sorted, wait, prevExists
  96. {
  97. mustNewForm(t, "foo", url.Values{"recursive": []string{"hahaha"}}),
  98. etcdErr.EcodeInvalidField,
  99. },
  100. {
  101. mustNewForm(t, "foo", url.Values{"recursive": []string{"1234"}}),
  102. etcdErr.EcodeInvalidField,
  103. },
  104. {
  105. mustNewForm(t, "foo", url.Values{"recursive": []string{"?"}}),
  106. etcdErr.EcodeInvalidField,
  107. },
  108. {
  109. mustNewForm(t, "foo", url.Values{"sorted": []string{"?"}}),
  110. etcdErr.EcodeInvalidField,
  111. },
  112. {
  113. mustNewForm(t, "foo", url.Values{"sorted": []string{"x"}}),
  114. etcdErr.EcodeInvalidField,
  115. },
  116. {
  117. mustNewForm(t, "foo", url.Values{"wait": []string{"?!"}}),
  118. etcdErr.EcodeInvalidField,
  119. },
  120. {
  121. mustNewForm(t, "foo", url.Values{"wait": []string{"yes"}}),
  122. etcdErr.EcodeInvalidField,
  123. },
  124. {
  125. mustNewForm(t, "foo", url.Values{"prevExists": []string{"yes"}}),
  126. etcdErr.EcodeInvalidField,
  127. },
  128. {
  129. mustNewForm(t, "foo", url.Values{"prevExists": []string{"#2"}}),
  130. etcdErr.EcodeInvalidField,
  131. },
  132. // query values are considered
  133. {
  134. mustNewRequest(t, "foo?prevExists=wrong"),
  135. etcdErr.EcodeInvalidField,
  136. },
  137. {
  138. mustNewRequest(t, "foo?ttl=wrong"),
  139. etcdErr.EcodeTTLNaN,
  140. },
  141. // but body takes precedence if both are specified
  142. {
  143. mustNewForm(
  144. t,
  145. "foo?ttl=12",
  146. url.Values{"ttl": []string{"garbage"}},
  147. ),
  148. etcdErr.EcodeTTLNaN,
  149. },
  150. {
  151. mustNewForm(
  152. t,
  153. "foo?prevExists=false",
  154. url.Values{"prevExists": []string{"yes"}},
  155. ),
  156. etcdErr.EcodeInvalidField,
  157. },
  158. }
  159. for i, tt := range tests {
  160. got, err := parseRequest(tt.in, 1234)
  161. if err == nil {
  162. t.Errorf("#%d: unexpected nil error!", i)
  163. continue
  164. }
  165. ee, ok := err.(*etcdErr.Error)
  166. if !ok {
  167. t.Errorf("#%d: err is not etcd.Error!", i)
  168. continue
  169. }
  170. if ee.ErrorCode != tt.wcode {
  171. t.Errorf("#%d: code=%d, want %v", i, ee.ErrorCode, tt.wcode)
  172. t.Logf("cause: %#v", ee.Cause)
  173. }
  174. if !reflect.DeepEqual(got, etcdserverpb.Request{}) {
  175. t.Errorf("#%d: unexpected non-empty Request: %#v", i, got)
  176. }
  177. }
  178. }
  179. func TestGoodParseRequest(t *testing.T) {
  180. tests := []struct {
  181. in *http.Request
  182. w etcdserverpb.Request
  183. }{
  184. {
  185. // good prefix, all other values default
  186. mustNewRequest(t, "foo"),
  187. etcdserverpb.Request{
  188. Id: 1234,
  189. Method: "GET",
  190. Path: "/foo",
  191. },
  192. },
  193. {
  194. // value specified
  195. mustNewForm(
  196. t,
  197. "foo",
  198. url.Values{"value": []string{"some_value"}},
  199. ),
  200. etcdserverpb.Request{
  201. Id: 1234,
  202. Method: "PUT",
  203. Val: "some_value",
  204. Path: "/foo",
  205. },
  206. },
  207. {
  208. // prevIndex specified
  209. mustNewForm(
  210. t,
  211. "foo",
  212. url.Values{"prevIndex": []string{"98765"}},
  213. ),
  214. etcdserverpb.Request{
  215. Id: 1234,
  216. Method: "PUT",
  217. PrevIndex: 98765,
  218. Path: "/foo",
  219. },
  220. },
  221. {
  222. // recursive specified
  223. mustNewForm(
  224. t,
  225. "foo",
  226. url.Values{"recursive": []string{"true"}},
  227. ),
  228. etcdserverpb.Request{
  229. Id: 1234,
  230. Method: "PUT",
  231. Recursive: true,
  232. Path: "/foo",
  233. },
  234. },
  235. {
  236. // sorted specified
  237. mustNewForm(
  238. t,
  239. "foo",
  240. url.Values{"sorted": []string{"true"}},
  241. ),
  242. etcdserverpb.Request{
  243. Id: 1234,
  244. Method: "PUT",
  245. Sorted: true,
  246. Path: "/foo",
  247. },
  248. },
  249. {
  250. // wait specified
  251. mustNewForm(
  252. t,
  253. "foo",
  254. url.Values{"wait": []string{"true"}},
  255. ),
  256. etcdserverpb.Request{
  257. Id: 1234,
  258. Method: "PUT",
  259. Wait: true,
  260. Path: "/foo",
  261. },
  262. },
  263. {
  264. // prevExists should be non-null if specified
  265. mustNewForm(
  266. t,
  267. "foo",
  268. url.Values{"prevExists": []string{"true"}},
  269. ),
  270. etcdserverpb.Request{
  271. Id: 1234,
  272. Method: "PUT",
  273. PrevExists: boolp(true),
  274. Path: "/foo",
  275. },
  276. },
  277. {
  278. // prevExists should be non-null if specified
  279. mustNewForm(
  280. t,
  281. "foo",
  282. url.Values{"prevExists": []string{"false"}},
  283. ),
  284. etcdserverpb.Request{
  285. Id: 1234,
  286. Method: "PUT",
  287. PrevExists: boolp(false),
  288. Path: "/foo",
  289. },
  290. },
  291. // mix various fields
  292. {
  293. mustNewForm(
  294. t,
  295. "foo",
  296. url.Values{
  297. "value": []string{"some value"},
  298. "prevExists": []string{"true"},
  299. "prevValue": []string{"previous value"},
  300. },
  301. ),
  302. etcdserverpb.Request{
  303. Id: 1234,
  304. Method: "PUT",
  305. PrevExists: boolp(true),
  306. PrevValue: "previous value",
  307. Val: "some value",
  308. Path: "/foo",
  309. },
  310. },
  311. // query parameters should be used if given
  312. {
  313. mustNewForm(
  314. t,
  315. "foo?prevValue=woof",
  316. url.Values{},
  317. ),
  318. etcdserverpb.Request{
  319. Id: 1234,
  320. Method: "PUT",
  321. PrevValue: "woof",
  322. Path: "/foo",
  323. },
  324. },
  325. // but form values should take precedence over query parameters
  326. {
  327. mustNewForm(
  328. t,
  329. "foo?prevValue=woof",
  330. url.Values{
  331. "prevValue": []string{"miaow"},
  332. },
  333. ),
  334. etcdserverpb.Request{
  335. Id: 1234,
  336. Method: "PUT",
  337. PrevValue: "miaow",
  338. Path: "/foo",
  339. },
  340. },
  341. }
  342. for i, tt := range tests {
  343. got, err := parseRequest(tt.in, 1234)
  344. if err != nil {
  345. t.Errorf("#%d: err = %v, want %v", i, err, nil)
  346. }
  347. if !reflect.DeepEqual(got, tt.w) {
  348. t.Errorf("#%d: request=%#v, want %#v", i, got, tt.w)
  349. }
  350. }
  351. }
  352. // eventingWatcher immediately returns a simple event of the given action on its channel
  353. type eventingWatcher struct {
  354. action string
  355. }
  356. func (w *eventingWatcher) EventChan() chan *store.Event {
  357. ch := make(chan *store.Event)
  358. go func() {
  359. ch <- &store.Event{
  360. Action: w.action,
  361. Node: &store.NodeExtern{},
  362. }
  363. }()
  364. return ch
  365. }
  366. func (w *eventingWatcher) Remove() {}
  367. func TestWriteError(t *testing.T) {
  368. // nil error should not panic
  369. rw := httptest.NewRecorder()
  370. writeError(rw, nil)
  371. h := rw.Header()
  372. if len(h) > 0 {
  373. t.Fatalf("unexpected non-empty headers: %#v", h)
  374. }
  375. b := rw.Body.String()
  376. if len(b) > 0 {
  377. t.Fatalf("unexpected non-empty body: %q", b)
  378. }
  379. tests := []struct {
  380. err error
  381. wcode int
  382. wi string
  383. }{
  384. {
  385. etcdErr.NewError(etcdErr.EcodeKeyNotFound, "/foo/bar", 123),
  386. http.StatusNotFound,
  387. "123",
  388. },
  389. {
  390. etcdErr.NewError(etcdErr.EcodeTestFailed, "/foo/bar", 456),
  391. http.StatusPreconditionFailed,
  392. "456",
  393. },
  394. {
  395. err: errors.New("something went wrong"),
  396. wcode: http.StatusInternalServerError,
  397. },
  398. }
  399. for i, tt := range tests {
  400. rw := httptest.NewRecorder()
  401. writeError(rw, tt.err)
  402. if code := rw.Code; code != tt.wcode {
  403. t.Errorf("#%d: code=%d, want %d", i, code, tt.wcode)
  404. }
  405. if idx := rw.Header().Get("X-Etcd-Index"); idx != tt.wi {
  406. t.Errorf("#%d: X-Etcd-Index=%q, want %q", i, idx, tt.wi)
  407. }
  408. }
  409. }
  410. func TestWriteEvent(t *testing.T) {
  411. // nil event should not panic
  412. rw := httptest.NewRecorder()
  413. writeEvent(rw, nil)
  414. h := rw.Header()
  415. if len(h) > 0 {
  416. t.Fatalf("unexpected non-empty headers: %#v", h)
  417. }
  418. b := rw.Body.String()
  419. if len(b) > 0 {
  420. t.Fatalf("unexpected non-empty body: %q", b)
  421. }
  422. tests := []struct {
  423. ev *store.Event
  424. idx string
  425. // TODO(jonboulle): check body as well as just status code
  426. code int
  427. err error
  428. }{
  429. // standard case, standard 200 response
  430. {
  431. &store.Event{
  432. Action: store.Get,
  433. Node: &store.NodeExtern{},
  434. PrevNode: &store.NodeExtern{},
  435. },
  436. "0",
  437. http.StatusOK,
  438. nil,
  439. },
  440. // check new nodes return StatusCreated
  441. {
  442. &store.Event{
  443. Action: store.Create,
  444. Node: &store.NodeExtern{},
  445. PrevNode: &store.NodeExtern{},
  446. },
  447. "0",
  448. http.StatusCreated,
  449. nil,
  450. },
  451. }
  452. for i, tt := range tests {
  453. rw := httptest.NewRecorder()
  454. writeEvent(rw, tt.ev)
  455. if gct := rw.Header().Get("Content-Type"); gct != "application/json" {
  456. t.Errorf("case %d: bad Content-Type: got %q, want application/json", i, gct)
  457. }
  458. if gei := rw.Header().Get("X-Etcd-Index"); gei != tt.idx {
  459. t.Errorf("case %d: bad X-Etcd-Index header: got %s, want %s", i, gei, tt.idx)
  460. }
  461. if rw.Code != tt.code {
  462. t.Errorf("case %d: bad response code: got %d, want %v", i, rw.Code, tt.code)
  463. }
  464. }
  465. }
  466. type dummyWatcher struct {
  467. echan chan *store.Event
  468. }
  469. func (w *dummyWatcher) EventChan() chan *store.Event {
  470. return w.echan
  471. }
  472. func (w *dummyWatcher) Remove() {}
  473. type dummyResponseWriter struct {
  474. cnchan chan bool
  475. http.ResponseWriter
  476. }
  477. func (rw *dummyResponseWriter) CloseNotify() <-chan bool {
  478. return rw.cnchan
  479. }
  480. func TestWaitForEventChan(t *testing.T) {
  481. ctx := context.Background()
  482. ec := make(chan *store.Event)
  483. dw := &dummyWatcher{
  484. echan: ec,
  485. }
  486. w := httptest.NewRecorder()
  487. var wg sync.WaitGroup
  488. var ev *store.Event
  489. var err error
  490. wg.Add(1)
  491. go func() {
  492. ev, err = waitForEvent(ctx, w, dw)
  493. wg.Done()
  494. }()
  495. ec <- &store.Event{
  496. Action: store.Get,
  497. Node: &store.NodeExtern{
  498. Key: "/foo/bar",
  499. ModifiedIndex: 12345,
  500. },
  501. }
  502. wg.Wait()
  503. want := &store.Event{
  504. Action: store.Get,
  505. Node: &store.NodeExtern{
  506. Key: "/foo/bar",
  507. ModifiedIndex: 12345,
  508. },
  509. }
  510. if !reflect.DeepEqual(ev, want) {
  511. t.Fatalf("bad event: got %#v, want %#v", ev, want)
  512. }
  513. if err != nil {
  514. t.Fatalf("unexpected error: %v", err)
  515. }
  516. }
  517. func TestWaitForEventCloseNotify(t *testing.T) {
  518. ctx := context.Background()
  519. dw := &dummyWatcher{}
  520. cnchan := make(chan bool)
  521. w := &dummyResponseWriter{
  522. cnchan: cnchan,
  523. }
  524. var wg sync.WaitGroup
  525. var ev *store.Event
  526. var err error
  527. wg.Add(1)
  528. go func() {
  529. ev, err = waitForEvent(ctx, w, dw)
  530. wg.Done()
  531. }()
  532. close(cnchan)
  533. wg.Wait()
  534. if ev != nil {
  535. t.Fatalf("non-nil Event returned with CloseNotifier: %v", ev)
  536. }
  537. if err == nil {
  538. t.Fatalf("nil err returned with CloseNotifier!")
  539. }
  540. }
  541. func TestWaitForEventCancelledContext(t *testing.T) {
  542. cctx, cancel := context.WithCancel(context.Background())
  543. dw := &dummyWatcher{}
  544. w := httptest.NewRecorder()
  545. var wg sync.WaitGroup
  546. var ev *store.Event
  547. var err error
  548. wg.Add(1)
  549. go func() {
  550. ev, err = waitForEvent(cctx, w, dw)
  551. wg.Done()
  552. }()
  553. cancel()
  554. wg.Wait()
  555. if ev != nil {
  556. t.Fatalf("non-nil Event returned with cancelled context: %v", ev)
  557. }
  558. if err == nil {
  559. t.Fatalf("nil err returned with cancelled context!")
  560. }
  561. }
  562. func TestV2MachinesEndpoint(t *testing.T) {
  563. tests := []struct {
  564. method string
  565. wcode int
  566. }{
  567. {"GET", http.StatusOK},
  568. {"HEAD", http.StatusOK},
  569. {"POST", http.StatusMethodNotAllowed},
  570. }
  571. m := NewHandler(nil, Peers{}, time.Hour)
  572. s := httptest.NewServer(m)
  573. defer s.Close()
  574. for _, tt := range tests {
  575. req, err := http.NewRequest(tt.method, s.URL+machinesPrefix, nil)
  576. if err != nil {
  577. t.Fatal(err)
  578. }
  579. resp, err := http.DefaultClient.Do(req)
  580. if err != nil {
  581. t.Fatal(err)
  582. }
  583. if resp.StatusCode != tt.wcode {
  584. t.Errorf("StatusCode = %d, expected %d", resp.StatusCode, tt.wcode)
  585. }
  586. }
  587. }
  588. func TestServeMachines(t *testing.T) {
  589. peers := Peers{}
  590. peers.Set("0xBEEF0=localhost:8080&0xBEEF1=localhost:8081&0xBEEF2=localhost:8082")
  591. writer := httptest.NewRecorder()
  592. req, err := http.NewRequest("GET", "", nil)
  593. if err != nil {
  594. t.Fatal(err)
  595. }
  596. h := &serverHandler{peers: peers}
  597. h.serveMachines(writer, req)
  598. w := "http://localhost:8080, http://localhost:8081, http://localhost:8082"
  599. if g := writer.Body.String(); g != w {
  600. t.Errorf("body = %s, want %s", g, w)
  601. }
  602. if writer.Code != http.StatusOK {
  603. t.Errorf("header = %d, want %d", writer.Code, http.StatusOK)
  604. }
  605. }
  606. func TestPeersEndpoints(t *testing.T) {
  607. tests := []struct {
  608. peers Peers
  609. endpoints []string
  610. }{
  611. // single peer with a single address
  612. {
  613. peers: Peers(map[int64][]string{
  614. 1: []string{"192.0.2.1"},
  615. }),
  616. endpoints: []string{"http://192.0.2.1"},
  617. },
  618. // single peer with a single address with a port
  619. {
  620. peers: Peers(map[int64][]string{
  621. 1: []string{"192.0.2.1:8001"},
  622. }),
  623. endpoints: []string{"http://192.0.2.1:8001"},
  624. },
  625. // several peers explicitly unsorted
  626. {
  627. peers: Peers(map[int64][]string{
  628. 2: []string{"192.0.2.3", "192.0.2.4"},
  629. 3: []string{"192.0.2.5", "192.0.2.6"},
  630. 1: []string{"192.0.2.1", "192.0.2.2"},
  631. }),
  632. endpoints: []string{"http://192.0.2.1", "http://192.0.2.2", "http://192.0.2.3", "http://192.0.2.4", "http://192.0.2.5", "http://192.0.2.6"},
  633. },
  634. // no peers
  635. {
  636. peers: Peers(map[int64][]string{}),
  637. endpoints: []string{},
  638. },
  639. // peer with no endpoints
  640. {
  641. peers: Peers(map[int64][]string{
  642. 3: []string{},
  643. }),
  644. endpoints: []string{},
  645. },
  646. }
  647. for i, tt := range tests {
  648. endpoints := tt.peers.Endpoints()
  649. if !reflect.DeepEqual(tt.endpoints, endpoints) {
  650. t.Errorf("#%d: peers.Endpoints() incorrect: want=%#v got=%#v", i, tt.endpoints, endpoints)
  651. }
  652. }
  653. }
  654. func TestAllowMethod(t *testing.T) {
  655. tests := []struct {
  656. m string
  657. ms []string
  658. w bool
  659. wh string
  660. }{
  661. // Accepted methods
  662. {
  663. m: "GET",
  664. ms: []string{"GET", "POST", "PUT"},
  665. w: true,
  666. },
  667. {
  668. m: "POST",
  669. ms: []string{"POST"},
  670. w: true,
  671. },
  672. // Made-up methods no good
  673. {
  674. m: "FAKE",
  675. ms: []string{"GET", "POST", "PUT"},
  676. w: false,
  677. wh: "GET,POST,PUT",
  678. },
  679. // Empty methods no good
  680. {
  681. m: "",
  682. ms: []string{"GET", "POST"},
  683. w: false,
  684. wh: "GET,POST",
  685. },
  686. // Empty accepted methods no good
  687. {
  688. m: "GET",
  689. ms: []string{""},
  690. w: false,
  691. wh: "",
  692. },
  693. // No methods accepted
  694. {
  695. m: "GET",
  696. ms: []string{},
  697. w: false,
  698. wh: "",
  699. },
  700. }
  701. for i, tt := range tests {
  702. rw := httptest.NewRecorder()
  703. g := allowMethod(rw, tt.m, tt.ms...)
  704. if g != tt.w {
  705. t.Errorf("#%d: got allowMethod()=%t, want %t", i, g, tt.w)
  706. }
  707. if !tt.w {
  708. if rw.Code != http.StatusMethodNotAllowed {
  709. t.Errorf("#%d: code=%d, want %d", i, rw.Code, http.StatusMethodNotAllowed)
  710. }
  711. gh := rw.Header().Get("Allow")
  712. if gh != tt.wh {
  713. t.Errorf("#%d: Allow header=%q, want %q", i, gh, tt.wh)
  714. }
  715. }
  716. }
  717. }
  718. // errServer implements the etcd.Server interface for testing.
  719. // It returns the given error from any Do/Process calls.
  720. type errServer struct {
  721. err error
  722. }
  723. func (fs *errServer) Do(ctx context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
  724. return etcdserver.Response{}, fs.err
  725. }
  726. func (fs *errServer) Process(ctx context.Context, m raftpb.Message) error {
  727. return fs.err
  728. }
  729. func (fs *errServer) Start() {}
  730. func (fs *errServer) Stop() {}
  731. // errReader implements io.Reader to facilitate a broken request.
  732. type errReader struct{}
  733. func (er *errReader) Read(_ []byte) (int, error) { return 0, errors.New("some error") }
  734. func mustMarshalMsg(t *testing.T, m raftpb.Message) []byte {
  735. json, err := m.Marshal()
  736. if err != nil {
  737. t.Fatalf("error marshalling raft Message: %#v", err)
  738. }
  739. return json
  740. }
  741. func TestServeRaft(t *testing.T) {
  742. testCases := []struct {
  743. method string
  744. body io.Reader
  745. serverErr error
  746. wcode int
  747. }{
  748. {
  749. // bad method
  750. "GET",
  751. bytes.NewReader(
  752. mustMarshalMsg(
  753. t,
  754. raftpb.Message{},
  755. ),
  756. ),
  757. nil,
  758. http.StatusMethodNotAllowed,
  759. },
  760. {
  761. // bad method
  762. "PUT",
  763. bytes.NewReader(
  764. mustMarshalMsg(
  765. t,
  766. raftpb.Message{},
  767. ),
  768. ),
  769. nil,
  770. http.StatusMethodNotAllowed,
  771. },
  772. {
  773. // bad method
  774. "DELETE",
  775. bytes.NewReader(
  776. mustMarshalMsg(
  777. t,
  778. raftpb.Message{},
  779. ),
  780. ),
  781. nil,
  782. http.StatusMethodNotAllowed,
  783. },
  784. {
  785. // bad request body
  786. "POST",
  787. &errReader{},
  788. nil,
  789. http.StatusBadRequest,
  790. },
  791. {
  792. // bad request protobuf
  793. "POST",
  794. strings.NewReader("malformed garbage"),
  795. nil,
  796. http.StatusBadRequest,
  797. },
  798. {
  799. // good request, etcdserver.Server error
  800. "POST",
  801. bytes.NewReader(
  802. mustMarshalMsg(
  803. t,
  804. raftpb.Message{},
  805. ),
  806. ),
  807. errors.New("some error"),
  808. http.StatusInternalServerError,
  809. },
  810. {
  811. // good request
  812. "POST",
  813. bytes.NewReader(
  814. mustMarshalMsg(
  815. t,
  816. raftpb.Message{},
  817. ),
  818. ),
  819. nil,
  820. http.StatusNoContent,
  821. },
  822. }
  823. for i, tt := range testCases {
  824. req, err := http.NewRequest(tt.method, "foo", tt.body)
  825. if err != nil {
  826. t.Fatalf("#%d: could not create request: %#v", i, err)
  827. }
  828. h := &serverHandler{
  829. timeout: time.Hour,
  830. server: &errServer{tt.serverErr},
  831. peers: nil,
  832. }
  833. rw := httptest.NewRecorder()
  834. h.serveRaft(rw, req)
  835. if rw.Code != tt.wcode {
  836. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  837. }
  838. }
  839. }
  840. // resServer implements the etcd.Server interface for testing.
  841. // It returns the given responsefrom any Do calls, and nil error
  842. type resServer struct {
  843. res etcdserver.Response
  844. }
  845. func (rs *resServer) Do(_ context.Context, _ etcdserverpb.Request) (etcdserver.Response, error) {
  846. return rs.res, nil
  847. }
  848. func (rs *resServer) Process(_ context.Context, _ raftpb.Message) error { return nil }
  849. func (rs *resServer) Start() {}
  850. func (rs *resServer) Stop() {}
  851. func mustMarshalEvent(t *testing.T, ev *store.Event) string {
  852. b := new(bytes.Buffer)
  853. if err := json.NewEncoder(b).Encode(ev); err != nil {
  854. t.Fatalf("error marshalling event %#v: %v", ev, err)
  855. }
  856. return b.String()
  857. }
  858. func TestBadServeKeys(t *testing.T) {
  859. testBadCases := []struct {
  860. req *http.Request
  861. server etcdserver.Server
  862. wcode int
  863. }{
  864. {
  865. // bad method
  866. &http.Request{
  867. Method: "CONNECT",
  868. },
  869. &resServer{},
  870. http.StatusMethodNotAllowed,
  871. },
  872. {
  873. // bad method
  874. &http.Request{
  875. Method: "TRACE",
  876. },
  877. &resServer{},
  878. http.StatusMethodNotAllowed,
  879. },
  880. {
  881. // parseRequest error
  882. &http.Request{
  883. Body: nil,
  884. Method: "PUT",
  885. },
  886. &resServer{},
  887. http.StatusBadRequest,
  888. },
  889. {
  890. // etcdserver.Server error
  891. mustNewRequest(t, "foo"),
  892. &errServer{
  893. errors.New("blah"),
  894. },
  895. http.StatusInternalServerError,
  896. },
  897. {
  898. // timeout waiting for event (watcher never returns)
  899. mustNewRequest(t, "foo"),
  900. &resServer{
  901. etcdserver.Response{
  902. Watcher: &dummyWatcher{},
  903. },
  904. },
  905. http.StatusGatewayTimeout,
  906. },
  907. {
  908. // non-event/watcher response from etcdserver.Server
  909. mustNewRequest(t, "foo"),
  910. &resServer{
  911. etcdserver.Response{},
  912. },
  913. http.StatusInternalServerError,
  914. },
  915. }
  916. for i, tt := range testBadCases {
  917. h := &serverHandler{
  918. timeout: 0, // context times out immediately
  919. server: tt.server,
  920. peers: nil,
  921. }
  922. rw := httptest.NewRecorder()
  923. h.serveKeys(rw, tt.req)
  924. if rw.Code != tt.wcode {
  925. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  926. }
  927. }
  928. }
  929. func TestServeKeysEvent(t *testing.T) {
  930. req := mustNewRequest(t, "foo")
  931. server := &resServer{
  932. etcdserver.Response{
  933. Event: &store.Event{
  934. Action: store.Get,
  935. Node: &store.NodeExtern{},
  936. },
  937. },
  938. }
  939. h := &serverHandler{
  940. timeout: time.Hour,
  941. server: server,
  942. peers: nil,
  943. }
  944. rw := httptest.NewRecorder()
  945. h.serveKeys(rw, req)
  946. wcode := http.StatusOK
  947. wbody := mustMarshalEvent(
  948. t,
  949. &store.Event{
  950. Action: store.Get,
  951. Node: &store.NodeExtern{},
  952. },
  953. )
  954. if rw.Code != wcode {
  955. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  956. }
  957. g := rw.Body.String()
  958. if g != wbody {
  959. t.Errorf("got body=%#v, want %#v", g, wbody)
  960. }
  961. }
  962. func TestServeKeysWatch(t *testing.T) {
  963. req := mustNewRequest(t, "/foo/bar")
  964. ec := make(chan *store.Event)
  965. dw := &dummyWatcher{
  966. echan: ec,
  967. }
  968. server := &resServer{
  969. etcdserver.Response{
  970. Watcher: dw,
  971. },
  972. }
  973. h := &serverHandler{
  974. timeout: time.Hour,
  975. server: server,
  976. peers: nil,
  977. }
  978. go func() {
  979. ec <- &store.Event{
  980. Action: store.Get,
  981. Node: &store.NodeExtern{},
  982. }
  983. }()
  984. rw := httptest.NewRecorder()
  985. h.serveKeys(rw, req)
  986. wcode := http.StatusOK
  987. wbody := mustMarshalEvent(
  988. t,
  989. &store.Event{
  990. Action: store.Get,
  991. Node: &store.NodeExtern{},
  992. },
  993. )
  994. if rw.Code != wcode {
  995. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  996. }
  997. g := rw.Body.String()
  998. if g != wbody {
  999. t.Errorf("got body=%#v, want %#v", g, wbody)
  1000. }
  1001. }