v2_http_kv_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. /*
  2. Copyright 2014 CoreOS Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package etcd
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "net/http"
  20. "net/url"
  21. "reflect"
  22. "strings"
  23. "testing"
  24. "time"
  25. )
  26. func TestV2Set(t *testing.T) {
  27. es, hs := buildCluster(1, false)
  28. u := hs[0].URL
  29. tc := NewTestClient()
  30. v := url.Values{}
  31. v.Set("value", "bar")
  32. tests := []struct {
  33. relativeURL string
  34. value url.Values
  35. wStatus int
  36. w string
  37. }{
  38. {
  39. "/v2/keys/foo/bar",
  40. v,
  41. http.StatusCreated,
  42. `{"action":"set","node":{"key":"/foo/bar","value":"bar","modifiedIndex":2,"createdIndex":2}}`,
  43. },
  44. {
  45. "/v2/keys/foodir?dir=true",
  46. url.Values{},
  47. http.StatusCreated,
  48. `{"action":"set","node":{"key":"/foodir","dir":true,"modifiedIndex":3,"createdIndex":3}}`,
  49. },
  50. {
  51. "/v2/keys/fooempty",
  52. url.Values(map[string][]string{"value": {""}}),
  53. http.StatusCreated,
  54. `{"action":"set","node":{"key":"/fooempty","value":"","modifiedIndex":4,"createdIndex":4}}`,
  55. },
  56. }
  57. for i, tt := range tests {
  58. resp, err := tc.PutForm(fmt.Sprintf("%s%s", u, tt.relativeURL), tt.value)
  59. if err != nil {
  60. t.Errorf("#%d: err = %v, want nil", i, err)
  61. }
  62. g := string(tc.ReadBody(resp))
  63. if g != tt.w {
  64. t.Errorf("#%d: body = %v, want %v", i, g, tt.w)
  65. }
  66. if resp.StatusCode != tt.wStatus {
  67. t.Errorf("#%d: status = %d, want %d", i, resp.StatusCode, tt.wStatus)
  68. }
  69. }
  70. destoryCluster(t, es, hs)
  71. afterTest(t)
  72. }
  73. func TestV2CreateUpdate(t *testing.T) {
  74. es, hs := buildCluster(1, false)
  75. u := hs[0].URL
  76. tc := NewTestClient()
  77. tests := []struct {
  78. relativeURL string
  79. value url.Values
  80. wStatus int
  81. w map[string]interface{}
  82. }{
  83. // key with ttl
  84. {
  85. "/v2/keys/ttl/foo",
  86. url.Values(map[string][]string{"value": {"XXX"}, "ttl": {"20"}}),
  87. http.StatusCreated,
  88. map[string]interface{}{
  89. "node": map[string]interface{}{
  90. "value": "XXX",
  91. "ttl": float64(20),
  92. },
  93. },
  94. },
  95. // key with bad ttl
  96. {
  97. "/v2/keys/ttl/foo",
  98. url.Values(map[string][]string{"value": {"XXX"}, "ttl": {"bad_ttl"}}),
  99. http.StatusBadRequest,
  100. map[string]interface{}{
  101. "errorCode": float64(202),
  102. "message": "The given TTL in POST form is not a number",
  103. "cause": "Update",
  104. },
  105. },
  106. // create key
  107. {
  108. "/v2/keys/create/foo",
  109. url.Values(map[string][]string{"value": {"XXX"}, "prevExist": {"false"}}),
  110. http.StatusCreated,
  111. map[string]interface{}{
  112. "node": map[string]interface{}{
  113. "value": "XXX",
  114. },
  115. },
  116. },
  117. // created key failed
  118. {
  119. "/v2/keys/create/foo",
  120. url.Values(map[string][]string{"value": {"XXX"}, "prevExist": {"false"}}),
  121. http.StatusPreconditionFailed,
  122. map[string]interface{}{
  123. "errorCode": float64(105),
  124. "message": "Key already exists",
  125. "cause": "/create/foo",
  126. },
  127. },
  128. // update the newly created key with ttl
  129. {
  130. "/v2/keys/create/foo",
  131. url.Values(map[string][]string{"value": {"YYY"}, "prevExist": {"true"}, "ttl": {"20"}}),
  132. http.StatusOK,
  133. map[string]interface{}{
  134. "node": map[string]interface{}{
  135. "value": "YYY",
  136. "ttl": float64(20),
  137. },
  138. "action": "update",
  139. },
  140. },
  141. // update the ttl to none
  142. {
  143. "/v2/keys/create/foo",
  144. url.Values(map[string][]string{"value": {"ZZZ"}, "prevExist": {"true"}}),
  145. http.StatusOK,
  146. map[string]interface{}{
  147. "node": map[string]interface{}{
  148. "value": "ZZZ",
  149. },
  150. "action": "update",
  151. },
  152. },
  153. // update on a non-existing key
  154. {
  155. "/v2/keys/nonexist",
  156. url.Values(map[string][]string{"value": {"XXX"}, "prevExist": {"true"}}),
  157. http.StatusNotFound,
  158. map[string]interface{}{
  159. "errorCode": float64(100),
  160. "message": "Key not found",
  161. "cause": "/nonexist",
  162. },
  163. },
  164. }
  165. for i, tt := range tests {
  166. resp, _ := tc.PutForm(fmt.Sprintf("%s%s", u, tt.relativeURL), tt.value)
  167. if resp.StatusCode != tt.wStatus {
  168. t.Errorf("#%d: status = %d, want %d", i, resp.StatusCode, tt.wStatus)
  169. }
  170. if err := checkBody(tc.ReadBodyJSON(resp), tt.w); err != nil {
  171. t.Errorf("#%d: %v", i, err)
  172. }
  173. }
  174. destoryCluster(t, es, hs)
  175. afterTest(t)
  176. }
  177. func TestV2CAS(t *testing.T) {
  178. es, hs := buildCluster(1, false)
  179. u := hs[0].URL
  180. tc := NewTestClient()
  181. tests := []struct {
  182. relativeURL string
  183. value url.Values
  184. wStatus int
  185. w map[string]interface{}
  186. }{
  187. {
  188. "/v2/keys/cas/foo",
  189. url.Values(map[string][]string{"value": {"XXX"}}),
  190. http.StatusCreated,
  191. nil,
  192. },
  193. {
  194. "/v2/keys/cas/foo",
  195. url.Values(map[string][]string{"value": {"YYY"}, "prevIndex": {"2"}}),
  196. http.StatusOK,
  197. map[string]interface{}{
  198. "node": map[string]interface{}{
  199. "value": "YYY",
  200. "modifiedIndex": float64(3),
  201. },
  202. "action": "compareAndSwap",
  203. },
  204. },
  205. {
  206. "/v2/keys/cas/foo",
  207. url.Values(map[string][]string{"value": {"YYY"}, "prevIndex": {"10"}}),
  208. http.StatusPreconditionFailed,
  209. map[string]interface{}{
  210. "errorCode": float64(101),
  211. "message": "Compare failed",
  212. "cause": "[10 != 3]",
  213. "index": float64(3),
  214. },
  215. },
  216. {
  217. "/v2/keys/cas/foo",
  218. url.Values(map[string][]string{"value": {"YYY"}, "prevIndex": {"bad_index"}}),
  219. http.StatusBadRequest,
  220. map[string]interface{}{
  221. "errorCode": float64(203),
  222. "message": "The given index in POST form is not a number",
  223. "cause": "CompareAndSwap",
  224. },
  225. },
  226. {
  227. "/v2/keys/cas/foo",
  228. url.Values(map[string][]string{"value": {"ZZZ"}, "prevValue": {"YYY"}}),
  229. http.StatusOK,
  230. map[string]interface{}{
  231. "node": map[string]interface{}{
  232. "value": "ZZZ",
  233. },
  234. "action": "compareAndSwap",
  235. },
  236. },
  237. {
  238. "/v2/keys/cas/foo",
  239. url.Values(map[string][]string{"value": {"XXX"}, "prevValue": {"bad_value"}}),
  240. http.StatusPreconditionFailed,
  241. map[string]interface{}{
  242. "errorCode": float64(101),
  243. "message": "Compare failed",
  244. "cause": "[bad_value != ZZZ]",
  245. },
  246. },
  247. // prevValue is required
  248. {
  249. "/v2/keys/cas/foo",
  250. url.Values(map[string][]string{"value": {"XXX"}, "prevValue": {""}}),
  251. http.StatusBadRequest,
  252. map[string]interface{}{
  253. "errorCode": float64(201),
  254. "message": "PrevValue is Required in POST form",
  255. "cause": "CompareAndSwap",
  256. },
  257. },
  258. {
  259. "/v2/keys/cas/foo",
  260. url.Values(map[string][]string{"value": {"XXX"}, "prevValue": {"bad_value"}, "prevIndex": {"100"}}),
  261. http.StatusPreconditionFailed,
  262. map[string]interface{}{
  263. "errorCode": float64(101),
  264. "message": "Compare failed",
  265. "cause": "[bad_value != ZZZ] [100 != 4]",
  266. },
  267. },
  268. {
  269. "/v2/keys/cas/foo",
  270. url.Values(map[string][]string{"value": {"XXX"}, "prevValue": {"ZZZ"}, "prevIndex": {"100"}}),
  271. http.StatusPreconditionFailed,
  272. map[string]interface{}{
  273. "errorCode": float64(101),
  274. "message": "Compare failed",
  275. "cause": "[100 != 4]",
  276. },
  277. },
  278. {
  279. "/v2/keys/cas/foo",
  280. url.Values(map[string][]string{"value": {"XXX"}, "prevValue": {"bad_value"}, "prevIndex": {"4"}}),
  281. http.StatusPreconditionFailed,
  282. map[string]interface{}{
  283. "errorCode": float64(101),
  284. "message": "Compare failed",
  285. "cause": "[bad_value != ZZZ]",
  286. },
  287. },
  288. }
  289. for i, tt := range tests {
  290. resp, _ := tc.PutForm(fmt.Sprintf("%s%s", u, tt.relativeURL), tt.value)
  291. if resp.StatusCode != tt.wStatus {
  292. t.Errorf("#%d: status = %d, want %d", i, resp.StatusCode, tt.wStatus)
  293. }
  294. if err := checkBody(tc.ReadBodyJSON(resp), tt.w); err != nil {
  295. t.Errorf("#%d: %v", i, err)
  296. }
  297. }
  298. destoryCluster(t, es, hs)
  299. afterTest(t)
  300. }
  301. func TestV2Delete(t *testing.T) {
  302. es, hs := buildCluster(1, false)
  303. u := hs[0].URL
  304. tc := NewTestClient()
  305. v := url.Values{}
  306. v.Set("value", "XXX")
  307. resp, err := tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/foo"), v)
  308. if err != nil {
  309. t.Error(err)
  310. }
  311. resp.Body.Close()
  312. resp, err = tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/emptydir?dir=true"), v)
  313. if err != nil {
  314. t.Error(err)
  315. }
  316. resp.Body.Close()
  317. resp, err = tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/foodir/bar?dir=true"), v)
  318. if err != nil {
  319. t.Error(err)
  320. }
  321. resp.Body.Close()
  322. tests := []struct {
  323. relativeURL string
  324. wStatus int
  325. w map[string]interface{}
  326. }{
  327. {
  328. "/v2/keys/foo",
  329. http.StatusOK,
  330. map[string]interface{}{
  331. "node": map[string]interface{}{
  332. "key": "/foo",
  333. },
  334. "prevNode": map[string]interface{}{
  335. "key": "/foo",
  336. "value": "XXX",
  337. },
  338. "action": "delete",
  339. },
  340. },
  341. {
  342. "/v2/keys/emptydir",
  343. http.StatusForbidden,
  344. map[string]interface{}{
  345. "errorCode": float64(102),
  346. "message": "Not a file",
  347. "cause": "/emptydir",
  348. },
  349. },
  350. {
  351. "/v2/keys/emptydir?dir=true",
  352. http.StatusOK,
  353. nil,
  354. },
  355. {
  356. "/v2/keys/foodir?dir=true",
  357. http.StatusForbidden,
  358. map[string]interface{}{
  359. "errorCode": float64(108),
  360. "message": "Directory not empty",
  361. "cause": "/foodir",
  362. },
  363. },
  364. {
  365. "/v2/keys/foodir?recursive=true",
  366. http.StatusOK,
  367. map[string]interface{}{
  368. "node": map[string]interface{}{
  369. "key": "/foodir",
  370. "dir": true,
  371. },
  372. "prevNode": map[string]interface{}{
  373. "key": "/foodir",
  374. "dir": true,
  375. },
  376. "action": "delete",
  377. },
  378. },
  379. }
  380. for i, tt := range tests {
  381. resp, _ := tc.DeleteForm(fmt.Sprintf("%s%s", u, tt.relativeURL), nil)
  382. if resp.StatusCode != tt.wStatus {
  383. t.Errorf("#%d: status = %d, want %d", i, resp.StatusCode, tt.wStatus)
  384. }
  385. if err := checkBody(tc.ReadBodyJSON(resp), tt.w); err != nil {
  386. t.Errorf("#%d: %v", i, err)
  387. }
  388. }
  389. destoryCluster(t, es, hs)
  390. afterTest(t)
  391. }
  392. func TestV2CAD(t *testing.T) {
  393. es, hs := buildCluster(1, false)
  394. u := hs[0].URL
  395. tc := NewTestClient()
  396. v := url.Values{}
  397. v.Set("value", "XXX")
  398. resp, err := tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/foo"), v)
  399. if err != nil {
  400. t.Error(err)
  401. }
  402. resp.Body.Close()
  403. resp, err = tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/foovalue"), v)
  404. if err != nil {
  405. t.Error(err)
  406. }
  407. resp.Body.Close()
  408. tests := []struct {
  409. relativeURL string
  410. wStatus int
  411. w map[string]interface{}
  412. }{
  413. {
  414. "/v2/keys/foo?prevIndex=100",
  415. http.StatusPreconditionFailed,
  416. map[string]interface{}{
  417. "errorCode": float64(101),
  418. "message": "Compare failed",
  419. "cause": "[100 != 2]",
  420. },
  421. },
  422. {
  423. "/v2/keys/foo?prevIndex=bad_index",
  424. http.StatusBadRequest,
  425. map[string]interface{}{
  426. "errorCode": float64(203),
  427. "message": "The given index in POST form is not a number",
  428. "cause": "CompareAndDelete",
  429. },
  430. },
  431. {
  432. "/v2/keys/foo?prevIndex=2",
  433. http.StatusOK,
  434. map[string]interface{}{
  435. "node": map[string]interface{}{
  436. "key": "/foo",
  437. "modifiedIndex": float64(4),
  438. },
  439. "action": "compareAndDelete",
  440. },
  441. },
  442. {
  443. "/v2/keys/foovalue?prevValue=YYY",
  444. http.StatusPreconditionFailed,
  445. map[string]interface{}{
  446. "errorCode": float64(101),
  447. "message": "Compare failed",
  448. "cause": "[YYY != XXX]",
  449. },
  450. },
  451. {
  452. "/v2/keys/foovalue?prevValue=",
  453. http.StatusBadRequest,
  454. map[string]interface{}{
  455. "errorCode": float64(201),
  456. "message": "PrevValue is Required in POST form",
  457. "cause": "CompareAndDelete",
  458. },
  459. },
  460. {
  461. "/v2/keys/foovalue?prevValue=XXX",
  462. http.StatusOK,
  463. map[string]interface{}{
  464. "node": map[string]interface{}{
  465. "key": "/foovalue",
  466. "modifiedIndex": float64(5),
  467. },
  468. "action": "compareAndDelete",
  469. },
  470. },
  471. }
  472. for i, tt := range tests {
  473. resp, _ := tc.DeleteForm(fmt.Sprintf("%s%s", u, tt.relativeURL), nil)
  474. if resp.StatusCode != tt.wStatus {
  475. t.Errorf("#%d: status = %d, want %d", i, resp.StatusCode, tt.wStatus)
  476. }
  477. if err := checkBody(tc.ReadBodyJSON(resp), tt.w); err != nil {
  478. t.Errorf("#%d: %v", i, err)
  479. }
  480. }
  481. destoryCluster(t, es, hs)
  482. afterTest(t)
  483. }
  484. func TestV2Unique(t *testing.T) {
  485. es, hs := buildCluster(1, false)
  486. u := hs[0].URL
  487. tc := NewTestClient()
  488. tests := []struct {
  489. relativeURL string
  490. value url.Values
  491. wStatus int
  492. w map[string]interface{}
  493. }{
  494. {
  495. "/v2/keys/foo",
  496. url.Values(map[string][]string{"value": {"XXX"}}),
  497. http.StatusCreated,
  498. map[string]interface{}{
  499. "node": map[string]interface{}{
  500. "key": "/foo/2",
  501. "value": "XXX",
  502. },
  503. "action": "create",
  504. },
  505. },
  506. {
  507. "/v2/keys/foo",
  508. url.Values(map[string][]string{"value": {"XXX"}}),
  509. http.StatusCreated,
  510. map[string]interface{}{
  511. "node": map[string]interface{}{
  512. "key": "/foo/3",
  513. "value": "XXX",
  514. },
  515. "action": "create",
  516. },
  517. },
  518. {
  519. "/v2/keys/bar",
  520. url.Values(map[string][]string{"value": {"XXX"}}),
  521. http.StatusCreated,
  522. map[string]interface{}{
  523. "node": map[string]interface{}{
  524. "key": "/bar/4",
  525. "value": "XXX",
  526. },
  527. "action": "create",
  528. },
  529. },
  530. }
  531. for i, tt := range tests {
  532. resp, _ := tc.PostForm(fmt.Sprintf("%s%s", u, tt.relativeURL), tt.value)
  533. if resp.StatusCode != tt.wStatus {
  534. t.Errorf("#%d: status = %d, want %d", i, resp.StatusCode, tt.wStatus)
  535. }
  536. if err := checkBody(tc.ReadBodyJSON(resp), tt.w); err != nil {
  537. t.Errorf("#%d: %v", i, err)
  538. }
  539. }
  540. destoryCluster(t, es, hs)
  541. afterTest(t)
  542. }
  543. func TestV2Get(t *testing.T) {
  544. es, hs := buildCluster(1, false)
  545. u := hs[0].URL
  546. tc := NewTestClient()
  547. v := url.Values{}
  548. v.Set("value", "XXX")
  549. resp, err := tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/foo/bar/zar"), v)
  550. if err != nil {
  551. t.Error(err)
  552. }
  553. resp.Body.Close()
  554. tests := []struct {
  555. relativeURL string
  556. wStatus int
  557. w map[string]interface{}
  558. }{
  559. {
  560. "/v2/keys/foo/bar/zar",
  561. http.StatusOK,
  562. map[string]interface{}{
  563. "node": map[string]interface{}{
  564. "key": "/foo/bar/zar",
  565. "value": "XXX",
  566. },
  567. "action": "get",
  568. },
  569. },
  570. {
  571. "/v2/keys/foo",
  572. http.StatusOK,
  573. map[string]interface{}{
  574. "node": map[string]interface{}{
  575. "key": "/foo",
  576. "dir": true,
  577. "nodes": []interface{}{
  578. map[string]interface{}{
  579. "key": "/foo/bar",
  580. "dir": true,
  581. "createdIndex": float64(2),
  582. "modifiedIndex": float64(2),
  583. },
  584. },
  585. },
  586. "action": "get",
  587. },
  588. },
  589. {
  590. "/v2/keys/foo?recursive=true",
  591. http.StatusOK,
  592. map[string]interface{}{
  593. "node": map[string]interface{}{
  594. "key": "/foo",
  595. "dir": true,
  596. "nodes": []interface{}{
  597. map[string]interface{}{
  598. "key": "/foo/bar",
  599. "dir": true,
  600. "createdIndex": float64(2),
  601. "modifiedIndex": float64(2),
  602. "nodes": []interface{}{
  603. map[string]interface{}{
  604. "key": "/foo/bar/zar",
  605. "value": "XXX",
  606. "createdIndex": float64(2),
  607. "modifiedIndex": float64(2),
  608. },
  609. },
  610. },
  611. },
  612. },
  613. "action": "get",
  614. },
  615. },
  616. }
  617. for i, tt := range tests {
  618. resp, _ := tc.Get(fmt.Sprintf("%s%s", u, tt.relativeURL))
  619. if resp.StatusCode != tt.wStatus {
  620. t.Errorf("#%d: status = %d, want %d", i, resp.StatusCode, tt.wStatus)
  621. }
  622. if resp.Header.Get("Content-Type") != "application/json" {
  623. t.Errorf("#%d: header = %v, want %v", resp.Header.Get("Content-Type"), "application/json")
  624. }
  625. if err := checkBody(tc.ReadBodyJSON(resp), tt.w); err != nil {
  626. t.Errorf("#%d: %v", i, err)
  627. }
  628. }
  629. destoryCluster(t, es, hs)
  630. afterTest(t)
  631. }
  632. func TestV2Watch(t *testing.T) {
  633. es, hs := buildCluster(1, false)
  634. u := hs[0].URL
  635. tc := NewTestClient()
  636. var watchResp *http.Response
  637. c := make(chan bool)
  638. go func() {
  639. watchResp, _ = tc.Get(fmt.Sprintf("%s%s", u, "/v2/keys/foo/bar?wait=true"))
  640. c <- true
  641. }()
  642. // Make sure response didn't fire early.
  643. time.Sleep(1 * time.Millisecond)
  644. // Set a value.
  645. v := url.Values{}
  646. v.Set("value", "XXX")
  647. resp, _ := tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/foo/bar"), v)
  648. resp.Body.Close()
  649. select {
  650. case <-c:
  651. case <-time.After(time.Millisecond):
  652. t.Fatal("cannot get watch result")
  653. }
  654. body := tc.ReadBodyJSON(watchResp)
  655. w := map[string]interface{}{
  656. "node": map[string]interface{}{
  657. "key": "/foo/bar",
  658. "value": "XXX",
  659. "modifiedIndex": float64(2),
  660. },
  661. "action": "set",
  662. }
  663. if err := checkBody(body, w); err != nil {
  664. t.Error(err)
  665. }
  666. destoryCluster(t, es, hs)
  667. afterTest(t)
  668. }
  669. func TestV2WatchWithIndex(t *testing.T) {
  670. es, hs := buildCluster(1, false)
  671. u := hs[0].URL
  672. tc := NewTestClient()
  673. var body map[string]interface{}
  674. c := make(chan bool, 1)
  675. go func() {
  676. resp, _ := tc.Get(fmt.Sprintf("%s%s", u, "/v2/keys/foo/bar?wait=true&waitIndex=3"))
  677. body = tc.ReadBodyJSON(resp)
  678. c <- true
  679. }()
  680. select {
  681. case <-c:
  682. t.Fatal("should not get the watch result")
  683. case <-time.After(time.Millisecond):
  684. }
  685. // Set a value (before given index).
  686. v := url.Values{}
  687. v.Set("value", "XXX")
  688. resp, _ := tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/foo/bar"), v)
  689. resp.Body.Close()
  690. select {
  691. case <-c:
  692. t.Fatal("should not get the watch result")
  693. case <-time.After(time.Millisecond):
  694. }
  695. // Set a value (before given index).
  696. resp, _ = tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/foo/bar"), v)
  697. resp.Body.Close()
  698. select {
  699. case <-c:
  700. case <-time.After(time.Millisecond):
  701. t.Fatal("cannot get watch result")
  702. }
  703. w := map[string]interface{}{
  704. "node": map[string]interface{}{
  705. "key": "/foo/bar",
  706. "value": "XXX",
  707. "modifiedIndex": float64(3),
  708. },
  709. "action": "set",
  710. }
  711. if err := checkBody(body, w); err != nil {
  712. t.Error(err)
  713. }
  714. destoryCluster(t, es, hs)
  715. afterTest(t)
  716. }
  717. func TestV2WatchKeyInDir(t *testing.T) {
  718. es, hs := buildCluster(1, false)
  719. u := hs[0].URL
  720. tc := NewTestClient()
  721. var body map[string]interface{}
  722. c := make(chan bool)
  723. // Set a value (before given index).
  724. v := url.Values{}
  725. v.Set("dir", "true")
  726. v.Set("ttl", "1")
  727. resp, _ := tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/keyindir"), v)
  728. resp.Body.Close()
  729. // Set a value (before given index).
  730. v = url.Values{}
  731. v.Set("value", "XXX")
  732. resp, _ = tc.PutForm(fmt.Sprintf("%s%s", u, "/v2/keys/keyindir/bar"), v)
  733. resp.Body.Close()
  734. go func() {
  735. resp, _ := tc.Get(fmt.Sprintf("%s%s", u, "/v2/keys/keyindir/bar?wait=true"))
  736. body = tc.ReadBodyJSON(resp)
  737. c <- true
  738. }()
  739. select {
  740. case <-c:
  741. case <-time.After(time.Millisecond * 1500):
  742. t.Fatal("cannot get watch result")
  743. }
  744. w := map[string]interface{}{
  745. "node": map[string]interface{}{
  746. "key": "/keyindir",
  747. },
  748. "action": "expire",
  749. }
  750. if err := checkBody(body, w); err != nil {
  751. t.Error(err)
  752. }
  753. destoryCluster(t, es, hs)
  754. afterTest(t)
  755. }
  756. func TestV2Head(t *testing.T) {
  757. es, hs := buildCluster(1, false)
  758. u := hs[0].URL
  759. tc := NewTestClient()
  760. v := url.Values{}
  761. v.Set("value", "XXX")
  762. fullURL := fmt.Sprintf("%s%s", u, "/v2/keys/foo/bar")
  763. resp, _ := tc.Head(fullURL)
  764. resp.Body.Close()
  765. if resp.StatusCode != http.StatusNotFound {
  766. t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusNotFound)
  767. }
  768. if resp.ContentLength != -1 {
  769. t.Errorf("ContentLength = %d, want -1", resp.ContentLength)
  770. }
  771. resp, _ = tc.PutForm(fullURL, v)
  772. resp.Body.Close()
  773. resp, _ = tc.Head(fullURL)
  774. resp.Body.Close()
  775. if resp.StatusCode != http.StatusOK {
  776. t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK)
  777. }
  778. if resp.ContentLength != -1 {
  779. t.Errorf("ContentLength = %d, want -1", resp.ContentLength)
  780. }
  781. destoryCluster(t, es, hs)
  782. afterTest(t)
  783. }
  784. func checkBody(body map[string]interface{}, w map[string]interface{}) error {
  785. if body["node"] != nil {
  786. if w["node"] != nil {
  787. wn := w["node"].(map[string]interface{})
  788. n := body["node"].(map[string]interface{})
  789. for k := range n {
  790. if wn[k] == nil {
  791. delete(n, k)
  792. }
  793. }
  794. body["node"] = n
  795. }
  796. if w["prevNode"] != nil {
  797. wn := w["prevNode"].(map[string]interface{})
  798. n := body["prevNode"].(map[string]interface{})
  799. for k := range n {
  800. if wn[k] == nil {
  801. delete(n, k)
  802. }
  803. }
  804. body["prevNode"] = n
  805. }
  806. }
  807. for k, v := range w {
  808. g := body[k]
  809. if !reflect.DeepEqual(g, v) {
  810. return fmt.Errorf("%v = %+v, want %+v", k, g, v)
  811. }
  812. }
  813. return nil
  814. }
  815. type testHttpClient struct {
  816. *http.Client
  817. }
  818. // Creates a new HTTP client with KeepAlive disabled.
  819. func NewTestClient() *testHttpClient {
  820. return &testHttpClient{&http.Client{Transport: &http.Transport{DisableKeepAlives: true}}}
  821. }
  822. // Reads the body from the response and closes it.
  823. func (t *testHttpClient) ReadBody(resp *http.Response) []byte {
  824. if resp == nil {
  825. return []byte{}
  826. }
  827. body, _ := ioutil.ReadAll(resp.Body)
  828. resp.Body.Close()
  829. return body
  830. }
  831. // Reads the body from the response and parses it as JSON.
  832. func (t *testHttpClient) ReadBodyJSON(resp *http.Response) map[string]interface{} {
  833. m := make(map[string]interface{})
  834. b := t.ReadBody(resp)
  835. if err := json.Unmarshal(b, &m); err != nil {
  836. panic(fmt.Sprintf("HTTP body JSON parse error: %v: %s", err, string(b)))
  837. }
  838. return m
  839. }
  840. func (t *testHttpClient) Head(url string) (*http.Response, error) {
  841. return t.send("HEAD", url, "application/json", nil)
  842. }
  843. func (t *testHttpClient) Get(url string) (*http.Response, error) {
  844. return t.send("GET", url, "application/json", nil)
  845. }
  846. func (t *testHttpClient) Post(url string, bodyType string, body io.Reader) (*http.Response, error) {
  847. return t.send("POST", url, bodyType, body)
  848. }
  849. func (t *testHttpClient) PostForm(url string, data url.Values) (*http.Response, error) {
  850. return t.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  851. }
  852. func (t *testHttpClient) Put(url string, bodyType string, body io.Reader) (*http.Response, error) {
  853. return t.send("PUT", url, bodyType, body)
  854. }
  855. func (t *testHttpClient) PutForm(url string, data url.Values) (*http.Response, error) {
  856. return t.Put(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  857. }
  858. func (t *testHttpClient) Delete(url string, bodyType string, body io.Reader) (*http.Response, error) {
  859. return t.send("DELETE", url, bodyType, body)
  860. }
  861. func (t *testHttpClient) DeleteForm(url string, data url.Values) (*http.Response, error) {
  862. return t.Delete(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  863. }
  864. func (t *testHttpClient) send(method string, url string, bodyType string, body io.Reader) (*http.Response, error) {
  865. req, err := http.NewRequest(method, url, body)
  866. if err != nil {
  867. return nil, err
  868. }
  869. req.Header.Set("Content-Type", bodyType)
  870. return t.Do(req)
  871. }