http_test.go 25 KB

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