keys_test.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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. "context"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "net/http"
  21. "net/url"
  22. "reflect"
  23. "testing"
  24. "time"
  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. indexHdr string
  610. clusterIDHdr string
  611. body string
  612. wantRes *Response
  613. wantErr bool
  614. }{
  615. // Neither PrevNode or Node
  616. {
  617. indexHdr: "1",
  618. body: `{"action":"delete"}`,
  619. wantRes: &Response{Action: "delete", Index: 1},
  620. wantErr: false,
  621. },
  622. // PrevNode
  623. {
  624. indexHdr: "15",
  625. body: `{"action":"delete", "prevNode": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  626. wantRes: &Response{
  627. Action: "delete",
  628. Index: 15,
  629. Node: nil,
  630. PrevNode: &Node{
  631. Key: "/foo",
  632. Value: "bar",
  633. ModifiedIndex: 12,
  634. CreatedIndex: 10,
  635. },
  636. },
  637. wantErr: false,
  638. },
  639. // Node
  640. {
  641. indexHdr: "15",
  642. body: `{"action":"get", "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10, "ttl": 10, "expiration": "2015-04-07T04:40:23.044979686Z"}}`,
  643. wantRes: &Response{
  644. Action: "get",
  645. Index: 15,
  646. Node: &Node{
  647. Key: "/foo",
  648. Value: "bar",
  649. ModifiedIndex: 12,
  650. CreatedIndex: 10,
  651. TTL: 10,
  652. Expiration: &expiration,
  653. },
  654. PrevNode: nil,
  655. },
  656. wantErr: false,
  657. },
  658. // Node Dir
  659. {
  660. indexHdr: "15",
  661. clusterIDHdr: "abcdef",
  662. body: `{"action":"get", "node": {"key": "/foo", "dir": true, "modifiedIndex": 12, "createdIndex": 10}}`,
  663. wantRes: &Response{
  664. Action: "get",
  665. Index: 15,
  666. Node: &Node{
  667. Key: "/foo",
  668. Dir: true,
  669. ModifiedIndex: 12,
  670. CreatedIndex: 10,
  671. },
  672. PrevNode: nil,
  673. ClusterID: "abcdef",
  674. },
  675. wantErr: false,
  676. },
  677. // PrevNode and Node
  678. {
  679. indexHdr: "15",
  680. body: `{"action":"update", "prevNode": {"key": "/foo", "value": "baz", "modifiedIndex": 10, "createdIndex": 10}, "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  681. wantRes: &Response{
  682. Action: "update",
  683. Index: 15,
  684. PrevNode: &Node{
  685. Key: "/foo",
  686. Value: "baz",
  687. ModifiedIndex: 10,
  688. CreatedIndex: 10,
  689. },
  690. Node: &Node{
  691. Key: "/foo",
  692. Value: "bar",
  693. ModifiedIndex: 12,
  694. CreatedIndex: 10,
  695. },
  696. },
  697. wantErr: false,
  698. },
  699. // Garbage in body
  700. {
  701. indexHdr: "",
  702. body: `garbage`,
  703. wantRes: nil,
  704. wantErr: true,
  705. },
  706. // non-integer index
  707. {
  708. indexHdr: "poo",
  709. body: `{}`,
  710. wantRes: nil,
  711. wantErr: true,
  712. },
  713. }
  714. for i, tt := range tests {
  715. h := make(http.Header)
  716. h.Add("X-Etcd-Index", tt.indexHdr)
  717. res, err := unmarshalSuccessfulKeysResponse(h, []byte(tt.body))
  718. if tt.wantErr != (err != nil) {
  719. t.Errorf("#%d: wantErr=%t, err=%v", i, tt.wantErr, err)
  720. }
  721. if (res == nil) != (tt.wantRes == nil) {
  722. t.Errorf("#%d: received res=%#v, but expected res=%#v", i, res, tt.wantRes)
  723. continue
  724. } else if tt.wantRes == nil {
  725. // expected and successfully got nil response
  726. continue
  727. }
  728. if res.Action != tt.wantRes.Action {
  729. t.Errorf("#%d: Action=%s, expected %s", i, res.Action, tt.wantRes.Action)
  730. }
  731. if res.Index != tt.wantRes.Index {
  732. t.Errorf("#%d: Index=%d, expected %d", i, res.Index, tt.wantRes.Index)
  733. }
  734. if !reflect.DeepEqual(res.Node, tt.wantRes.Node) {
  735. t.Errorf("#%d: Node=%v, expected %v", i, res.Node, tt.wantRes.Node)
  736. }
  737. }
  738. }
  739. func TestUnmarshalFailedKeysResponse(t *testing.T) {
  740. body := []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`)
  741. wantErr := Error{
  742. Code: 100,
  743. Message: "Key not found",
  744. Cause: "/foo",
  745. Index: uint64(18),
  746. }
  747. gotErr := unmarshalFailedKeysResponse(body)
  748. if !reflect.DeepEqual(wantErr, gotErr) {
  749. t.Errorf("unexpected error: want=%#v got=%#v", wantErr, gotErr)
  750. }
  751. }
  752. func TestUnmarshalFailedKeysResponseBadJSON(t *testing.T) {
  753. err := unmarshalFailedKeysResponse([]byte(`{"er`))
  754. if err == nil {
  755. t.Errorf("got nil error")
  756. } else if _, ok := err.(Error); ok {
  757. t.Errorf("error is of incorrect type *Error: %#v", err)
  758. }
  759. }
  760. func TestHTTPWatcherNextWaitAction(t *testing.T) {
  761. initAction := waitAction{
  762. Prefix: "/pants",
  763. Key: "/foo/bar",
  764. Recursive: true,
  765. WaitIndex: 19,
  766. }
  767. client := &actionAssertingHTTPClient{
  768. t: t,
  769. act: &initAction,
  770. resp: http.Response{
  771. StatusCode: http.StatusOK,
  772. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  773. },
  774. 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}}`),
  775. }
  776. wantResponse := &Response{
  777. Action: "update",
  778. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(21)},
  779. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  780. Index: uint64(42),
  781. }
  782. wantNextWait := waitAction{
  783. Prefix: "/pants",
  784. Key: "/foo/bar",
  785. Recursive: true,
  786. WaitIndex: 22,
  787. }
  788. watcher := &httpWatcher{
  789. client: client,
  790. nextWait: initAction,
  791. }
  792. resp, err := watcher.Next(context.Background())
  793. if err != nil {
  794. t.Errorf("non-nil error: %#v", err)
  795. }
  796. if !reflect.DeepEqual(wantResponse, resp) {
  797. t.Errorf("received incorrect Response: want=%#v got=%#v", wantResponse, resp)
  798. }
  799. if !reflect.DeepEqual(wantNextWait, watcher.nextWait) {
  800. t.Errorf("nextWait incorrect: want=%#v got=%#v", wantNextWait, watcher.nextWait)
  801. }
  802. }
  803. func TestHTTPWatcherNextFail(t *testing.T) {
  804. tests := []httpClient{
  805. // generic HTTP client failure
  806. &staticHTTPClient{
  807. err: errors.New("fail!"),
  808. },
  809. // unusable status code
  810. &staticHTTPClient{
  811. resp: http.Response{
  812. StatusCode: http.StatusTeapot,
  813. },
  814. },
  815. // etcd Error response
  816. &staticHTTPClient{
  817. resp: http.Response{
  818. StatusCode: http.StatusNotFound,
  819. },
  820. body: []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`),
  821. },
  822. }
  823. for i, tt := range tests {
  824. act := waitAction{
  825. Prefix: "/pants",
  826. Key: "/foo/bar",
  827. Recursive: true,
  828. WaitIndex: 19,
  829. }
  830. watcher := &httpWatcher{
  831. client: tt,
  832. nextWait: act,
  833. }
  834. resp, err := watcher.Next(context.Background())
  835. if err == nil {
  836. t.Errorf("#%d: expected non-nil error", i)
  837. }
  838. if resp != nil {
  839. t.Errorf("#%d: expected nil Response, got %#v", i, resp)
  840. }
  841. if !reflect.DeepEqual(act, watcher.nextWait) {
  842. t.Errorf("#%d: nextWait changed: want=%#v got=%#v", i, act, watcher.nextWait)
  843. }
  844. }
  845. }
  846. func TestHTTPKeysAPIWatcherAction(t *testing.T) {
  847. tests := []struct {
  848. key string
  849. opts *WatcherOptions
  850. want waitAction
  851. }{
  852. {
  853. key: "/foo",
  854. opts: nil,
  855. want: waitAction{
  856. Key: "/foo",
  857. Recursive: false,
  858. WaitIndex: 0,
  859. },
  860. },
  861. {
  862. key: "/foo",
  863. opts: &WatcherOptions{
  864. Recursive: false,
  865. AfterIndex: 0,
  866. },
  867. want: waitAction{
  868. Key: "/foo",
  869. Recursive: false,
  870. WaitIndex: 0,
  871. },
  872. },
  873. {
  874. key: "/foo",
  875. opts: &WatcherOptions{
  876. Recursive: true,
  877. AfterIndex: 0,
  878. },
  879. want: waitAction{
  880. Key: "/foo",
  881. Recursive: true,
  882. WaitIndex: 0,
  883. },
  884. },
  885. {
  886. key: "/foo",
  887. opts: &WatcherOptions{
  888. Recursive: false,
  889. AfterIndex: 19,
  890. },
  891. want: waitAction{
  892. Key: "/foo",
  893. Recursive: false,
  894. WaitIndex: 20,
  895. },
  896. },
  897. }
  898. for i, tt := range tests {
  899. testError := errors.New("fail!")
  900. kAPI := &httpKeysAPI{
  901. client: &staticHTTPClient{err: testError},
  902. }
  903. want := &httpWatcher{
  904. client: &staticHTTPClient{err: testError},
  905. nextWait: tt.want,
  906. }
  907. got := kAPI.Watcher(tt.key, tt.opts)
  908. if !reflect.DeepEqual(want, got) {
  909. t.Errorf("#%d: incorrect watcher: want=%#v got=%#v", i, want, got)
  910. }
  911. }
  912. }
  913. func TestHTTPKeysAPISetAction(t *testing.T) {
  914. tests := []struct {
  915. key string
  916. value string
  917. opts *SetOptions
  918. wantAction httpAction
  919. }{
  920. // nil SetOptions
  921. {
  922. key: "/foo",
  923. value: "bar",
  924. opts: nil,
  925. wantAction: &setAction{
  926. Key: "/foo",
  927. Value: "bar",
  928. PrevValue: "",
  929. PrevIndex: 0,
  930. PrevExist: PrevIgnore,
  931. TTL: 0,
  932. },
  933. },
  934. // empty SetOptions
  935. {
  936. key: "/foo",
  937. value: "bar",
  938. opts: &SetOptions{},
  939. wantAction: &setAction{
  940. Key: "/foo",
  941. Value: "bar",
  942. PrevValue: "",
  943. PrevIndex: 0,
  944. PrevExist: PrevIgnore,
  945. TTL: 0,
  946. },
  947. },
  948. // populated SetOptions
  949. {
  950. key: "/foo",
  951. value: "bar",
  952. opts: &SetOptions{
  953. PrevValue: "baz",
  954. PrevIndex: 13,
  955. PrevExist: PrevExist,
  956. TTL: time.Minute,
  957. Dir: true,
  958. },
  959. wantAction: &setAction{
  960. Key: "/foo",
  961. Value: "bar",
  962. PrevValue: "baz",
  963. PrevIndex: 13,
  964. PrevExist: PrevExist,
  965. TTL: time.Minute,
  966. Dir: true,
  967. },
  968. },
  969. }
  970. for i, tt := range tests {
  971. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  972. kAPI := httpKeysAPI{client: client}
  973. kAPI.Set(context.Background(), tt.key, tt.value, tt.opts)
  974. }
  975. }
  976. func TestHTTPKeysAPISetError(t *testing.T) {
  977. tests := []httpClient{
  978. // generic HTTP client failure
  979. &staticHTTPClient{
  980. err: errors.New("fail!"),
  981. },
  982. // unusable status code
  983. &staticHTTPClient{
  984. resp: http.Response{
  985. StatusCode: http.StatusTeapot,
  986. },
  987. },
  988. // etcd Error response
  989. &staticHTTPClient{
  990. resp: http.Response{
  991. StatusCode: http.StatusInternalServerError,
  992. },
  993. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  994. },
  995. }
  996. for i, tt := range tests {
  997. kAPI := httpKeysAPI{client: tt}
  998. resp, err := kAPI.Set(context.Background(), "/foo", "bar", nil)
  999. if err == nil {
  1000. t.Errorf("#%d: received nil error", i)
  1001. }
  1002. if resp != nil {
  1003. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1004. }
  1005. }
  1006. }
  1007. func TestHTTPKeysAPISetResponse(t *testing.T) {
  1008. client := &staticHTTPClient{
  1009. resp: http.Response{
  1010. StatusCode: http.StatusOK,
  1011. Header: http.Header{"X-Etcd-Index": []string{"21"}},
  1012. },
  1013. 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}}`),
  1014. }
  1015. wantResponse := &Response{
  1016. Action: "set",
  1017. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(21), ModifiedIndex: uint64(21)},
  1018. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  1019. Index: uint64(21),
  1020. }
  1021. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1022. resp, err := kAPI.Set(context.Background(), "/foo/bar/baz", "snarf", nil)
  1023. if err != nil {
  1024. t.Errorf("non-nil error: %#v", err)
  1025. }
  1026. if !reflect.DeepEqual(wantResponse, resp) {
  1027. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1028. }
  1029. }
  1030. func TestHTTPKeysAPIGetAction(t *testing.T) {
  1031. tests := []struct {
  1032. key string
  1033. opts *GetOptions
  1034. wantAction httpAction
  1035. }{
  1036. // nil GetOptions
  1037. {
  1038. key: "/foo",
  1039. opts: nil,
  1040. wantAction: &getAction{
  1041. Key: "/foo",
  1042. Sorted: false,
  1043. Recursive: false,
  1044. },
  1045. },
  1046. // empty GetOptions
  1047. {
  1048. key: "/foo",
  1049. opts: &GetOptions{},
  1050. wantAction: &getAction{
  1051. Key: "/foo",
  1052. Sorted: false,
  1053. Recursive: false,
  1054. },
  1055. },
  1056. // populated GetOptions
  1057. {
  1058. key: "/foo",
  1059. opts: &GetOptions{
  1060. Sort: true,
  1061. Recursive: true,
  1062. Quorum: true,
  1063. },
  1064. wantAction: &getAction{
  1065. Key: "/foo",
  1066. Sorted: true,
  1067. Recursive: true,
  1068. Quorum: true,
  1069. },
  1070. },
  1071. }
  1072. for i, tt := range tests {
  1073. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1074. kAPI := httpKeysAPI{client: client}
  1075. kAPI.Get(context.Background(), tt.key, tt.opts)
  1076. }
  1077. }
  1078. func TestHTTPKeysAPIGetError(t *testing.T) {
  1079. tests := []httpClient{
  1080. // generic HTTP client failure
  1081. &staticHTTPClient{
  1082. err: errors.New("fail!"),
  1083. },
  1084. // unusable status code
  1085. &staticHTTPClient{
  1086. resp: http.Response{
  1087. StatusCode: http.StatusTeapot,
  1088. },
  1089. },
  1090. // etcd Error response
  1091. &staticHTTPClient{
  1092. resp: http.Response{
  1093. StatusCode: http.StatusInternalServerError,
  1094. },
  1095. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1096. },
  1097. }
  1098. for i, tt := range tests {
  1099. kAPI := httpKeysAPI{client: tt}
  1100. resp, err := kAPI.Get(context.Background(), "/foo", nil)
  1101. if err == nil {
  1102. t.Errorf("#%d: received nil error", i)
  1103. }
  1104. if resp != nil {
  1105. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1106. }
  1107. }
  1108. }
  1109. func TestHTTPKeysAPIGetResponse(t *testing.T) {
  1110. client := &staticHTTPClient{
  1111. resp: http.Response{
  1112. StatusCode: http.StatusOK,
  1113. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  1114. },
  1115. 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}]}}`),
  1116. }
  1117. wantResponse := &Response{
  1118. Action: "get",
  1119. Node: &Node{
  1120. Key: "/pants/foo/bar",
  1121. Nodes: []*Node{
  1122. {Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: 21, ModifiedIndex: 25},
  1123. },
  1124. CreatedIndex: uint64(19),
  1125. ModifiedIndex: uint64(25),
  1126. },
  1127. Index: uint64(42),
  1128. }
  1129. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1130. resp, err := kAPI.Get(context.Background(), "/foo/bar", &GetOptions{Recursive: true})
  1131. if err != nil {
  1132. t.Errorf("non-nil error: %#v", err)
  1133. }
  1134. if !reflect.DeepEqual(wantResponse, resp) {
  1135. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1136. }
  1137. }
  1138. func TestHTTPKeysAPIDeleteAction(t *testing.T) {
  1139. tests := []struct {
  1140. key string
  1141. opts *DeleteOptions
  1142. wantAction httpAction
  1143. }{
  1144. // nil DeleteOptions
  1145. {
  1146. key: "/foo",
  1147. opts: nil,
  1148. wantAction: &deleteAction{
  1149. Key: "/foo",
  1150. PrevValue: "",
  1151. PrevIndex: 0,
  1152. Recursive: false,
  1153. },
  1154. },
  1155. // empty DeleteOptions
  1156. {
  1157. key: "/foo",
  1158. opts: &DeleteOptions{},
  1159. wantAction: &deleteAction{
  1160. Key: "/foo",
  1161. PrevValue: "",
  1162. PrevIndex: 0,
  1163. Recursive: false,
  1164. },
  1165. },
  1166. // populated DeleteOptions
  1167. {
  1168. key: "/foo",
  1169. opts: &DeleteOptions{
  1170. PrevValue: "baz",
  1171. PrevIndex: 13,
  1172. Recursive: true,
  1173. },
  1174. wantAction: &deleteAction{
  1175. Key: "/foo",
  1176. PrevValue: "baz",
  1177. PrevIndex: 13,
  1178. Recursive: true,
  1179. },
  1180. },
  1181. }
  1182. for i, tt := range tests {
  1183. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1184. kAPI := httpKeysAPI{client: client}
  1185. kAPI.Delete(context.Background(), tt.key, tt.opts)
  1186. }
  1187. }
  1188. func TestHTTPKeysAPIDeleteError(t *testing.T) {
  1189. tests := []httpClient{
  1190. // generic HTTP client failure
  1191. &staticHTTPClient{
  1192. err: errors.New("fail!"),
  1193. },
  1194. // unusable status code
  1195. &staticHTTPClient{
  1196. resp: http.Response{
  1197. StatusCode: http.StatusTeapot,
  1198. },
  1199. },
  1200. // etcd Error response
  1201. &staticHTTPClient{
  1202. resp: http.Response{
  1203. StatusCode: http.StatusInternalServerError,
  1204. },
  1205. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1206. },
  1207. }
  1208. for i, tt := range tests {
  1209. kAPI := httpKeysAPI{client: tt}
  1210. resp, err := kAPI.Delete(context.Background(), "/foo", nil)
  1211. if err == nil {
  1212. t.Errorf("#%d: received nil error", i)
  1213. }
  1214. if resp != nil {
  1215. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1216. }
  1217. }
  1218. }
  1219. func TestHTTPKeysAPIDeleteResponse(t *testing.T) {
  1220. client := &staticHTTPClient{
  1221. resp: http.Response{
  1222. StatusCode: http.StatusOK,
  1223. Header: http.Header{"X-Etcd-Index": []string{"22"}},
  1224. },
  1225. 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}}`),
  1226. }
  1227. wantResponse := &Response{
  1228. Action: "delete",
  1229. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(22)},
  1230. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  1231. Index: uint64(22),
  1232. }
  1233. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1234. resp, err := kAPI.Delete(context.Background(), "/foo/bar/baz", nil)
  1235. if err != nil {
  1236. t.Errorf("non-nil error: %#v", err)
  1237. }
  1238. if !reflect.DeepEqual(wantResponse, resp) {
  1239. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1240. }
  1241. }
  1242. func TestHTTPKeysAPICreateAction(t *testing.T) {
  1243. act := &setAction{
  1244. Key: "/foo",
  1245. Value: "bar",
  1246. PrevExist: PrevNoExist,
  1247. PrevIndex: 0,
  1248. PrevValue: "",
  1249. TTL: 0,
  1250. }
  1251. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1252. kAPI.Create(context.Background(), "/foo", "bar")
  1253. }
  1254. func TestHTTPKeysAPICreateInOrderAction(t *testing.T) {
  1255. act := &createInOrderAction{
  1256. Dir: "/foo",
  1257. Value: "bar",
  1258. TTL: 0,
  1259. }
  1260. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1261. kAPI.CreateInOrder(context.Background(), "/foo", "bar", nil)
  1262. }
  1263. func TestHTTPKeysAPIUpdateAction(t *testing.T) {
  1264. act := &setAction{
  1265. Key: "/foo",
  1266. Value: "bar",
  1267. PrevExist: PrevExist,
  1268. PrevIndex: 0,
  1269. PrevValue: "",
  1270. TTL: 0,
  1271. }
  1272. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1273. kAPI.Update(context.Background(), "/foo", "bar")
  1274. }
  1275. func TestNodeTTLDuration(t *testing.T) {
  1276. tests := []struct {
  1277. node *Node
  1278. want time.Duration
  1279. }{
  1280. {
  1281. node: &Node{TTL: 0},
  1282. want: 0,
  1283. },
  1284. {
  1285. node: &Node{TTL: 97},
  1286. want: 97 * time.Second,
  1287. },
  1288. }
  1289. for i, tt := range tests {
  1290. got := tt.node.TTLDuration()
  1291. if tt.want != got {
  1292. t.Errorf("#%d: incorrect duration: want=%v got=%v", i, tt.want, got)
  1293. }
  1294. }
  1295. }