http_test.go 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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. }
  551. func (w *dummyWatcher) EventChan() chan *store.Event {
  552. return w.echan
  553. }
  554. func (w *dummyWatcher) Remove() {}
  555. func TestV2MachinesEndpoint(t *testing.T) {
  556. tests := []struct {
  557. method string
  558. wcode int
  559. }{
  560. {"GET", http.StatusOK},
  561. {"HEAD", http.StatusOK},
  562. {"POST", http.StatusMethodNotAllowed},
  563. }
  564. m := NewClientHandler(nil, &fakeCluster{}, time.Hour)
  565. s := httptest.NewServer(m)
  566. defer s.Close()
  567. for _, tt := range tests {
  568. req, err := http.NewRequest(tt.method, s.URL+machinesPrefix, nil)
  569. if err != nil {
  570. t.Fatal(err)
  571. }
  572. resp, err := http.DefaultClient.Do(req)
  573. if err != nil {
  574. t.Fatal(err)
  575. }
  576. if resp.StatusCode != tt.wcode {
  577. t.Errorf("StatusCode = %d, expected %d", resp.StatusCode, tt.wcode)
  578. }
  579. }
  580. }
  581. func TestServeMachines(t *testing.T) {
  582. cluster := &fakeCluster{
  583. members: []etcdserver.Member{
  584. {ID: 0xBEEF0, ClientURLs: []string{"localhost:8080"}},
  585. {ID: 0xBEEF1, ClientURLs: []string{"localhost:8081"}},
  586. {ID: 0xBEEF2, ClientURLs: []string{"localhost:8082"}},
  587. },
  588. }
  589. writer := httptest.NewRecorder()
  590. req, err := http.NewRequest("GET", "", nil)
  591. if err != nil {
  592. t.Fatal(err)
  593. }
  594. h := &serverHandler{clusterStore: cluster}
  595. h.serveMachines(writer, req)
  596. w := "http://localhost:8080, http://localhost:8081, http://localhost:8082"
  597. if g := writer.Body.String(); g != w {
  598. t.Errorf("body = %s, want %s", g, w)
  599. }
  600. if writer.Code != http.StatusOK {
  601. t.Errorf("header = %d, want %d", writer.Code, http.StatusOK)
  602. }
  603. }
  604. func TestAllowMethod(t *testing.T) {
  605. tests := []struct {
  606. m string
  607. ms []string
  608. w bool
  609. wh string
  610. }{
  611. // Accepted methods
  612. {
  613. m: "GET",
  614. ms: []string{"GET", "POST", "PUT"},
  615. w: true,
  616. },
  617. {
  618. m: "POST",
  619. ms: []string{"POST"},
  620. w: true,
  621. },
  622. // Made-up methods no good
  623. {
  624. m: "FAKE",
  625. ms: []string{"GET", "POST", "PUT"},
  626. w: false,
  627. wh: "GET,POST,PUT",
  628. },
  629. // Empty methods no good
  630. {
  631. m: "",
  632. ms: []string{"GET", "POST"},
  633. w: false,
  634. wh: "GET,POST",
  635. },
  636. // Empty accepted methods no good
  637. {
  638. m: "GET",
  639. ms: []string{""},
  640. w: false,
  641. wh: "",
  642. },
  643. // No methods accepted
  644. {
  645. m: "GET",
  646. ms: []string{},
  647. w: false,
  648. wh: "",
  649. },
  650. }
  651. for i, tt := range tests {
  652. rw := httptest.NewRecorder()
  653. g := allowMethod(rw, tt.m, tt.ms...)
  654. if g != tt.w {
  655. t.Errorf("#%d: got allowMethod()=%t, want %t", i, g, tt.w)
  656. }
  657. if !tt.w {
  658. if rw.Code != http.StatusMethodNotAllowed {
  659. t.Errorf("#%d: code=%d, want %d", i, rw.Code, http.StatusMethodNotAllowed)
  660. }
  661. gh := rw.Header().Get("Allow")
  662. if gh != tt.wh {
  663. t.Errorf("#%d: Allow header=%q, want %q", i, gh, tt.wh)
  664. }
  665. }
  666. }
  667. }
  668. // errServer implements the etcd.Server interface for testing.
  669. // It returns the given error from any Do/Process calls.
  670. type errServer struct {
  671. err error
  672. }
  673. func (fs *errServer) Do(ctx context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
  674. return etcdserver.Response{}, fs.err
  675. }
  676. func (fs *errServer) Process(ctx context.Context, m raftpb.Message) error {
  677. return fs.err
  678. }
  679. func (fs *errServer) Start() {}
  680. func (fs *errServer) Stop() {}
  681. // errReader implements io.Reader to facilitate a broken request.
  682. type errReader struct{}
  683. func (er *errReader) Read(_ []byte) (int, error) { return 0, errors.New("some error") }
  684. func mustMarshalMsg(t *testing.T, m raftpb.Message) []byte {
  685. json, err := m.Marshal()
  686. if err != nil {
  687. t.Fatalf("error marshalling raft Message: %#v", err)
  688. }
  689. return json
  690. }
  691. func TestServeRaft(t *testing.T) {
  692. testCases := []struct {
  693. method string
  694. body io.Reader
  695. serverErr error
  696. wcode int
  697. }{
  698. {
  699. // bad method
  700. "GET",
  701. bytes.NewReader(
  702. mustMarshalMsg(
  703. t,
  704. raftpb.Message{},
  705. ),
  706. ),
  707. nil,
  708. http.StatusMethodNotAllowed,
  709. },
  710. {
  711. // bad method
  712. "PUT",
  713. bytes.NewReader(
  714. mustMarshalMsg(
  715. t,
  716. raftpb.Message{},
  717. ),
  718. ),
  719. nil,
  720. http.StatusMethodNotAllowed,
  721. },
  722. {
  723. // bad method
  724. "DELETE",
  725. bytes.NewReader(
  726. mustMarshalMsg(
  727. t,
  728. raftpb.Message{},
  729. ),
  730. ),
  731. nil,
  732. http.StatusMethodNotAllowed,
  733. },
  734. {
  735. // bad request body
  736. "POST",
  737. &errReader{},
  738. nil,
  739. http.StatusBadRequest,
  740. },
  741. {
  742. // bad request protobuf
  743. "POST",
  744. strings.NewReader("malformed garbage"),
  745. nil,
  746. http.StatusBadRequest,
  747. },
  748. {
  749. // good request, etcdserver.Server error
  750. "POST",
  751. bytes.NewReader(
  752. mustMarshalMsg(
  753. t,
  754. raftpb.Message{},
  755. ),
  756. ),
  757. errors.New("some error"),
  758. http.StatusInternalServerError,
  759. },
  760. {
  761. // good request
  762. "POST",
  763. bytes.NewReader(
  764. mustMarshalMsg(
  765. t,
  766. raftpb.Message{},
  767. ),
  768. ),
  769. nil,
  770. http.StatusNoContent,
  771. },
  772. }
  773. for i, tt := range testCases {
  774. req, err := http.NewRequest(tt.method, "foo", tt.body)
  775. if err != nil {
  776. t.Fatalf("#%d: could not create request: %#v", i, err)
  777. }
  778. h := &serverHandler{
  779. timeout: time.Hour,
  780. server: &errServer{tt.serverErr},
  781. }
  782. rw := httptest.NewRecorder()
  783. h.serveRaft(rw, req)
  784. if rw.Code != tt.wcode {
  785. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  786. }
  787. }
  788. }
  789. // resServer implements the etcd.Server interface for testing.
  790. // It returns the given responsefrom any Do calls, and nil error
  791. type resServer struct {
  792. res etcdserver.Response
  793. }
  794. func (rs *resServer) Do(_ context.Context, _ etcdserverpb.Request) (etcdserver.Response, error) {
  795. return rs.res, nil
  796. }
  797. func (rs *resServer) Process(_ context.Context, _ raftpb.Message) error { return nil }
  798. func (rs *resServer) Start() {}
  799. func (rs *resServer) Stop() {}
  800. func mustMarshalEvent(t *testing.T, ev *store.Event) string {
  801. b := new(bytes.Buffer)
  802. if err := json.NewEncoder(b).Encode(ev); err != nil {
  803. t.Fatalf("error marshalling event %#v: %v", ev, err)
  804. }
  805. return b.String()
  806. }
  807. func TestBadServeKeys(t *testing.T) {
  808. testBadCases := []struct {
  809. req *http.Request
  810. server etcdserver.Server
  811. wcode int
  812. }{
  813. {
  814. // bad method
  815. &http.Request{
  816. Method: "CONNECT",
  817. },
  818. &resServer{},
  819. http.StatusMethodNotAllowed,
  820. },
  821. {
  822. // bad method
  823. &http.Request{
  824. Method: "TRACE",
  825. },
  826. &resServer{},
  827. http.StatusMethodNotAllowed,
  828. },
  829. {
  830. // parseRequest error
  831. &http.Request{
  832. Body: nil,
  833. Method: "PUT",
  834. },
  835. &resServer{},
  836. http.StatusBadRequest,
  837. },
  838. {
  839. // etcdserver.Server error
  840. mustNewRequest(t, "foo"),
  841. &errServer{
  842. errors.New("blah"),
  843. },
  844. http.StatusInternalServerError,
  845. },
  846. {
  847. // non-event/watcher response from etcdserver.Server
  848. mustNewRequest(t, "foo"),
  849. &resServer{
  850. etcdserver.Response{},
  851. },
  852. http.StatusInternalServerError,
  853. },
  854. }
  855. for i, tt := range testBadCases {
  856. h := &serverHandler{
  857. timeout: 0, // context times out immediately
  858. server: tt.server,
  859. }
  860. rw := httptest.NewRecorder()
  861. h.serveKeys(rw, tt.req)
  862. if rw.Code != tt.wcode {
  863. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  864. }
  865. }
  866. }
  867. func TestServeKeysEvent(t *testing.T) {
  868. req := mustNewRequest(t, "foo")
  869. server := &resServer{
  870. etcdserver.Response{
  871. Event: &store.Event{
  872. Action: store.Get,
  873. Node: &store.NodeExtern{},
  874. },
  875. },
  876. }
  877. h := &serverHandler{
  878. timeout: time.Hour,
  879. server: server,
  880. timer: &dummyRaftTimer{},
  881. }
  882. rw := httptest.NewRecorder()
  883. h.serveKeys(rw, req)
  884. wcode := http.StatusOK
  885. wbody := mustMarshalEvent(
  886. t,
  887. &store.Event{
  888. Action: store.Get,
  889. Node: &store.NodeExtern{},
  890. },
  891. )
  892. if rw.Code != wcode {
  893. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  894. }
  895. g := rw.Body.String()
  896. if g != wbody {
  897. t.Errorf("got body=%#v, want %#v", g, wbody)
  898. }
  899. }
  900. func TestServeKeysWatch(t *testing.T) {
  901. req := mustNewRequest(t, "/foo/bar")
  902. ec := make(chan *store.Event)
  903. dw := &dummyWatcher{
  904. echan: ec,
  905. }
  906. server := &resServer{
  907. etcdserver.Response{
  908. Watcher: dw,
  909. },
  910. }
  911. h := &serverHandler{
  912. timeout: time.Hour,
  913. server: server,
  914. timer: &dummyRaftTimer{},
  915. }
  916. go func() {
  917. ec <- &store.Event{
  918. Action: store.Get,
  919. Node: &store.NodeExtern{},
  920. }
  921. }()
  922. rw := httptest.NewRecorder()
  923. h.serveKeys(rw, req)
  924. wcode := http.StatusOK
  925. wbody := mustMarshalEvent(
  926. t,
  927. &store.Event{
  928. Action: store.Get,
  929. Node: &store.NodeExtern{},
  930. },
  931. )
  932. if rw.Code != wcode {
  933. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  934. }
  935. g := rw.Body.String()
  936. if g != wbody {
  937. t.Errorf("got body=%#v, want %#v", g, wbody)
  938. }
  939. }
  940. func TestHandleWatch(t *testing.T) {
  941. rw := httptest.NewRecorder()
  942. wa := &dummyWatcher{
  943. echan: make(chan *store.Event, 1),
  944. }
  945. wa.echan <- &store.Event{
  946. Action: store.Get,
  947. Node: &store.NodeExtern{},
  948. }
  949. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  950. wcode := http.StatusOK
  951. wct := "application/json"
  952. wri := "100"
  953. wrt := "5"
  954. wbody := mustMarshalEvent(
  955. t,
  956. &store.Event{
  957. Action: store.Get,
  958. Node: &store.NodeExtern{},
  959. },
  960. )
  961. if rw.Code != wcode {
  962. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  963. }
  964. h := rw.Header()
  965. if ct := h.Get("Content-Type"); ct != wct {
  966. t.Errorf("Content-Type=%q, want %q", ct, wct)
  967. }
  968. if ri := h.Get("X-Raft-Index"); ri != wri {
  969. t.Errorf("X-Raft-Index=%q, want %q", ri, wri)
  970. }
  971. if rt := h.Get("X-Raft-Term"); rt != wrt {
  972. t.Errorf("X-Raft-Term=%q, want %q", rt, wrt)
  973. }
  974. g := rw.Body.String()
  975. if g != wbody {
  976. t.Errorf("got body=%#v, want %#v", g, wbody)
  977. }
  978. }
  979. func TestHandleWatchNoEvent(t *testing.T) {
  980. rw := httptest.NewRecorder()
  981. wa := &dummyWatcher{
  982. echan: make(chan *store.Event, 1),
  983. }
  984. close(wa.echan)
  985. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  986. wcode := http.StatusOK
  987. wct := "application/json"
  988. wbody := ""
  989. if rw.Code != wcode {
  990. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  991. }
  992. h := rw.Header()
  993. if ct := h.Get("Content-Type"); ct != wct {
  994. t.Errorf("Content-Type=%q, want %q", ct, wct)
  995. }
  996. g := rw.Body.String()
  997. if g != wbody {
  998. t.Errorf("got body=%#v, want %#v", g, wbody)
  999. }
  1000. }
  1001. type recordingCloseNotifier struct {
  1002. *httptest.ResponseRecorder
  1003. cn chan bool
  1004. }
  1005. func (rcn *recordingCloseNotifier) CloseNotify() <-chan bool {
  1006. return rcn.cn
  1007. }
  1008. func TestHandleWatchCloseNotified(t *testing.T) {
  1009. rw := &recordingCloseNotifier{
  1010. ResponseRecorder: httptest.NewRecorder(),
  1011. cn: make(chan bool, 1),
  1012. }
  1013. rw.cn <- true
  1014. wa := &dummyWatcher{}
  1015. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  1016. wcode := http.StatusOK
  1017. wct := "application/json"
  1018. wbody := ""
  1019. if rw.Code != wcode {
  1020. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1021. }
  1022. h := rw.Header()
  1023. if ct := h.Get("Content-Type"); ct != wct {
  1024. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1025. }
  1026. g := rw.Body.String()
  1027. if g != wbody {
  1028. t.Errorf("got body=%#v, want %#v", g, wbody)
  1029. }
  1030. }
  1031. func TestHandleWatchTimeout(t *testing.T) {
  1032. rw := httptest.NewRecorder()
  1033. wa := &dummyWatcher{}
  1034. // Simulate a timed-out context
  1035. ctx, cancel := context.WithCancel(context.Background())
  1036. cancel()
  1037. handleWatch(ctx, rw, wa, false, dummyRaftTimer{})
  1038. wcode := http.StatusOK
  1039. wct := "application/json"
  1040. wbody := ""
  1041. if rw.Code != wcode {
  1042. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1043. }
  1044. h := rw.Header()
  1045. if ct := h.Get("Content-Type"); ct != wct {
  1046. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1047. }
  1048. g := rw.Body.String()
  1049. if g != wbody {
  1050. t.Errorf("got body=%#v, want %#v", g, wbody)
  1051. }
  1052. }
  1053. // flushingRecorder provides a channel to allow users to block until the Recorder is Flushed()
  1054. type flushingRecorder struct {
  1055. *httptest.ResponseRecorder
  1056. ch chan struct{}
  1057. }
  1058. func (fr *flushingRecorder) Flush() {
  1059. fr.ResponseRecorder.Flush()
  1060. fr.ch <- struct{}{}
  1061. }
  1062. func TestHandleWatchStreaming(t *testing.T) {
  1063. rw := &flushingRecorder{
  1064. httptest.NewRecorder(),
  1065. make(chan struct{}, 1),
  1066. }
  1067. wa := &dummyWatcher{
  1068. echan: make(chan *store.Event),
  1069. }
  1070. // Launch the streaming handler in the background with a cancellable context
  1071. ctx, cancel := context.WithCancel(context.Background())
  1072. done := make(chan struct{})
  1073. go func() {
  1074. handleWatch(ctx, rw, wa, true, dummyRaftTimer{})
  1075. close(done)
  1076. }()
  1077. // Expect one Flush for the headers etc.
  1078. select {
  1079. case <-rw.ch:
  1080. case <-time.After(time.Second):
  1081. t.Fatalf("timed out waiting for flush")
  1082. }
  1083. // Expect headers but no body
  1084. wcode := http.StatusOK
  1085. wct := "application/json"
  1086. wbody := ""
  1087. if rw.Code != wcode {
  1088. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1089. }
  1090. h := rw.Header()
  1091. if ct := h.Get("Content-Type"); ct != wct {
  1092. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1093. }
  1094. g := rw.Body.String()
  1095. if g != wbody {
  1096. t.Errorf("got body=%#v, want %#v", g, wbody)
  1097. }
  1098. // Now send the first event
  1099. select {
  1100. case wa.echan <- &store.Event{
  1101. Action: store.Get,
  1102. Node: &store.NodeExtern{},
  1103. }:
  1104. case <-time.After(time.Second):
  1105. t.Fatal("timed out waiting for send")
  1106. }
  1107. // Wait for it to be flushed...
  1108. select {
  1109. case <-rw.ch:
  1110. case <-time.After(time.Second):
  1111. t.Fatalf("timed out waiting for flush")
  1112. }
  1113. // And check the body is as expected
  1114. wbody = mustMarshalEvent(
  1115. t,
  1116. &store.Event{
  1117. Action: store.Get,
  1118. Node: &store.NodeExtern{},
  1119. },
  1120. )
  1121. g = rw.Body.String()
  1122. if g != wbody {
  1123. t.Errorf("got body=%#v, want %#v", g, wbody)
  1124. }
  1125. // Rinse and repeat
  1126. select {
  1127. case wa.echan <- &store.Event{
  1128. Action: store.Get,
  1129. Node: &store.NodeExtern{},
  1130. }:
  1131. case <-time.After(time.Second):
  1132. t.Fatal("timed out waiting for send")
  1133. }
  1134. select {
  1135. case <-rw.ch:
  1136. case <-time.After(time.Second):
  1137. t.Fatalf("timed out waiting for flush")
  1138. }
  1139. // This time, we expect to see both events
  1140. wbody = wbody + wbody
  1141. g = rw.Body.String()
  1142. if g != wbody {
  1143. t.Errorf("got body=%#v, want %#v", g, wbody)
  1144. }
  1145. // Finally, time out the connection and ensure the serving goroutine returns
  1146. cancel()
  1147. select {
  1148. case <-done:
  1149. case <-time.After(time.Second):
  1150. t.Fatalf("timed out waiting for done")
  1151. }
  1152. }
  1153. type fakeCluster struct {
  1154. members []etcdserver.Member
  1155. }
  1156. func (c *fakeCluster) Get() etcdserver.Cluster {
  1157. cl := &etcdserver.Cluster{}
  1158. cl.AddSlice(c.members)
  1159. return *cl
  1160. }
  1161. func (c *fakeCluster) Delete(id int64) { return }