keys_test.go 31 KB

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