v2_http_kv_test.go 24 KB

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