http_test.go 34 KB

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