http_test.go 33 KB

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