http_test.go 26 KB

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