keys_test.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  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. waitIndex uint64
  142. recursive bool
  143. wantQuery string
  144. }{
  145. {
  146. recursive: false,
  147. waitIndex: uint64(0),
  148. wantQuery: "recursive=false&wait=true&waitIndex=0",
  149. },
  150. {
  151. recursive: false,
  152. waitIndex: uint64(12),
  153. wantQuery: "recursive=false&wait=true&waitIndex=12",
  154. },
  155. {
  156. recursive: true,
  157. waitIndex: 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. WaitIndex: tt.waitIndex,
  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: unexpected error: %#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 TestCreateInOrderAction(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 createInOrderAction
  318. wantURL string
  319. wantBody string
  320. }{
  321. // default prefix
  322. {
  323. act: createInOrderAction{
  324. Prefix: defaultV2KeysPrefix,
  325. Dir: "foo",
  326. },
  327. wantURL: "http://example.com/v2/keys/foo",
  328. wantBody: "value=",
  329. },
  330. // non-default prefix
  331. {
  332. act: createInOrderAction{
  333. Prefix: "/pfx",
  334. Dir: "foo",
  335. },
  336. wantURL: "http://example.com/pfx/foo",
  337. wantBody: "value=",
  338. },
  339. // no prefix
  340. {
  341. act: createInOrderAction{
  342. Dir: "foo",
  343. },
  344. wantURL: "http://example.com/foo",
  345. wantBody: "value=",
  346. },
  347. // Key with path separators
  348. {
  349. act: createInOrderAction{
  350. Prefix: defaultV2KeysPrefix,
  351. Dir: "foo/bar/baz",
  352. },
  353. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  354. wantBody: "value=",
  355. },
  356. // Key with leading slash, Prefix with trailing slash
  357. {
  358. act: createInOrderAction{
  359. Prefix: "/foo/",
  360. Dir: "/bar",
  361. },
  362. wantURL: "http://example.com/foo/bar",
  363. wantBody: "value=",
  364. },
  365. // Key with trailing slash
  366. {
  367. act: createInOrderAction{
  368. Dir: "/foo/",
  369. },
  370. wantURL: "http://example.com/foo",
  371. wantBody: "value=",
  372. },
  373. // Value is set
  374. {
  375. act: createInOrderAction{
  376. Dir: "foo",
  377. Value: "baz",
  378. },
  379. wantURL: "http://example.com/foo",
  380. wantBody: "value=baz",
  381. },
  382. // TTL is set
  383. {
  384. act: createInOrderAction{
  385. Dir: "foo",
  386. TTL: 3 * time.Minute,
  387. },
  388. wantURL: "http://example.com/foo",
  389. wantBody: "ttl=180&value=",
  390. },
  391. }
  392. for i, tt := range tests {
  393. u, err := url.Parse(tt.wantURL)
  394. if err != nil {
  395. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  396. }
  397. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  398. if err := assertRequest(*got, "POST", u, wantHeader, []byte(tt.wantBody)); err != nil {
  399. t.Errorf("#%d: %v", i, err)
  400. }
  401. }
  402. }
  403. func TestDeleteAction(t *testing.T) {
  404. wantHeader := http.Header(map[string][]string{
  405. "Content-Type": []string{"application/x-www-form-urlencoded"},
  406. })
  407. tests := []struct {
  408. act deleteAction
  409. wantURL string
  410. }{
  411. // default prefix
  412. {
  413. act: deleteAction{
  414. Prefix: defaultV2KeysPrefix,
  415. Key: "foo",
  416. },
  417. wantURL: "http://example.com/v2/keys/foo",
  418. },
  419. // non-default prefix
  420. {
  421. act: deleteAction{
  422. Prefix: "/pfx",
  423. Key: "foo",
  424. },
  425. wantURL: "http://example.com/pfx/foo",
  426. },
  427. // no prefix
  428. {
  429. act: deleteAction{
  430. Key: "foo",
  431. },
  432. wantURL: "http://example.com/foo",
  433. },
  434. // Key with path separators
  435. {
  436. act: deleteAction{
  437. Prefix: defaultV2KeysPrefix,
  438. Key: "foo/bar/baz",
  439. },
  440. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  441. },
  442. // Key with leading slash, Prefix with trailing slash
  443. {
  444. act: deleteAction{
  445. Prefix: "/foo/",
  446. Key: "/bar",
  447. },
  448. wantURL: "http://example.com/foo/bar",
  449. },
  450. // Key with trailing slash
  451. {
  452. act: deleteAction{
  453. Key: "/foo/",
  454. },
  455. wantURL: "http://example.com/foo",
  456. },
  457. // Recursive set to true
  458. {
  459. act: deleteAction{
  460. Key: "foo",
  461. Recursive: true,
  462. },
  463. wantURL: "http://example.com/foo?recursive=true",
  464. },
  465. // PrevValue is urlencoded
  466. {
  467. act: deleteAction{
  468. Key: "foo",
  469. PrevValue: "bar baz",
  470. },
  471. wantURL: "http://example.com/foo?prevValue=bar+baz",
  472. },
  473. // PrevIndex is set
  474. {
  475. act: deleteAction{
  476. Key: "foo",
  477. PrevIndex: uint64(12),
  478. },
  479. wantURL: "http://example.com/foo?prevIndex=12",
  480. },
  481. }
  482. for i, tt := range tests {
  483. u, err := url.Parse(tt.wantURL)
  484. if err != nil {
  485. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  486. }
  487. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  488. if err := assertRequest(*got, "DELETE", u, wantHeader, nil); err != nil {
  489. t.Errorf("#%d: %v", i, err)
  490. }
  491. }
  492. }
  493. func assertRequest(got http.Request, wantMethod string, wantURL *url.URL, wantHeader http.Header, wantBody []byte) error {
  494. if wantMethod != got.Method {
  495. return fmt.Errorf("want.Method=%#v got.Method=%#v", wantMethod, got.Method)
  496. }
  497. if !reflect.DeepEqual(wantURL, got.URL) {
  498. return fmt.Errorf("want.URL=%#v got.URL=%#v", wantURL, got.URL)
  499. }
  500. if !reflect.DeepEqual(wantHeader, got.Header) {
  501. return fmt.Errorf("want.Header=%#v got.Header=%#v", wantHeader, got.Header)
  502. }
  503. if got.Body == nil {
  504. if wantBody != nil {
  505. return fmt.Errorf("want.Body=%v got.Body=%v", wantBody, got.Body)
  506. }
  507. } else {
  508. if wantBody == nil {
  509. return fmt.Errorf("want.Body=%v got.Body=%s", wantBody, got.Body)
  510. } else {
  511. gotBytes, err := ioutil.ReadAll(got.Body)
  512. if err != nil {
  513. return err
  514. }
  515. if !reflect.DeepEqual(wantBody, gotBytes) {
  516. return fmt.Errorf("want.Body=%s got.Body=%s", wantBody, gotBytes)
  517. }
  518. }
  519. }
  520. return nil
  521. }
  522. func TestUnmarshalSuccessfulResponse(t *testing.T) {
  523. var expiration time.Time
  524. expiration.UnmarshalText([]byte("2015-04-07T04:40:23.044979686Z"))
  525. tests := []struct {
  526. hdr string
  527. body string
  528. wantRes *Response
  529. wantErr bool
  530. }{
  531. // Neither PrevNode or Node
  532. {
  533. hdr: "1",
  534. body: `{"action":"delete"}`,
  535. wantRes: &Response{Action: "delete", Index: 1},
  536. wantErr: false,
  537. },
  538. // PrevNode
  539. {
  540. hdr: "15",
  541. body: `{"action":"delete", "prevNode": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  542. wantRes: &Response{
  543. Action: "delete",
  544. Index: 15,
  545. Node: nil,
  546. PrevNode: &Node{
  547. Key: "/foo",
  548. Value: "bar",
  549. ModifiedIndex: 12,
  550. CreatedIndex: 10,
  551. },
  552. },
  553. wantErr: false,
  554. },
  555. // Node
  556. {
  557. hdr: "15",
  558. body: `{"action":"get", "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10, "ttl": 10, "expiration": "2015-04-07T04:40:23.044979686Z"}}`,
  559. wantRes: &Response{
  560. Action: "get",
  561. Index: 15,
  562. Node: &Node{
  563. Key: "/foo",
  564. Value: "bar",
  565. ModifiedIndex: 12,
  566. CreatedIndex: 10,
  567. TTL: 10,
  568. Expiration: &expiration,
  569. },
  570. PrevNode: nil,
  571. },
  572. wantErr: false,
  573. },
  574. // Node Dir
  575. {
  576. hdr: "15",
  577. body: `{"action":"get", "node": {"key": "/foo", "dir": true, "modifiedIndex": 12, "createdIndex": 10}}`,
  578. wantRes: &Response{
  579. Action: "get",
  580. Index: 15,
  581. Node: &Node{
  582. Key: "/foo",
  583. Dir: true,
  584. ModifiedIndex: 12,
  585. CreatedIndex: 10,
  586. },
  587. PrevNode: nil,
  588. },
  589. wantErr: false,
  590. },
  591. // PrevNode and Node
  592. {
  593. hdr: "15",
  594. body: `{"action":"update", "prevNode": {"key": "/foo", "value": "baz", "modifiedIndex": 10, "createdIndex": 10}, "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  595. wantRes: &Response{
  596. Action: "update",
  597. Index: 15,
  598. PrevNode: &Node{
  599. Key: "/foo",
  600. Value: "baz",
  601. ModifiedIndex: 10,
  602. CreatedIndex: 10,
  603. },
  604. Node: &Node{
  605. Key: "/foo",
  606. Value: "bar",
  607. ModifiedIndex: 12,
  608. CreatedIndex: 10,
  609. },
  610. },
  611. wantErr: false,
  612. },
  613. // Garbage in body
  614. {
  615. hdr: "",
  616. body: `garbage`,
  617. wantRes: nil,
  618. wantErr: true,
  619. },
  620. // non-integer index
  621. {
  622. hdr: "poo",
  623. body: `{}`,
  624. wantRes: nil,
  625. wantErr: true,
  626. },
  627. }
  628. for i, tt := range tests {
  629. h := make(http.Header)
  630. h.Add("X-Etcd-Index", tt.hdr)
  631. res, err := unmarshalSuccessfulKeysResponse(h, []byte(tt.body))
  632. if tt.wantErr != (err != nil) {
  633. t.Errorf("#%d: wantErr=%t, err=%v", i, tt.wantErr, err)
  634. }
  635. if (res == nil) != (tt.wantRes == nil) {
  636. t.Errorf("#%d: received res=%#v, but expected res=%#v", i, res, tt.wantRes)
  637. continue
  638. } else if tt.wantRes == nil {
  639. // expected and successfully got nil response
  640. continue
  641. }
  642. if res.Action != tt.wantRes.Action {
  643. t.Errorf("#%d: Action=%s, expected %s", i, res.Action, tt.wantRes.Action)
  644. }
  645. if res.Index != tt.wantRes.Index {
  646. t.Errorf("#%d: Index=%d, expected %d", i, res.Index, tt.wantRes.Index)
  647. }
  648. if !reflect.DeepEqual(res.Node, tt.wantRes.Node) {
  649. t.Errorf("#%d: Node=%v, expected %v", i, res.Node, tt.wantRes.Node)
  650. }
  651. }
  652. }
  653. func TestUnmarshalFailedKeysResponse(t *testing.T) {
  654. body := []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`)
  655. wantErr := Error{
  656. Code: 100,
  657. Message: "Key not found",
  658. Cause: "/foo",
  659. Index: uint64(18),
  660. }
  661. gotErr := unmarshalFailedKeysResponse(body)
  662. if !reflect.DeepEqual(wantErr, gotErr) {
  663. t.Errorf("unexpected error: want=%#v got=%#v", wantErr, gotErr)
  664. }
  665. }
  666. func TestUnmarshalFailedKeysResponseBadJSON(t *testing.T) {
  667. err := unmarshalFailedKeysResponse([]byte(`{"er`))
  668. if err == nil {
  669. t.Errorf("got nil error")
  670. } else if _, ok := err.(Error); ok {
  671. t.Errorf("error is of incorrect type *Error: %#v", err)
  672. }
  673. }
  674. func TestHTTPWatcherNextWaitAction(t *testing.T) {
  675. initAction := waitAction{
  676. Prefix: "/pants",
  677. Key: "/foo/bar",
  678. Recursive: true,
  679. WaitIndex: 19,
  680. }
  681. client := &actionAssertingHTTPClient{
  682. t: t,
  683. act: &initAction,
  684. resp: http.Response{
  685. StatusCode: http.StatusOK,
  686. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  687. },
  688. 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}}`),
  689. }
  690. wantResponse := &Response{
  691. Action: "update",
  692. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(21)},
  693. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  694. Index: uint64(42),
  695. }
  696. wantNextWait := waitAction{
  697. Prefix: "/pants",
  698. Key: "/foo/bar",
  699. Recursive: true,
  700. WaitIndex: 22,
  701. }
  702. watcher := &httpWatcher{
  703. client: client,
  704. nextWait: initAction,
  705. }
  706. resp, err := watcher.Next(context.Background())
  707. if err != nil {
  708. t.Errorf("non-nil error: %#v", err)
  709. }
  710. if !reflect.DeepEqual(wantResponse, resp) {
  711. t.Errorf("received incorrect Response: want=%#v got=%#v", wantResponse, resp)
  712. }
  713. if !reflect.DeepEqual(wantNextWait, watcher.nextWait) {
  714. t.Errorf("nextWait incorrect: want=%#v got=%#v", wantNextWait, watcher.nextWait)
  715. }
  716. }
  717. func TestHTTPWatcherNextFail(t *testing.T) {
  718. tests := []httpClient{
  719. // generic HTTP client failure
  720. &staticHTTPClient{
  721. err: errors.New("fail!"),
  722. },
  723. // unusable status code
  724. &staticHTTPClient{
  725. resp: http.Response{
  726. StatusCode: http.StatusTeapot,
  727. },
  728. },
  729. // etcd Error response
  730. &staticHTTPClient{
  731. resp: http.Response{
  732. StatusCode: http.StatusNotFound,
  733. },
  734. body: []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`),
  735. },
  736. }
  737. for i, tt := range tests {
  738. act := waitAction{
  739. Prefix: "/pants",
  740. Key: "/foo/bar",
  741. Recursive: true,
  742. WaitIndex: 19,
  743. }
  744. watcher := &httpWatcher{
  745. client: tt,
  746. nextWait: act,
  747. }
  748. resp, err := watcher.Next(context.Background())
  749. if err == nil {
  750. t.Errorf("#%d: expected non-nil error", i)
  751. }
  752. if resp != nil {
  753. t.Errorf("#%d: expected nil Response, got %#v", i, resp)
  754. }
  755. if !reflect.DeepEqual(act, watcher.nextWait) {
  756. t.Errorf("#%d: nextWait changed: want=%#v got=%#v", i, act, watcher.nextWait)
  757. }
  758. }
  759. }
  760. func TestHTTPKeysAPIWatcherAction(t *testing.T) {
  761. tests := []struct {
  762. key string
  763. opts *WatcherOptions
  764. want waitAction
  765. }{
  766. {
  767. key: "/foo",
  768. opts: nil,
  769. want: waitAction{
  770. Key: "/foo",
  771. Recursive: false,
  772. WaitIndex: 0,
  773. },
  774. },
  775. {
  776. key: "/foo",
  777. opts: &WatcherOptions{
  778. Recursive: false,
  779. AfterIndex: 0,
  780. },
  781. want: waitAction{
  782. Key: "/foo",
  783. Recursive: false,
  784. WaitIndex: 0,
  785. },
  786. },
  787. {
  788. key: "/foo",
  789. opts: &WatcherOptions{
  790. Recursive: true,
  791. AfterIndex: 0,
  792. },
  793. want: waitAction{
  794. Key: "/foo",
  795. Recursive: true,
  796. WaitIndex: 0,
  797. },
  798. },
  799. {
  800. key: "/foo",
  801. opts: &WatcherOptions{
  802. Recursive: false,
  803. AfterIndex: 19,
  804. },
  805. want: waitAction{
  806. Key: "/foo",
  807. Recursive: false,
  808. WaitIndex: 20,
  809. },
  810. },
  811. }
  812. for i, tt := range tests {
  813. kAPI := &httpKeysAPI{
  814. client: &staticHTTPClient{err: errors.New("fail!")},
  815. }
  816. want := &httpWatcher{
  817. client: &staticHTTPClient{err: errors.New("fail!")},
  818. nextWait: tt.want,
  819. }
  820. got := kAPI.Watcher(tt.key, tt.opts)
  821. if !reflect.DeepEqual(want, got) {
  822. t.Errorf("#%d: incorrect watcher: want=%#v got=%#v", i, want, got)
  823. }
  824. }
  825. }
  826. func TestHTTPKeysAPISetAction(t *testing.T) {
  827. tests := []struct {
  828. key string
  829. value string
  830. opts *SetOptions
  831. wantAction httpAction
  832. }{
  833. // nil SetOptions
  834. {
  835. key: "/foo",
  836. value: "bar",
  837. opts: nil,
  838. wantAction: &setAction{
  839. Key: "/foo",
  840. Value: "bar",
  841. PrevValue: "",
  842. PrevIndex: 0,
  843. PrevExist: PrevIgnore,
  844. TTL: 0,
  845. },
  846. },
  847. // empty SetOptions
  848. {
  849. key: "/foo",
  850. value: "bar",
  851. opts: &SetOptions{},
  852. wantAction: &setAction{
  853. Key: "/foo",
  854. Value: "bar",
  855. PrevValue: "",
  856. PrevIndex: 0,
  857. PrevExist: PrevIgnore,
  858. TTL: 0,
  859. },
  860. },
  861. // populated SetOptions
  862. {
  863. key: "/foo",
  864. value: "bar",
  865. opts: &SetOptions{
  866. PrevValue: "baz",
  867. PrevIndex: 13,
  868. PrevExist: PrevExist,
  869. TTL: time.Minute,
  870. },
  871. wantAction: &setAction{
  872. Key: "/foo",
  873. Value: "bar",
  874. PrevValue: "baz",
  875. PrevIndex: 13,
  876. PrevExist: PrevExist,
  877. TTL: time.Minute,
  878. },
  879. },
  880. }
  881. for i, tt := range tests {
  882. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  883. kAPI := httpKeysAPI{client: client}
  884. kAPI.Set(context.Background(), tt.key, tt.value, tt.opts)
  885. }
  886. }
  887. func TestHTTPKeysAPISetError(t *testing.T) {
  888. tests := []httpClient{
  889. // generic HTTP client failure
  890. &staticHTTPClient{
  891. err: errors.New("fail!"),
  892. },
  893. // unusable status code
  894. &staticHTTPClient{
  895. resp: http.Response{
  896. StatusCode: http.StatusTeapot,
  897. },
  898. },
  899. // etcd Error response
  900. &staticHTTPClient{
  901. resp: http.Response{
  902. StatusCode: http.StatusInternalServerError,
  903. },
  904. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  905. },
  906. }
  907. for i, tt := range tests {
  908. kAPI := httpKeysAPI{client: tt}
  909. resp, err := kAPI.Set(context.Background(), "/foo", "bar", nil)
  910. if err == nil {
  911. t.Errorf("#%d: received nil error", i)
  912. }
  913. if resp != nil {
  914. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  915. }
  916. }
  917. }
  918. func TestHTTPKeysAPISetResponse(t *testing.T) {
  919. client := &staticHTTPClient{
  920. resp: http.Response{
  921. StatusCode: http.StatusOK,
  922. Header: http.Header{"X-Etcd-Index": []string{"21"}},
  923. },
  924. body: []byte(`{"action":"set","node":{"key":"/pants/foo/bar/baz","value":"snarf","modifiedIndex":21,"createdIndex":21},"prevNode":{"key":"/pants/foo/bar/baz","value":"snazz","modifiedIndex":20,"createdIndex":19}}`),
  925. }
  926. wantResponse := &Response{
  927. Action: "set",
  928. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(21), ModifiedIndex: uint64(21)},
  929. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  930. Index: uint64(21),
  931. }
  932. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  933. resp, err := kAPI.Set(context.Background(), "/foo/bar/baz", "snarf", nil)
  934. if err != nil {
  935. t.Errorf("non-nil error: %#v", err)
  936. }
  937. if !reflect.DeepEqual(wantResponse, resp) {
  938. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  939. }
  940. }
  941. func TestHTTPKeysAPIGetAction(t *testing.T) {
  942. tests := []struct {
  943. key string
  944. opts *GetOptions
  945. wantAction httpAction
  946. }{
  947. // nil GetOptions
  948. {
  949. key: "/foo",
  950. opts: nil,
  951. wantAction: &getAction{
  952. Key: "/foo",
  953. Sorted: false,
  954. Recursive: false,
  955. },
  956. },
  957. // empty GetOptions
  958. {
  959. key: "/foo",
  960. opts: &GetOptions{},
  961. wantAction: &getAction{
  962. Key: "/foo",
  963. Sorted: false,
  964. Recursive: false,
  965. },
  966. },
  967. // populated GetOptions
  968. {
  969. key: "/foo",
  970. opts: &GetOptions{
  971. Sort: true,
  972. Recursive: true,
  973. },
  974. wantAction: &getAction{
  975. Key: "/foo",
  976. Sorted: true,
  977. Recursive: true,
  978. },
  979. },
  980. }
  981. for i, tt := range tests {
  982. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  983. kAPI := httpKeysAPI{client: client}
  984. kAPI.Get(context.Background(), tt.key, tt.opts)
  985. }
  986. }
  987. func TestHTTPKeysAPIGetError(t *testing.T) {
  988. tests := []httpClient{
  989. // generic HTTP client failure
  990. &staticHTTPClient{
  991. err: errors.New("fail!"),
  992. },
  993. // unusable status code
  994. &staticHTTPClient{
  995. resp: http.Response{
  996. StatusCode: http.StatusTeapot,
  997. },
  998. },
  999. // etcd Error response
  1000. &staticHTTPClient{
  1001. resp: http.Response{
  1002. StatusCode: http.StatusInternalServerError,
  1003. },
  1004. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1005. },
  1006. }
  1007. for i, tt := range tests {
  1008. kAPI := httpKeysAPI{client: tt}
  1009. resp, err := kAPI.Get(context.Background(), "/foo", nil)
  1010. if err == nil {
  1011. t.Errorf("#%d: received nil error", i)
  1012. }
  1013. if resp != nil {
  1014. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1015. }
  1016. }
  1017. }
  1018. func TestHTTPKeysAPIGetResponse(t *testing.T) {
  1019. client := &staticHTTPClient{
  1020. resp: http.Response{
  1021. StatusCode: http.StatusOK,
  1022. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  1023. },
  1024. body: []byte(`{"action":"get","node":{"key":"/pants/foo/bar","modifiedIndex":25,"createdIndex":19,"nodes":[{"key":"/pants/foo/bar/baz","value":"snarf","createdIndex":21,"modifiedIndex":25}]}}`),
  1025. }
  1026. wantResponse := &Response{
  1027. Action: "get",
  1028. Node: &Node{
  1029. Key: "/pants/foo/bar",
  1030. Nodes: []*Node{
  1031. &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: 21, ModifiedIndex: 25},
  1032. },
  1033. CreatedIndex: uint64(19),
  1034. ModifiedIndex: uint64(25),
  1035. },
  1036. Index: uint64(42),
  1037. }
  1038. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1039. resp, err := kAPI.Get(context.Background(), "/foo/bar", &GetOptions{Recursive: true})
  1040. if err != nil {
  1041. t.Errorf("non-nil error: %#v", err)
  1042. }
  1043. if !reflect.DeepEqual(wantResponse, resp) {
  1044. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1045. }
  1046. }
  1047. func TestHTTPKeysAPIDeleteAction(t *testing.T) {
  1048. tests := []struct {
  1049. key string
  1050. value string
  1051. opts *DeleteOptions
  1052. wantAction httpAction
  1053. }{
  1054. // nil DeleteOptions
  1055. {
  1056. key: "/foo",
  1057. opts: nil,
  1058. wantAction: &deleteAction{
  1059. Key: "/foo",
  1060. PrevValue: "",
  1061. PrevIndex: 0,
  1062. Recursive: false,
  1063. },
  1064. },
  1065. // empty DeleteOptions
  1066. {
  1067. key: "/foo",
  1068. opts: &DeleteOptions{},
  1069. wantAction: &deleteAction{
  1070. Key: "/foo",
  1071. PrevValue: "",
  1072. PrevIndex: 0,
  1073. Recursive: false,
  1074. },
  1075. },
  1076. // populated DeleteOptions
  1077. {
  1078. key: "/foo",
  1079. opts: &DeleteOptions{
  1080. PrevValue: "baz",
  1081. PrevIndex: 13,
  1082. Recursive: true,
  1083. },
  1084. wantAction: &deleteAction{
  1085. Key: "/foo",
  1086. PrevValue: "baz",
  1087. PrevIndex: 13,
  1088. Recursive: true,
  1089. },
  1090. },
  1091. }
  1092. for i, tt := range tests {
  1093. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1094. kAPI := httpKeysAPI{client: client}
  1095. kAPI.Delete(context.Background(), tt.key, tt.opts)
  1096. }
  1097. }
  1098. func TestHTTPKeysAPIDeleteError(t *testing.T) {
  1099. tests := []httpClient{
  1100. // generic HTTP client failure
  1101. &staticHTTPClient{
  1102. err: errors.New("fail!"),
  1103. },
  1104. // unusable status code
  1105. &staticHTTPClient{
  1106. resp: http.Response{
  1107. StatusCode: http.StatusTeapot,
  1108. },
  1109. },
  1110. // etcd Error response
  1111. &staticHTTPClient{
  1112. resp: http.Response{
  1113. StatusCode: http.StatusInternalServerError,
  1114. },
  1115. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1116. },
  1117. }
  1118. for i, tt := range tests {
  1119. kAPI := httpKeysAPI{client: tt}
  1120. resp, err := kAPI.Delete(context.Background(), "/foo", nil)
  1121. if err == nil {
  1122. t.Errorf("#%d: received nil error", i)
  1123. }
  1124. if resp != nil {
  1125. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1126. }
  1127. }
  1128. }
  1129. func TestHTTPKeysAPIDeleteResponse(t *testing.T) {
  1130. client := &staticHTTPClient{
  1131. resp: http.Response{
  1132. StatusCode: http.StatusOK,
  1133. Header: http.Header{"X-Etcd-Index": []string{"22"}},
  1134. },
  1135. body: []byte(`{"action":"delete","node":{"key":"/pants/foo/bar/baz","value":"snarf","modifiedIndex":22,"createdIndex":19},"prevNode":{"key":"/pants/foo/bar/baz","value":"snazz","modifiedIndex":20,"createdIndex":19}}`),
  1136. }
  1137. wantResponse := &Response{
  1138. Action: "delete",
  1139. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(22)},
  1140. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  1141. Index: uint64(22),
  1142. }
  1143. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1144. resp, err := kAPI.Delete(context.Background(), "/foo/bar/baz", nil)
  1145. if err != nil {
  1146. t.Errorf("non-nil error: %#v", err)
  1147. }
  1148. if !reflect.DeepEqual(wantResponse, resp) {
  1149. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1150. }
  1151. }
  1152. func TestHTTPKeysAPICreateAction(t *testing.T) {
  1153. act := &setAction{
  1154. Key: "/foo",
  1155. Value: "bar",
  1156. PrevExist: PrevNoExist,
  1157. PrevIndex: 0,
  1158. PrevValue: "",
  1159. TTL: 0,
  1160. }
  1161. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1162. kAPI.Create(context.Background(), "/foo", "bar")
  1163. }
  1164. func TestHTTPKeysAPICreateInOrderAction(t *testing.T) {
  1165. act := &createInOrderAction{
  1166. Dir: "/foo",
  1167. Value: "bar",
  1168. TTL: 0,
  1169. }
  1170. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1171. kAPI.CreateInOrder(context.Background(), "/foo", "bar", nil)
  1172. }
  1173. func TestHTTPKeysAPIUpdateAction(t *testing.T) {
  1174. act := &setAction{
  1175. Key: "/foo",
  1176. Value: "bar",
  1177. PrevExist: PrevExist,
  1178. PrevIndex: 0,
  1179. PrevValue: "",
  1180. TTL: 0,
  1181. }
  1182. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1183. kAPI.Update(context.Background(), "/foo", "bar")
  1184. }