keys_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package client
  15. import (
  16. "errors"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "net/url"
  21. "reflect"
  22. "testing"
  23. "time"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  25. )
  26. func TestV2KeysURLHelper(t *testing.T) {
  27. tests := []struct {
  28. endpoint url.URL
  29. prefix string
  30. key string
  31. want url.URL
  32. }{
  33. // key is empty, no problem
  34. {
  35. endpoint: url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"},
  36. prefix: "",
  37. key: "",
  38. want: url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"},
  39. },
  40. // key is joined to path
  41. {
  42. endpoint: url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"},
  43. prefix: "",
  44. key: "/foo/bar",
  45. want: url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys/foo/bar"},
  46. },
  47. // key is joined to path when path is empty
  48. {
  49. endpoint: url.URL{Scheme: "http", Host: "example.com", Path: ""},
  50. prefix: "",
  51. key: "/foo/bar",
  52. want: url.URL{Scheme: "http", Host: "example.com", Path: "/foo/bar"},
  53. },
  54. // Host field carries through with port
  55. {
  56. endpoint: url.URL{Scheme: "http", Host: "example.com:8080", Path: "/v2/keys"},
  57. prefix: "",
  58. key: "",
  59. want: url.URL{Scheme: "http", Host: "example.com:8080", Path: "/v2/keys"},
  60. },
  61. // Scheme carries through
  62. {
  63. endpoint: url.URL{Scheme: "https", Host: "example.com", Path: "/v2/keys"},
  64. prefix: "",
  65. key: "",
  66. want: url.URL{Scheme: "https", Host: "example.com", Path: "/v2/keys"},
  67. },
  68. // Prefix is applied
  69. {
  70. endpoint: url.URL{Scheme: "https", Host: "example.com", Path: "/foo"},
  71. prefix: "/bar",
  72. key: "/baz",
  73. want: url.URL{Scheme: "https", Host: "example.com", Path: "/foo/bar/baz"},
  74. },
  75. }
  76. for i, tt := range tests {
  77. got := v2KeysURL(tt.endpoint, tt.prefix, tt.key)
  78. if tt.want != *got {
  79. t.Errorf("#%d: want=%#v, got=%#v", i, tt.want, *got)
  80. }
  81. }
  82. }
  83. func TestGetAction(t *testing.T) {
  84. ep := url.URL{Scheme: "http", Host: "example.com/v2/keys"}
  85. baseWantURL := &url.URL{
  86. Scheme: "http",
  87. Host: "example.com",
  88. Path: "/v2/keys/foo/bar",
  89. }
  90. wantHeader := http.Header{}
  91. tests := []struct {
  92. recursive bool
  93. sorted bool
  94. wantQuery string
  95. }{
  96. {
  97. recursive: false,
  98. sorted: false,
  99. wantQuery: "recursive=false&sorted=false",
  100. },
  101. {
  102. recursive: true,
  103. sorted: false,
  104. wantQuery: "recursive=true&sorted=false",
  105. },
  106. {
  107. recursive: false,
  108. sorted: true,
  109. wantQuery: "recursive=false&sorted=true",
  110. },
  111. {
  112. recursive: true,
  113. sorted: true,
  114. wantQuery: "recursive=true&sorted=true",
  115. },
  116. }
  117. for i, tt := range tests {
  118. f := getAction{
  119. Key: "/foo/bar",
  120. Recursive: tt.recursive,
  121. Sorted: tt.sorted,
  122. }
  123. got := *f.HTTPRequest(ep)
  124. wantURL := baseWantURL
  125. wantURL.RawQuery = tt.wantQuery
  126. err := assertRequest(got, "GET", wantURL, wantHeader, nil)
  127. if err != nil {
  128. t.Errorf("#%d: %v", i, err)
  129. }
  130. }
  131. }
  132. func TestWaitAction(t *testing.T) {
  133. ep := url.URL{Scheme: "http", Host: "example.com/v2/keys"}
  134. baseWantURL := &url.URL{
  135. Scheme: "http",
  136. Host: "example.com",
  137. Path: "/v2/keys/foo/bar",
  138. }
  139. wantHeader := http.Header{}
  140. tests := []struct {
  141. afterIndex uint64
  142. recursive bool
  143. wantQuery string
  144. }{
  145. {
  146. recursive: false,
  147. afterIndex: uint64(0),
  148. wantQuery: "recursive=false&wait=true&waitIndex=0",
  149. },
  150. {
  151. recursive: false,
  152. afterIndex: uint64(12),
  153. wantQuery: "recursive=false&wait=true&waitIndex=12",
  154. },
  155. {
  156. recursive: true,
  157. afterIndex: uint64(12),
  158. wantQuery: "recursive=true&wait=true&waitIndex=12",
  159. },
  160. }
  161. for i, tt := range tests {
  162. f := waitAction{
  163. Key: "/foo/bar",
  164. AfterIndex: tt.afterIndex,
  165. Recursive: tt.recursive,
  166. }
  167. got := *f.HTTPRequest(ep)
  168. wantURL := baseWantURL
  169. wantURL.RawQuery = tt.wantQuery
  170. err := assertRequest(got, "GET", wantURL, wantHeader, nil)
  171. if err != nil {
  172. t.Errorf("#%d: %v", i, err)
  173. }
  174. }
  175. }
  176. func TestSetAction(t *testing.T) {
  177. wantHeader := http.Header(map[string][]string{
  178. "Content-Type": []string{"application/x-www-form-urlencoded"},
  179. })
  180. tests := []struct {
  181. act setAction
  182. wantURL string
  183. wantBody string
  184. }{
  185. // default prefix
  186. {
  187. act: setAction{
  188. Prefix: defaultV2KeysPrefix,
  189. Key: "foo",
  190. },
  191. wantURL: "http://example.com/v2/keys/foo",
  192. wantBody: "value=",
  193. },
  194. // non-default prefix
  195. {
  196. act: setAction{
  197. Prefix: "/pfx",
  198. Key: "foo",
  199. },
  200. wantURL: "http://example.com/pfx/foo",
  201. wantBody: "value=",
  202. },
  203. // no prefix
  204. {
  205. act: setAction{
  206. Key: "foo",
  207. },
  208. wantURL: "http://example.com/foo",
  209. wantBody: "value=",
  210. },
  211. // Key with path separators
  212. {
  213. act: setAction{
  214. Prefix: defaultV2KeysPrefix,
  215. Key: "foo/bar/baz",
  216. },
  217. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  218. wantBody: "value=",
  219. },
  220. // Key with leading slash, Prefix with trailing slash
  221. {
  222. act: setAction{
  223. Prefix: "/foo/",
  224. Key: "/bar",
  225. },
  226. wantURL: "http://example.com/foo/bar",
  227. wantBody: "value=",
  228. },
  229. // Key with trailing slash
  230. {
  231. act: setAction{
  232. Key: "/foo/",
  233. },
  234. wantURL: "http://example.com/foo",
  235. wantBody: "value=",
  236. },
  237. // Value is set
  238. {
  239. act: setAction{
  240. Key: "foo",
  241. Value: "baz",
  242. },
  243. wantURL: "http://example.com/foo",
  244. wantBody: "value=baz",
  245. },
  246. // PrevExist set, but still ignored
  247. {
  248. act: setAction{
  249. Key: "foo",
  250. PrevExist: PrevIgnore,
  251. },
  252. wantURL: "http://example.com/foo",
  253. wantBody: "value=",
  254. },
  255. // PrevExist set to true
  256. {
  257. act: setAction{
  258. Key: "foo",
  259. PrevExist: PrevExist,
  260. },
  261. wantURL: "http://example.com/foo?prevExist=true",
  262. wantBody: "value=",
  263. },
  264. // PrevExist set to false
  265. {
  266. act: setAction{
  267. Key: "foo",
  268. PrevExist: PrevNoExist,
  269. },
  270. wantURL: "http://example.com/foo?prevExist=false",
  271. wantBody: "value=",
  272. },
  273. // PrevValue is urlencoded
  274. {
  275. act: setAction{
  276. Key: "foo",
  277. PrevValue: "bar baz",
  278. },
  279. wantURL: "http://example.com/foo?prevValue=bar+baz",
  280. wantBody: "value=",
  281. },
  282. // PrevIndex is set
  283. {
  284. act: setAction{
  285. Key: "foo",
  286. PrevIndex: uint64(12),
  287. },
  288. wantURL: "http://example.com/foo?prevIndex=12",
  289. wantBody: "value=",
  290. },
  291. // TTL is set
  292. {
  293. act: setAction{
  294. Key: "foo",
  295. TTL: 3 * time.Minute,
  296. },
  297. wantURL: "http://example.com/foo",
  298. wantBody: "ttl=180&value=",
  299. },
  300. }
  301. for i, tt := range tests {
  302. u, err := url.Parse(tt.wantURL)
  303. if err != nil {
  304. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  305. }
  306. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  307. if err := assertRequest(*got, "PUT", u, wantHeader, []byte(tt.wantBody)); err != nil {
  308. t.Errorf("#%d: %v", i, err)
  309. }
  310. }
  311. }
  312. func TestDeleteAction(t *testing.T) {
  313. wantHeader := http.Header(map[string][]string{
  314. "Content-Type": []string{"application/x-www-form-urlencoded"},
  315. })
  316. tests := []struct {
  317. act deleteAction
  318. wantURL string
  319. }{
  320. // default prefix
  321. {
  322. act: deleteAction{
  323. Prefix: defaultV2KeysPrefix,
  324. Key: "foo",
  325. },
  326. wantURL: "http://example.com/v2/keys/foo",
  327. },
  328. // non-default prefix
  329. {
  330. act: deleteAction{
  331. Prefix: "/pfx",
  332. Key: "foo",
  333. },
  334. wantURL: "http://example.com/pfx/foo",
  335. },
  336. // no prefix
  337. {
  338. act: deleteAction{
  339. Key: "foo",
  340. },
  341. wantURL: "http://example.com/foo",
  342. },
  343. // Key with path separators
  344. {
  345. act: deleteAction{
  346. Prefix: defaultV2KeysPrefix,
  347. Key: "foo/bar/baz",
  348. },
  349. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  350. },
  351. // Key with leading slash, Prefix with trailing slash
  352. {
  353. act: deleteAction{
  354. Prefix: "/foo/",
  355. Key: "/bar",
  356. },
  357. wantURL: "http://example.com/foo/bar",
  358. },
  359. // Key with trailing slash
  360. {
  361. act: deleteAction{
  362. Key: "/foo/",
  363. },
  364. wantURL: "http://example.com/foo",
  365. },
  366. // Recursive set to true
  367. {
  368. act: deleteAction{
  369. Key: "foo",
  370. Recursive: true,
  371. },
  372. wantURL: "http://example.com/foo?recursive=true",
  373. },
  374. // PrevValue is urlencoded
  375. {
  376. act: deleteAction{
  377. Key: "foo",
  378. PrevValue: "bar baz",
  379. },
  380. wantURL: "http://example.com/foo?prevValue=bar+baz",
  381. },
  382. // PrevIndex is set
  383. {
  384. act: deleteAction{
  385. Key: "foo",
  386. PrevIndex: uint64(12),
  387. },
  388. wantURL: "http://example.com/foo?prevIndex=12",
  389. },
  390. }
  391. for i, tt := range tests {
  392. u, err := url.Parse(tt.wantURL)
  393. if err != nil {
  394. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  395. }
  396. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  397. if err := assertRequest(*got, "DELETE", u, wantHeader, nil); err != nil {
  398. t.Errorf("#%d: %v", i, err)
  399. }
  400. }
  401. }
  402. func assertRequest(got http.Request, wantMethod string, wantURL *url.URL, wantHeader http.Header, wantBody []byte) error {
  403. if wantMethod != got.Method {
  404. return fmt.Errorf("want.Method=%#v got.Method=%#v", wantMethod, got.Method)
  405. }
  406. if !reflect.DeepEqual(wantURL, got.URL) {
  407. return fmt.Errorf("want.URL=%#v got.URL=%#v", wantURL, got.URL)
  408. }
  409. if !reflect.DeepEqual(wantHeader, got.Header) {
  410. return fmt.Errorf("want.Header=%#v got.Header=%#v", wantHeader, got.Header)
  411. }
  412. if got.Body == nil {
  413. if wantBody != nil {
  414. return fmt.Errorf("want.Body=%v got.Body=%v", wantBody, got.Body)
  415. }
  416. } else {
  417. if wantBody == nil {
  418. return fmt.Errorf("want.Body=%v got.Body=%s", wantBody, got.Body)
  419. } else {
  420. gotBytes, err := ioutil.ReadAll(got.Body)
  421. if err != nil {
  422. return err
  423. }
  424. if !reflect.DeepEqual(wantBody, gotBytes) {
  425. return fmt.Errorf("want.Body=%s got.Body=%s", wantBody, gotBytes)
  426. }
  427. }
  428. }
  429. return nil
  430. }
  431. func TestUnmarshalSuccessfulResponse(t *testing.T) {
  432. tests := []struct {
  433. hdr string
  434. body string
  435. wantRes *Response
  436. wantErr bool
  437. }{
  438. // Neither PrevNode or Node
  439. {
  440. hdr: "1",
  441. body: `{"action":"delete"}`,
  442. wantRes: &Response{Action: "delete", Index: 1},
  443. wantErr: false,
  444. },
  445. // PrevNode
  446. {
  447. hdr: "15",
  448. body: `{"action":"delete", "prevNode": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  449. wantRes: &Response{
  450. Action: "delete",
  451. Index: 15,
  452. Node: nil,
  453. PrevNode: &Node{
  454. Key: "/foo",
  455. Value: "bar",
  456. ModifiedIndex: 12,
  457. CreatedIndex: 10,
  458. },
  459. },
  460. wantErr: false,
  461. },
  462. // Node
  463. {
  464. hdr: "15",
  465. body: `{"action":"get", "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  466. wantRes: &Response{
  467. Action: "get",
  468. Index: 15,
  469. Node: &Node{
  470. Key: "/foo",
  471. Value: "bar",
  472. ModifiedIndex: 12,
  473. CreatedIndex: 10,
  474. },
  475. PrevNode: nil,
  476. },
  477. wantErr: false,
  478. },
  479. // PrevNode and Node
  480. {
  481. hdr: "15",
  482. body: `{"action":"update", "prevNode": {"key": "/foo", "value": "baz", "modifiedIndex": 10, "createdIndex": 10}, "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  483. wantRes: &Response{
  484. Action: "update",
  485. Index: 15,
  486. PrevNode: &Node{
  487. Key: "/foo",
  488. Value: "baz",
  489. ModifiedIndex: 10,
  490. CreatedIndex: 10,
  491. },
  492. Node: &Node{
  493. Key: "/foo",
  494. Value: "bar",
  495. ModifiedIndex: 12,
  496. CreatedIndex: 10,
  497. },
  498. },
  499. wantErr: false,
  500. },
  501. // Garbage in body
  502. {
  503. hdr: "",
  504. body: `garbage`,
  505. wantRes: nil,
  506. wantErr: true,
  507. },
  508. // non-integer index
  509. {
  510. hdr: "poo",
  511. body: `{}`,
  512. wantRes: nil,
  513. wantErr: true,
  514. },
  515. }
  516. for i, tt := range tests {
  517. h := make(http.Header)
  518. h.Add("X-Etcd-Index", tt.hdr)
  519. res, err := unmarshalSuccessfulKeysResponse(h, []byte(tt.body))
  520. if tt.wantErr != (err != nil) {
  521. t.Errorf("#%d: wantErr=%t, err=%v", i, tt.wantErr, err)
  522. }
  523. if (res == nil) != (tt.wantRes == nil) {
  524. t.Errorf("#%d: received res=%#v, but expected res=%#v", i, res, tt.wantRes)
  525. continue
  526. } else if tt.wantRes == nil {
  527. // expected and successfully got nil response
  528. continue
  529. }
  530. if res.Action != tt.wantRes.Action {
  531. t.Errorf("#%d: Action=%s, expected %s", i, res.Action, tt.wantRes.Action)
  532. }
  533. if res.Index != tt.wantRes.Index {
  534. t.Errorf("#%d: Index=%d, expected %d", i, res.Index, tt.wantRes.Index)
  535. }
  536. if !reflect.DeepEqual(res.Node, tt.wantRes.Node) {
  537. t.Errorf("#%d: Node=%v, expected %v", i, res.Node, tt.wantRes.Node)
  538. }
  539. }
  540. }
  541. func TestUnmarshalFailedKeysResponse(t *testing.T) {
  542. body := []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`)
  543. wantErr := Error{
  544. Code: 100,
  545. Message: "Key not found",
  546. Cause: "/foo",
  547. Index: uint64(18),
  548. }
  549. gotErr := unmarshalFailedKeysResponse(body)
  550. if !reflect.DeepEqual(wantErr, gotErr) {
  551. t.Errorf("unexpected error: want=%#v got=%#v", wantErr, gotErr)
  552. }
  553. }
  554. func TestUnmarshalFailedKeysResponseBadJSON(t *testing.T) {
  555. err := unmarshalFailedKeysResponse([]byte(`{"er`))
  556. if err == nil {
  557. t.Errorf("got nil error")
  558. } else if _, ok := err.(Error); ok {
  559. t.Errorf("error is of incorrect type *Error: %#v", err)
  560. }
  561. }
  562. func TestHTTPWatcherNextWaitAction(t *testing.T) {
  563. initAction := waitAction{
  564. Prefix: "/pants",
  565. Key: "/foo/bar",
  566. Recursive: true,
  567. AfterIndex: 19,
  568. }
  569. client := &actionAssertingHTTPClient{
  570. t: t,
  571. act: &initAction,
  572. resp: http.Response{
  573. StatusCode: http.StatusOK,
  574. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  575. },
  576. body: []byte(`{"action":"update","node":{"key":"/pants/foo/bar/baz","value":"snarf","modifiedIndex":21,"createdIndex":19},"prevNode":{"key":"/pants/foo/bar/baz","value":"snazz","modifiedIndex":20,"createdIndex":19}}`),
  577. }
  578. wantResponse := &Response{
  579. Action: "update",
  580. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(21)},
  581. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  582. Index: uint64(42),
  583. }
  584. wantNextWait := waitAction{
  585. Prefix: "/pants",
  586. Key: "/foo/bar",
  587. Recursive: true,
  588. AfterIndex: 22,
  589. }
  590. watcher := &httpWatcher{
  591. client: client,
  592. nextWait: initAction,
  593. }
  594. resp, err := watcher.Next(context.Background())
  595. if err != nil {
  596. t.Errorf("non-nil error: %#v", err)
  597. }
  598. if !reflect.DeepEqual(wantResponse, resp) {
  599. t.Errorf("received incorrect Response: want=%#v got=%#v", wantResponse, resp)
  600. }
  601. if !reflect.DeepEqual(wantNextWait, watcher.nextWait) {
  602. t.Errorf("nextWait incorrect: want=%#v got=%#v", wantNextWait, watcher.nextWait)
  603. }
  604. }
  605. func TestHTTPWatcherNextFail(t *testing.T) {
  606. tests := []httpClient{
  607. // generic HTTP client failure
  608. &staticHTTPClient{
  609. err: errors.New("fail!"),
  610. },
  611. // unusable status code
  612. &staticHTTPClient{
  613. resp: http.Response{
  614. StatusCode: http.StatusTeapot,
  615. },
  616. },
  617. // etcd Error response
  618. &staticHTTPClient{
  619. resp: http.Response{
  620. StatusCode: http.StatusNotFound,
  621. },
  622. body: []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`),
  623. },
  624. }
  625. for i, tt := range tests {
  626. act := waitAction{
  627. Prefix: "/pants",
  628. Key: "/foo/bar",
  629. Recursive: true,
  630. AfterIndex: 19,
  631. }
  632. watcher := &httpWatcher{
  633. client: tt,
  634. nextWait: act,
  635. }
  636. resp, err := watcher.Next(context.Background())
  637. if err == nil {
  638. t.Errorf("#%d: expected non-nil error", i)
  639. }
  640. if resp != nil {
  641. t.Errorf("#%d: expected nil Response, got %#v", i, resp)
  642. }
  643. if !reflect.DeepEqual(act, watcher.nextWait) {
  644. t.Errorf("#%d: nextWait changed: want=%#v got=%#v", i, act, watcher.nextWait)
  645. }
  646. }
  647. }