http_test.go 26 KB

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