keys_test.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. // Copyright 2015 The etcd Authors
  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. "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. // Prefix is joined to path
  76. {
  77. endpoint: url.URL{Scheme: "https", Host: "example.com", Path: "/foo"},
  78. prefix: "/bar",
  79. key: "",
  80. want: url.URL{Scheme: "https", Host: "example.com", Path: "/foo/bar"},
  81. },
  82. // Keep trailing slash
  83. {
  84. endpoint: url.URL{Scheme: "https", Host: "example.com", Path: "/foo"},
  85. prefix: "/bar",
  86. key: "/baz/",
  87. want: url.URL{Scheme: "https", Host: "example.com", Path: "/foo/bar/baz/"},
  88. },
  89. }
  90. for i, tt := range tests {
  91. got := v2KeysURL(tt.endpoint, tt.prefix, tt.key)
  92. if tt.want != *got {
  93. t.Errorf("#%d: want=%#v, got=%#v", i, tt.want, *got)
  94. }
  95. }
  96. }
  97. func TestGetAction(t *testing.T) {
  98. ep := url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"}
  99. baseWantURL := &url.URL{
  100. Scheme: "http",
  101. Host: "example.com",
  102. Path: "/v2/keys/foo/bar",
  103. }
  104. wantHeader := http.Header{}
  105. tests := []struct {
  106. recursive bool
  107. sorted bool
  108. quorum bool
  109. wantQuery string
  110. }{
  111. {
  112. recursive: false,
  113. sorted: false,
  114. quorum: false,
  115. wantQuery: "quorum=false&recursive=false&sorted=false",
  116. },
  117. {
  118. recursive: true,
  119. sorted: false,
  120. quorum: false,
  121. wantQuery: "quorum=false&recursive=true&sorted=false",
  122. },
  123. {
  124. recursive: false,
  125. sorted: true,
  126. quorum: false,
  127. wantQuery: "quorum=false&recursive=false&sorted=true",
  128. },
  129. {
  130. recursive: true,
  131. sorted: true,
  132. quorum: false,
  133. wantQuery: "quorum=false&recursive=true&sorted=true",
  134. },
  135. {
  136. recursive: false,
  137. sorted: false,
  138. quorum: true,
  139. wantQuery: "quorum=true&recursive=false&sorted=false",
  140. },
  141. }
  142. for i, tt := range tests {
  143. f := getAction{
  144. Key: "/foo/bar",
  145. Recursive: tt.recursive,
  146. Sorted: tt.sorted,
  147. Quorum: tt.quorum,
  148. }
  149. got := *f.HTTPRequest(ep)
  150. wantURL := baseWantURL
  151. wantURL.RawQuery = tt.wantQuery
  152. err := assertRequest(got, "GET", wantURL, wantHeader, nil)
  153. if err != nil {
  154. t.Errorf("#%d: %v", i, err)
  155. }
  156. }
  157. }
  158. func TestWaitAction(t *testing.T) {
  159. ep := url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"}
  160. baseWantURL := &url.URL{
  161. Scheme: "http",
  162. Host: "example.com",
  163. Path: "/v2/keys/foo/bar",
  164. }
  165. wantHeader := http.Header{}
  166. tests := []struct {
  167. waitIndex uint64
  168. recursive bool
  169. wantQuery string
  170. }{
  171. {
  172. recursive: false,
  173. waitIndex: uint64(0),
  174. wantQuery: "recursive=false&wait=true&waitIndex=0",
  175. },
  176. {
  177. recursive: false,
  178. waitIndex: uint64(12),
  179. wantQuery: "recursive=false&wait=true&waitIndex=12",
  180. },
  181. {
  182. recursive: true,
  183. waitIndex: uint64(12),
  184. wantQuery: "recursive=true&wait=true&waitIndex=12",
  185. },
  186. }
  187. for i, tt := range tests {
  188. f := waitAction{
  189. Key: "/foo/bar",
  190. WaitIndex: tt.waitIndex,
  191. Recursive: tt.recursive,
  192. }
  193. got := *f.HTTPRequest(ep)
  194. wantURL := baseWantURL
  195. wantURL.RawQuery = tt.wantQuery
  196. err := assertRequest(got, "GET", wantURL, wantHeader, nil)
  197. if err != nil {
  198. t.Errorf("#%d: unexpected error: %#v", i, err)
  199. }
  200. }
  201. }
  202. func TestSetAction(t *testing.T) {
  203. wantHeader := http.Header(map[string][]string{
  204. "Content-Type": {"application/x-www-form-urlencoded"},
  205. })
  206. tests := []struct {
  207. act setAction
  208. wantURL string
  209. wantBody string
  210. }{
  211. // default prefix
  212. {
  213. act: setAction{
  214. Prefix: defaultV2KeysPrefix,
  215. Key: "foo",
  216. },
  217. wantURL: "http://example.com/v2/keys/foo",
  218. wantBody: "value=",
  219. },
  220. // non-default prefix
  221. {
  222. act: setAction{
  223. Prefix: "/pfx",
  224. Key: "foo",
  225. },
  226. wantURL: "http://example.com/pfx/foo",
  227. wantBody: "value=",
  228. },
  229. // no prefix
  230. {
  231. act: setAction{
  232. Key: "foo",
  233. },
  234. wantURL: "http://example.com/foo",
  235. wantBody: "value=",
  236. },
  237. // Key with path separators
  238. {
  239. act: setAction{
  240. Prefix: defaultV2KeysPrefix,
  241. Key: "foo/bar/baz",
  242. },
  243. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  244. wantBody: "value=",
  245. },
  246. // Key with leading slash, Prefix with trailing slash
  247. {
  248. act: setAction{
  249. Prefix: "/foo/",
  250. Key: "/bar",
  251. },
  252. wantURL: "http://example.com/foo/bar",
  253. wantBody: "value=",
  254. },
  255. // Key with trailing slash
  256. {
  257. act: setAction{
  258. Key: "/foo/",
  259. },
  260. wantURL: "http://example.com/foo/",
  261. wantBody: "value=",
  262. },
  263. // Value is set
  264. {
  265. act: setAction{
  266. Key: "foo",
  267. Value: "baz",
  268. },
  269. wantURL: "http://example.com/foo",
  270. wantBody: "value=baz",
  271. },
  272. // PrevExist set, but still ignored
  273. {
  274. act: setAction{
  275. Key: "foo",
  276. PrevExist: PrevIgnore,
  277. },
  278. wantURL: "http://example.com/foo",
  279. wantBody: "value=",
  280. },
  281. // PrevExist set to true
  282. {
  283. act: setAction{
  284. Key: "foo",
  285. PrevExist: PrevExist,
  286. },
  287. wantURL: "http://example.com/foo?prevExist=true",
  288. wantBody: "value=",
  289. },
  290. // PrevExist set to false
  291. {
  292. act: setAction{
  293. Key: "foo",
  294. PrevExist: PrevNoExist,
  295. },
  296. wantURL: "http://example.com/foo?prevExist=false",
  297. wantBody: "value=",
  298. },
  299. // PrevValue is urlencoded
  300. {
  301. act: setAction{
  302. Key: "foo",
  303. PrevValue: "bar baz",
  304. },
  305. wantURL: "http://example.com/foo?prevValue=bar+baz",
  306. wantBody: "value=",
  307. },
  308. // PrevIndex is set
  309. {
  310. act: setAction{
  311. Key: "foo",
  312. PrevIndex: uint64(12),
  313. },
  314. wantURL: "http://example.com/foo?prevIndex=12",
  315. wantBody: "value=",
  316. },
  317. // TTL is set
  318. {
  319. act: setAction{
  320. Key: "foo",
  321. TTL: 3 * time.Minute,
  322. },
  323. wantURL: "http://example.com/foo",
  324. wantBody: "ttl=180&value=",
  325. },
  326. // Refresh is set
  327. {
  328. act: setAction{
  329. Key: "foo",
  330. TTL: 3 * time.Minute,
  331. Refresh: true,
  332. },
  333. wantURL: "http://example.com/foo",
  334. wantBody: "refresh=true&ttl=180&value=",
  335. },
  336. // Dir is set
  337. {
  338. act: setAction{
  339. Key: "foo",
  340. Dir: true,
  341. },
  342. wantURL: "http://example.com/foo?dir=true",
  343. wantBody: "",
  344. },
  345. // Dir is set with a value
  346. {
  347. act: setAction{
  348. Key: "foo",
  349. Value: "bar",
  350. Dir: true,
  351. },
  352. wantURL: "http://example.com/foo?dir=true",
  353. wantBody: "",
  354. },
  355. // Dir is set with PrevExist set to true
  356. {
  357. act: setAction{
  358. Key: "foo",
  359. PrevExist: PrevExist,
  360. Dir: true,
  361. },
  362. wantURL: "http://example.com/foo?dir=true&prevExist=true",
  363. wantBody: "",
  364. },
  365. // Dir is set with PrevValue
  366. {
  367. act: setAction{
  368. Key: "foo",
  369. PrevValue: "bar",
  370. Dir: true,
  371. },
  372. wantURL: "http://example.com/foo?dir=true",
  373. wantBody: "",
  374. },
  375. }
  376. for i, tt := range tests {
  377. u, err := url.Parse(tt.wantURL)
  378. if err != nil {
  379. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  380. }
  381. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  382. if err := assertRequest(*got, "PUT", u, wantHeader, []byte(tt.wantBody)); err != nil {
  383. t.Errorf("#%d: %v", i, err)
  384. }
  385. }
  386. }
  387. func TestCreateInOrderAction(t *testing.T) {
  388. wantHeader := http.Header(map[string][]string{
  389. "Content-Type": {"application/x-www-form-urlencoded"},
  390. })
  391. tests := []struct {
  392. act createInOrderAction
  393. wantURL string
  394. wantBody string
  395. }{
  396. // default prefix
  397. {
  398. act: createInOrderAction{
  399. Prefix: defaultV2KeysPrefix,
  400. Dir: "foo",
  401. },
  402. wantURL: "http://example.com/v2/keys/foo",
  403. wantBody: "value=",
  404. },
  405. // non-default prefix
  406. {
  407. act: createInOrderAction{
  408. Prefix: "/pfx",
  409. Dir: "foo",
  410. },
  411. wantURL: "http://example.com/pfx/foo",
  412. wantBody: "value=",
  413. },
  414. // no prefix
  415. {
  416. act: createInOrderAction{
  417. Dir: "foo",
  418. },
  419. wantURL: "http://example.com/foo",
  420. wantBody: "value=",
  421. },
  422. // Key with path separators
  423. {
  424. act: createInOrderAction{
  425. Prefix: defaultV2KeysPrefix,
  426. Dir: "foo/bar/baz",
  427. },
  428. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  429. wantBody: "value=",
  430. },
  431. // Key with leading slash, Prefix with trailing slash
  432. {
  433. act: createInOrderAction{
  434. Prefix: "/foo/",
  435. Dir: "/bar",
  436. },
  437. wantURL: "http://example.com/foo/bar",
  438. wantBody: "value=",
  439. },
  440. // Key with trailing slash
  441. {
  442. act: createInOrderAction{
  443. Dir: "/foo/",
  444. },
  445. wantURL: "http://example.com/foo/",
  446. wantBody: "value=",
  447. },
  448. // Value is set
  449. {
  450. act: createInOrderAction{
  451. Dir: "foo",
  452. Value: "baz",
  453. },
  454. wantURL: "http://example.com/foo",
  455. wantBody: "value=baz",
  456. },
  457. // TTL is set
  458. {
  459. act: createInOrderAction{
  460. Dir: "foo",
  461. TTL: 3 * time.Minute,
  462. },
  463. wantURL: "http://example.com/foo",
  464. wantBody: "ttl=180&value=",
  465. },
  466. }
  467. for i, tt := range tests {
  468. u, err := url.Parse(tt.wantURL)
  469. if err != nil {
  470. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  471. }
  472. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  473. if err := assertRequest(*got, "POST", u, wantHeader, []byte(tt.wantBody)); err != nil {
  474. t.Errorf("#%d: %v", i, err)
  475. }
  476. }
  477. }
  478. func TestDeleteAction(t *testing.T) {
  479. wantHeader := http.Header(map[string][]string{
  480. "Content-Type": {"application/x-www-form-urlencoded"},
  481. })
  482. tests := []struct {
  483. act deleteAction
  484. wantURL string
  485. }{
  486. // default prefix
  487. {
  488. act: deleteAction{
  489. Prefix: defaultV2KeysPrefix,
  490. Key: "foo",
  491. },
  492. wantURL: "http://example.com/v2/keys/foo",
  493. },
  494. // non-default prefix
  495. {
  496. act: deleteAction{
  497. Prefix: "/pfx",
  498. Key: "foo",
  499. },
  500. wantURL: "http://example.com/pfx/foo",
  501. },
  502. // no prefix
  503. {
  504. act: deleteAction{
  505. Key: "foo",
  506. },
  507. wantURL: "http://example.com/foo",
  508. },
  509. // Key with path separators
  510. {
  511. act: deleteAction{
  512. Prefix: defaultV2KeysPrefix,
  513. Key: "foo/bar/baz",
  514. },
  515. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  516. },
  517. // Key with leading slash, Prefix with trailing slash
  518. {
  519. act: deleteAction{
  520. Prefix: "/foo/",
  521. Key: "/bar",
  522. },
  523. wantURL: "http://example.com/foo/bar",
  524. },
  525. // Key with trailing slash
  526. {
  527. act: deleteAction{
  528. Key: "/foo/",
  529. },
  530. wantURL: "http://example.com/foo/",
  531. },
  532. // Recursive set to true
  533. {
  534. act: deleteAction{
  535. Key: "foo",
  536. Recursive: true,
  537. },
  538. wantURL: "http://example.com/foo?recursive=true",
  539. },
  540. // PrevValue is urlencoded
  541. {
  542. act: deleteAction{
  543. Key: "foo",
  544. PrevValue: "bar baz",
  545. },
  546. wantURL: "http://example.com/foo?prevValue=bar+baz",
  547. },
  548. // PrevIndex is set
  549. {
  550. act: deleteAction{
  551. Key: "foo",
  552. PrevIndex: uint64(12),
  553. },
  554. wantURL: "http://example.com/foo?prevIndex=12",
  555. },
  556. }
  557. for i, tt := range tests {
  558. u, err := url.Parse(tt.wantURL)
  559. if err != nil {
  560. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  561. }
  562. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  563. if err := assertRequest(*got, "DELETE", u, wantHeader, nil); err != nil {
  564. t.Errorf("#%d: %v", i, err)
  565. }
  566. }
  567. }
  568. func assertRequest(got http.Request, wantMethod string, wantURL *url.URL, wantHeader http.Header, wantBody []byte) error {
  569. if wantMethod != got.Method {
  570. return fmt.Errorf("want.Method=%#v got.Method=%#v", wantMethod, got.Method)
  571. }
  572. if !reflect.DeepEqual(wantURL, got.URL) {
  573. return fmt.Errorf("want.URL=%#v got.URL=%#v", wantURL, got.URL)
  574. }
  575. if !reflect.DeepEqual(wantHeader, got.Header) {
  576. return fmt.Errorf("want.Header=%#v got.Header=%#v", wantHeader, got.Header)
  577. }
  578. if got.Body == nil {
  579. if wantBody != nil {
  580. return fmt.Errorf("want.Body=%v got.Body=%v", wantBody, got.Body)
  581. }
  582. } else {
  583. if wantBody == nil {
  584. return fmt.Errorf("want.Body=%v got.Body=%s", wantBody, got.Body)
  585. }
  586. gotBytes, err := ioutil.ReadAll(got.Body)
  587. if err != nil {
  588. return err
  589. }
  590. if !reflect.DeepEqual(wantBody, gotBytes) {
  591. return fmt.Errorf("want.Body=%s got.Body=%s", wantBody, gotBytes)
  592. }
  593. }
  594. return nil
  595. }
  596. func TestUnmarshalSuccessfulResponse(t *testing.T) {
  597. var expiration time.Time
  598. expiration.UnmarshalText([]byte("2015-04-07T04:40:23.044979686Z"))
  599. tests := []struct {
  600. hdr string
  601. body string
  602. wantRes *Response
  603. wantErr bool
  604. }{
  605. // Neither PrevNode or Node
  606. {
  607. hdr: "1",
  608. body: `{"action":"delete"}`,
  609. wantRes: &Response{Action: "delete", Index: 1},
  610. wantErr: false,
  611. },
  612. // PrevNode
  613. {
  614. hdr: "15",
  615. body: `{"action":"delete", "prevNode": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  616. wantRes: &Response{
  617. Action: "delete",
  618. Index: 15,
  619. Node: nil,
  620. PrevNode: &Node{
  621. Key: "/foo",
  622. Value: "bar",
  623. ModifiedIndex: 12,
  624. CreatedIndex: 10,
  625. },
  626. },
  627. wantErr: false,
  628. },
  629. // Node
  630. {
  631. hdr: "15",
  632. body: `{"action":"get", "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10, "ttl": 10, "expiration": "2015-04-07T04:40:23.044979686Z"}}`,
  633. wantRes: &Response{
  634. Action: "get",
  635. Index: 15,
  636. Node: &Node{
  637. Key: "/foo",
  638. Value: "bar",
  639. ModifiedIndex: 12,
  640. CreatedIndex: 10,
  641. TTL: 10,
  642. Expiration: &expiration,
  643. },
  644. PrevNode: nil,
  645. },
  646. wantErr: false,
  647. },
  648. // Node Dir
  649. {
  650. hdr: "15",
  651. body: `{"action":"get", "node": {"key": "/foo", "dir": true, "modifiedIndex": 12, "createdIndex": 10}}`,
  652. wantRes: &Response{
  653. Action: "get",
  654. Index: 15,
  655. Node: &Node{
  656. Key: "/foo",
  657. Dir: true,
  658. ModifiedIndex: 12,
  659. CreatedIndex: 10,
  660. },
  661. PrevNode: nil,
  662. },
  663. wantErr: false,
  664. },
  665. // PrevNode and Node
  666. {
  667. hdr: "15",
  668. body: `{"action":"update", "prevNode": {"key": "/foo", "value": "baz", "modifiedIndex": 10, "createdIndex": 10}, "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  669. wantRes: &Response{
  670. Action: "update",
  671. Index: 15,
  672. PrevNode: &Node{
  673. Key: "/foo",
  674. Value: "baz",
  675. ModifiedIndex: 10,
  676. CreatedIndex: 10,
  677. },
  678. Node: &Node{
  679. Key: "/foo",
  680. Value: "bar",
  681. ModifiedIndex: 12,
  682. CreatedIndex: 10,
  683. },
  684. },
  685. wantErr: false,
  686. },
  687. // Garbage in body
  688. {
  689. hdr: "",
  690. body: `garbage`,
  691. wantRes: nil,
  692. wantErr: true,
  693. },
  694. // non-integer index
  695. {
  696. hdr: "poo",
  697. body: `{}`,
  698. wantRes: nil,
  699. wantErr: true,
  700. },
  701. }
  702. for i, tt := range tests {
  703. h := make(http.Header)
  704. h.Add("X-Etcd-Index", tt.hdr)
  705. res, err := unmarshalSuccessfulKeysResponse(h, []byte(tt.body))
  706. if tt.wantErr != (err != nil) {
  707. t.Errorf("#%d: wantErr=%t, err=%v", i, tt.wantErr, err)
  708. }
  709. if (res == nil) != (tt.wantRes == nil) {
  710. t.Errorf("#%d: received res=%#v, but expected res=%#v", i, res, tt.wantRes)
  711. continue
  712. } else if tt.wantRes == nil {
  713. // expected and successfully got nil response
  714. continue
  715. }
  716. if res.Action != tt.wantRes.Action {
  717. t.Errorf("#%d: Action=%s, expected %s", i, res.Action, tt.wantRes.Action)
  718. }
  719. if res.Index != tt.wantRes.Index {
  720. t.Errorf("#%d: Index=%d, expected %d", i, res.Index, tt.wantRes.Index)
  721. }
  722. if !reflect.DeepEqual(res.Node, tt.wantRes.Node) {
  723. t.Errorf("#%d: Node=%v, expected %v", i, res.Node, tt.wantRes.Node)
  724. }
  725. }
  726. }
  727. func TestUnmarshalFailedKeysResponse(t *testing.T) {
  728. body := []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`)
  729. wantErr := Error{
  730. Code: 100,
  731. Message: "Key not found",
  732. Cause: "/foo",
  733. Index: uint64(18),
  734. }
  735. gotErr := unmarshalFailedKeysResponse(body)
  736. if !reflect.DeepEqual(wantErr, gotErr) {
  737. t.Errorf("unexpected error: want=%#v got=%#v", wantErr, gotErr)
  738. }
  739. }
  740. func TestUnmarshalFailedKeysResponseBadJSON(t *testing.T) {
  741. err := unmarshalFailedKeysResponse([]byte(`{"er`))
  742. if err == nil {
  743. t.Errorf("got nil error")
  744. } else if _, ok := err.(Error); ok {
  745. t.Errorf("error is of incorrect type *Error: %#v", err)
  746. }
  747. }
  748. func TestHTTPWatcherNextWaitAction(t *testing.T) {
  749. initAction := waitAction{
  750. Prefix: "/pants",
  751. Key: "/foo/bar",
  752. Recursive: true,
  753. WaitIndex: 19,
  754. }
  755. client := &actionAssertingHTTPClient{
  756. t: t,
  757. act: &initAction,
  758. resp: http.Response{
  759. StatusCode: http.StatusOK,
  760. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  761. },
  762. 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}}`),
  763. }
  764. wantResponse := &Response{
  765. Action: "update",
  766. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(21)},
  767. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  768. Index: uint64(42),
  769. }
  770. wantNextWait := waitAction{
  771. Prefix: "/pants",
  772. Key: "/foo/bar",
  773. Recursive: true,
  774. WaitIndex: 22,
  775. }
  776. watcher := &httpWatcher{
  777. client: client,
  778. nextWait: initAction,
  779. }
  780. resp, err := watcher.Next(context.Background())
  781. if err != nil {
  782. t.Errorf("non-nil error: %#v", err)
  783. }
  784. if !reflect.DeepEqual(wantResponse, resp) {
  785. t.Errorf("received incorrect Response: want=%#v got=%#v", wantResponse, resp)
  786. }
  787. if !reflect.DeepEqual(wantNextWait, watcher.nextWait) {
  788. t.Errorf("nextWait incorrect: want=%#v got=%#v", wantNextWait, watcher.nextWait)
  789. }
  790. }
  791. func TestHTTPWatcherNextFail(t *testing.T) {
  792. tests := []httpClient{
  793. // generic HTTP client failure
  794. &staticHTTPClient{
  795. err: errors.New("fail!"),
  796. },
  797. // unusable status code
  798. &staticHTTPClient{
  799. resp: http.Response{
  800. StatusCode: http.StatusTeapot,
  801. },
  802. },
  803. // etcd Error response
  804. &staticHTTPClient{
  805. resp: http.Response{
  806. StatusCode: http.StatusNotFound,
  807. },
  808. body: []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`),
  809. },
  810. }
  811. for i, tt := range tests {
  812. act := waitAction{
  813. Prefix: "/pants",
  814. Key: "/foo/bar",
  815. Recursive: true,
  816. WaitIndex: 19,
  817. }
  818. watcher := &httpWatcher{
  819. client: tt,
  820. nextWait: act,
  821. }
  822. resp, err := watcher.Next(context.Background())
  823. if err == nil {
  824. t.Errorf("#%d: expected non-nil error", i)
  825. }
  826. if resp != nil {
  827. t.Errorf("#%d: expected nil Response, got %#v", i, resp)
  828. }
  829. if !reflect.DeepEqual(act, watcher.nextWait) {
  830. t.Errorf("#%d: nextWait changed: want=%#v got=%#v", i, act, watcher.nextWait)
  831. }
  832. }
  833. }
  834. func TestHTTPKeysAPIWatcherAction(t *testing.T) {
  835. tests := []struct {
  836. key string
  837. opts *WatcherOptions
  838. want waitAction
  839. }{
  840. {
  841. key: "/foo",
  842. opts: nil,
  843. want: waitAction{
  844. Key: "/foo",
  845. Recursive: false,
  846. WaitIndex: 0,
  847. },
  848. },
  849. {
  850. key: "/foo",
  851. opts: &WatcherOptions{
  852. Recursive: false,
  853. AfterIndex: 0,
  854. },
  855. want: waitAction{
  856. Key: "/foo",
  857. Recursive: false,
  858. WaitIndex: 0,
  859. },
  860. },
  861. {
  862. key: "/foo",
  863. opts: &WatcherOptions{
  864. Recursive: true,
  865. AfterIndex: 0,
  866. },
  867. want: waitAction{
  868. Key: "/foo",
  869. Recursive: true,
  870. WaitIndex: 0,
  871. },
  872. },
  873. {
  874. key: "/foo",
  875. opts: &WatcherOptions{
  876. Recursive: false,
  877. AfterIndex: 19,
  878. },
  879. want: waitAction{
  880. Key: "/foo",
  881. Recursive: false,
  882. WaitIndex: 20,
  883. },
  884. },
  885. }
  886. for i, tt := range tests {
  887. kAPI := &httpKeysAPI{
  888. client: &staticHTTPClient{err: errors.New("fail!")},
  889. }
  890. want := &httpWatcher{
  891. client: &staticHTTPClient{err: errors.New("fail!")},
  892. nextWait: tt.want,
  893. }
  894. got := kAPI.Watcher(tt.key, tt.opts)
  895. if !reflect.DeepEqual(want, got) {
  896. t.Errorf("#%d: incorrect watcher: want=%#v got=%#v", i, want, got)
  897. }
  898. }
  899. }
  900. func TestHTTPKeysAPISetAction(t *testing.T) {
  901. tests := []struct {
  902. key string
  903. value string
  904. opts *SetOptions
  905. wantAction httpAction
  906. }{
  907. // nil SetOptions
  908. {
  909. key: "/foo",
  910. value: "bar",
  911. opts: nil,
  912. wantAction: &setAction{
  913. Key: "/foo",
  914. Value: "bar",
  915. PrevValue: "",
  916. PrevIndex: 0,
  917. PrevExist: PrevIgnore,
  918. TTL: 0,
  919. },
  920. },
  921. // empty SetOptions
  922. {
  923. key: "/foo",
  924. value: "bar",
  925. opts: &SetOptions{},
  926. wantAction: &setAction{
  927. Key: "/foo",
  928. Value: "bar",
  929. PrevValue: "",
  930. PrevIndex: 0,
  931. PrevExist: PrevIgnore,
  932. TTL: 0,
  933. },
  934. },
  935. // populated SetOptions
  936. {
  937. key: "/foo",
  938. value: "bar",
  939. opts: &SetOptions{
  940. PrevValue: "baz",
  941. PrevIndex: 13,
  942. PrevExist: PrevExist,
  943. TTL: time.Minute,
  944. Dir: true,
  945. },
  946. wantAction: &setAction{
  947. Key: "/foo",
  948. Value: "bar",
  949. PrevValue: "baz",
  950. PrevIndex: 13,
  951. PrevExist: PrevExist,
  952. TTL: time.Minute,
  953. Dir: true,
  954. },
  955. },
  956. }
  957. for i, tt := range tests {
  958. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  959. kAPI := httpKeysAPI{client: client}
  960. kAPI.Set(context.Background(), tt.key, tt.value, tt.opts)
  961. }
  962. }
  963. func TestHTTPKeysAPISetError(t *testing.T) {
  964. tests := []httpClient{
  965. // generic HTTP client failure
  966. &staticHTTPClient{
  967. err: errors.New("fail!"),
  968. },
  969. // unusable status code
  970. &staticHTTPClient{
  971. resp: http.Response{
  972. StatusCode: http.StatusTeapot,
  973. },
  974. },
  975. // etcd Error response
  976. &staticHTTPClient{
  977. resp: http.Response{
  978. StatusCode: http.StatusInternalServerError,
  979. },
  980. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  981. },
  982. }
  983. for i, tt := range tests {
  984. kAPI := httpKeysAPI{client: tt}
  985. resp, err := kAPI.Set(context.Background(), "/foo", "bar", nil)
  986. if err == nil {
  987. t.Errorf("#%d: received nil error", i)
  988. }
  989. if resp != nil {
  990. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  991. }
  992. }
  993. }
  994. func TestHTTPKeysAPISetResponse(t *testing.T) {
  995. client := &staticHTTPClient{
  996. resp: http.Response{
  997. StatusCode: http.StatusOK,
  998. Header: http.Header{"X-Etcd-Index": []string{"21"}},
  999. },
  1000. 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}}`),
  1001. }
  1002. wantResponse := &Response{
  1003. Action: "set",
  1004. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(21), ModifiedIndex: uint64(21)},
  1005. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  1006. Index: uint64(21),
  1007. }
  1008. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1009. resp, err := kAPI.Set(context.Background(), "/foo/bar/baz", "snarf", nil)
  1010. if err != nil {
  1011. t.Errorf("non-nil error: %#v", err)
  1012. }
  1013. if !reflect.DeepEqual(wantResponse, resp) {
  1014. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1015. }
  1016. }
  1017. func TestHTTPKeysAPIGetAction(t *testing.T) {
  1018. tests := []struct {
  1019. key string
  1020. opts *GetOptions
  1021. wantAction httpAction
  1022. }{
  1023. // nil GetOptions
  1024. {
  1025. key: "/foo",
  1026. opts: nil,
  1027. wantAction: &getAction{
  1028. Key: "/foo",
  1029. Sorted: false,
  1030. Recursive: false,
  1031. },
  1032. },
  1033. // empty GetOptions
  1034. {
  1035. key: "/foo",
  1036. opts: &GetOptions{},
  1037. wantAction: &getAction{
  1038. Key: "/foo",
  1039. Sorted: false,
  1040. Recursive: false,
  1041. },
  1042. },
  1043. // populated GetOptions
  1044. {
  1045. key: "/foo",
  1046. opts: &GetOptions{
  1047. Sort: true,
  1048. Recursive: true,
  1049. Quorum: true,
  1050. },
  1051. wantAction: &getAction{
  1052. Key: "/foo",
  1053. Sorted: true,
  1054. Recursive: true,
  1055. Quorum: true,
  1056. },
  1057. },
  1058. }
  1059. for i, tt := range tests {
  1060. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1061. kAPI := httpKeysAPI{client: client}
  1062. kAPI.Get(context.Background(), tt.key, tt.opts)
  1063. }
  1064. }
  1065. func TestHTTPKeysAPIGetError(t *testing.T) {
  1066. tests := []httpClient{
  1067. // generic HTTP client failure
  1068. &staticHTTPClient{
  1069. err: errors.New("fail!"),
  1070. },
  1071. // unusable status code
  1072. &staticHTTPClient{
  1073. resp: http.Response{
  1074. StatusCode: http.StatusTeapot,
  1075. },
  1076. },
  1077. // etcd Error response
  1078. &staticHTTPClient{
  1079. resp: http.Response{
  1080. StatusCode: http.StatusInternalServerError,
  1081. },
  1082. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1083. },
  1084. }
  1085. for i, tt := range tests {
  1086. kAPI := httpKeysAPI{client: tt}
  1087. resp, err := kAPI.Get(context.Background(), "/foo", nil)
  1088. if err == nil {
  1089. t.Errorf("#%d: received nil error", i)
  1090. }
  1091. if resp != nil {
  1092. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1093. }
  1094. }
  1095. }
  1096. func TestHTTPKeysAPIGetResponse(t *testing.T) {
  1097. client := &staticHTTPClient{
  1098. resp: http.Response{
  1099. StatusCode: http.StatusOK,
  1100. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  1101. },
  1102. 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}]}}`),
  1103. }
  1104. wantResponse := &Response{
  1105. Action: "get",
  1106. Node: &Node{
  1107. Key: "/pants/foo/bar",
  1108. Nodes: []*Node{
  1109. {Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: 21, ModifiedIndex: 25},
  1110. },
  1111. CreatedIndex: uint64(19),
  1112. ModifiedIndex: uint64(25),
  1113. },
  1114. Index: uint64(42),
  1115. }
  1116. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1117. resp, err := kAPI.Get(context.Background(), "/foo/bar", &GetOptions{Recursive: true})
  1118. if err != nil {
  1119. t.Errorf("non-nil error: %#v", err)
  1120. }
  1121. if !reflect.DeepEqual(wantResponse, resp) {
  1122. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1123. }
  1124. }
  1125. func TestHTTPKeysAPIDeleteAction(t *testing.T) {
  1126. tests := []struct {
  1127. key string
  1128. opts *DeleteOptions
  1129. wantAction httpAction
  1130. }{
  1131. // nil DeleteOptions
  1132. {
  1133. key: "/foo",
  1134. opts: nil,
  1135. wantAction: &deleteAction{
  1136. Key: "/foo",
  1137. PrevValue: "",
  1138. PrevIndex: 0,
  1139. Recursive: false,
  1140. },
  1141. },
  1142. // empty DeleteOptions
  1143. {
  1144. key: "/foo",
  1145. opts: &DeleteOptions{},
  1146. wantAction: &deleteAction{
  1147. Key: "/foo",
  1148. PrevValue: "",
  1149. PrevIndex: 0,
  1150. Recursive: false,
  1151. },
  1152. },
  1153. // populated DeleteOptions
  1154. {
  1155. key: "/foo",
  1156. opts: &DeleteOptions{
  1157. PrevValue: "baz",
  1158. PrevIndex: 13,
  1159. Recursive: true,
  1160. },
  1161. wantAction: &deleteAction{
  1162. Key: "/foo",
  1163. PrevValue: "baz",
  1164. PrevIndex: 13,
  1165. Recursive: true,
  1166. },
  1167. },
  1168. }
  1169. for i, tt := range tests {
  1170. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1171. kAPI := httpKeysAPI{client: client}
  1172. kAPI.Delete(context.Background(), tt.key, tt.opts)
  1173. }
  1174. }
  1175. func TestHTTPKeysAPIDeleteError(t *testing.T) {
  1176. tests := []httpClient{
  1177. // generic HTTP client failure
  1178. &staticHTTPClient{
  1179. err: errors.New("fail!"),
  1180. },
  1181. // unusable status code
  1182. &staticHTTPClient{
  1183. resp: http.Response{
  1184. StatusCode: http.StatusTeapot,
  1185. },
  1186. },
  1187. // etcd Error response
  1188. &staticHTTPClient{
  1189. resp: http.Response{
  1190. StatusCode: http.StatusInternalServerError,
  1191. },
  1192. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1193. },
  1194. }
  1195. for i, tt := range tests {
  1196. kAPI := httpKeysAPI{client: tt}
  1197. resp, err := kAPI.Delete(context.Background(), "/foo", nil)
  1198. if err == nil {
  1199. t.Errorf("#%d: received nil error", i)
  1200. }
  1201. if resp != nil {
  1202. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1203. }
  1204. }
  1205. }
  1206. func TestHTTPKeysAPIDeleteResponse(t *testing.T) {
  1207. client := &staticHTTPClient{
  1208. resp: http.Response{
  1209. StatusCode: http.StatusOK,
  1210. Header: http.Header{"X-Etcd-Index": []string{"22"}},
  1211. },
  1212. 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}}`),
  1213. }
  1214. wantResponse := &Response{
  1215. Action: "delete",
  1216. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(22)},
  1217. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  1218. Index: uint64(22),
  1219. }
  1220. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1221. resp, err := kAPI.Delete(context.Background(), "/foo/bar/baz", nil)
  1222. if err != nil {
  1223. t.Errorf("non-nil error: %#v", err)
  1224. }
  1225. if !reflect.DeepEqual(wantResponse, resp) {
  1226. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1227. }
  1228. }
  1229. func TestHTTPKeysAPICreateAction(t *testing.T) {
  1230. act := &setAction{
  1231. Key: "/foo",
  1232. Value: "bar",
  1233. PrevExist: PrevNoExist,
  1234. PrevIndex: 0,
  1235. PrevValue: "",
  1236. TTL: 0,
  1237. }
  1238. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1239. kAPI.Create(context.Background(), "/foo", "bar")
  1240. }
  1241. func TestHTTPKeysAPICreateInOrderAction(t *testing.T) {
  1242. act := &createInOrderAction{
  1243. Dir: "/foo",
  1244. Value: "bar",
  1245. TTL: 0,
  1246. }
  1247. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1248. kAPI.CreateInOrder(context.Background(), "/foo", "bar", nil)
  1249. }
  1250. func TestHTTPKeysAPIUpdateAction(t *testing.T) {
  1251. act := &setAction{
  1252. Key: "/foo",
  1253. Value: "bar",
  1254. PrevExist: PrevExist,
  1255. PrevIndex: 0,
  1256. PrevValue: "",
  1257. TTL: 0,
  1258. }
  1259. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1260. kAPI.Update(context.Background(), "/foo", "bar")
  1261. }
  1262. func TestNodeTTLDuration(t *testing.T) {
  1263. tests := []struct {
  1264. node *Node
  1265. want time.Duration
  1266. }{
  1267. {
  1268. node: &Node{TTL: 0},
  1269. want: 0,
  1270. },
  1271. {
  1272. node: &Node{TTL: 97},
  1273. want: 97 * time.Second,
  1274. },
  1275. }
  1276. for i, tt := range tests {
  1277. got := tt.node.TTLDuration()
  1278. if tt.want != got {
  1279. t.Errorf("#%d: incorrect duration: want=%v got=%v", i, tt.want, got)
  1280. }
  1281. }
  1282. }